diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..6156cee Binary files /dev/null and b/.DS_Store differ diff --git a/DiplomProject/DiplomProject.xcodeproj/project.pbxproj b/DiplomProject/DiplomProject.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4f8c5cc --- /dev/null +++ b/DiplomProject/DiplomProject.xcodeproj/project.pbxproj @@ -0,0 +1,509 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 51; + objects = { + +/* Begin PBXBuildFile section */ + 0ECA698405B87A0BD2FD12D9 /* Pods_DiplomProject.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CA5F7B1A9BB503CCC596D78F /* Pods_DiplomProject.framework */; }; + 3309EBD023EB0012009C51E3 /* ExcenseScreenViewConroller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3309EBCF23EB0012009C51E3 /* ExcenseScreenViewConroller.swift */; }; + 330E009823EAD39600664CA2 /* MainScreenViewController+Alert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 330E009723EAD39600664CA2 /* MainScreenViewController+Alert.swift */; }; + 3310221323EB056800541354 /* ExcenseScreenViewConroller + Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3310221223EB056800541354 /* ExcenseScreenViewConroller + Alerts.swift */; }; + 3342A96323EAEC8E004D3C0C /* ChartExpenseIncomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3342A96223EAEC8E004D3C0C /* ChartExpenseIncomeViewController.swift */; }; + 3342A96523EAF796004D3C0C /* TransactionTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3342A96423EAF796004D3C0C /* TransactionTableViewCell.swift */; }; + 33ACA5D223EAB3E5003689D6 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5D123EAB3E4003689D6 /* Persistence.swift */; }; + 33ACA5D423EAB99D003689D6 /* Transaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5D323EAB99D003689D6 /* Transaction.swift */; }; + 33ACA5DB23EABBBD003689D6 /* Income.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5DA23EABBBD003689D6 /* Income.swift */; }; + 33ACA5DD23EABC34003689D6 /* Expense.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5DC23EABC34003689D6 /* Expense.swift */; }; + 33ACA5DF23EABCC3003689D6 /* ExpenseCategory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5DE23EABCC3003689D6 /* ExpenseCategory.swift */; }; + 33ACA5E123EAC32E003689D6 /* ExcensesCategoryTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5E023EAC32E003689D6 /* ExcensesCategoryTableViewCell.swift */; }; + 33ACA5E323EAC512003689D6 /* MainScreenViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5E223EAC512003689D6 /* MainScreenViewController.swift */; }; + 33ACA5E623EACC08003689D6 /* DefaultButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACA5E523EACC08003689D6 /* DefaultButton.swift */; }; + 33AE031823EAB0E00063D96F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33AE031723EAB0E00063D96F /* AppDelegate.swift */; }; + 33AE031A23EAB0E00063D96F /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33AE031923EAB0E00063D96F /* SceneDelegate.swift */; }; + 33AE031F23EAB0E00063D96F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33AE031D23EAB0E00063D96F /* Main.storyboard */; }; + 33AE032123EAB0E90063D96F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33AE032023EAB0E90063D96F /* Assets.xcassets */; }; + 33AE032423EAB0E90063D96F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33AE032223EAB0E90063D96F /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 3309EBCF23EB0012009C51E3 /* ExcenseScreenViewConroller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExcenseScreenViewConroller.swift; sourceTree = ""; }; + 330E009723EAD39600664CA2 /* MainScreenViewController+Alert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MainScreenViewController+Alert.swift"; sourceTree = ""; }; + 3310221223EB056800541354 /* ExcenseScreenViewConroller + Alerts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ExcenseScreenViewConroller + Alerts.swift"; sourceTree = ""; }; + 3342A96223EAEC8E004D3C0C /* ChartExpenseIncomeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChartExpenseIncomeViewController.swift; sourceTree = ""; }; + 3342A96423EAF796004D3C0C /* TransactionTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionTableViewCell.swift; sourceTree = ""; }; + 33ACA5D123EAB3E4003689D6 /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; + 33ACA5D323EAB99D003689D6 /* Transaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Transaction.swift; sourceTree = ""; }; + 33ACA5DA23EABBBD003689D6 /* Income.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Income.swift; sourceTree = ""; }; + 33ACA5DC23EABC34003689D6 /* Expense.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Expense.swift; sourceTree = ""; }; + 33ACA5DE23EABCC3003689D6 /* ExpenseCategory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExpenseCategory.swift; sourceTree = ""; }; + 33ACA5E023EAC32E003689D6 /* ExcensesCategoryTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExcensesCategoryTableViewCell.swift; sourceTree = ""; }; + 33ACA5E223EAC512003689D6 /* MainScreenViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainScreenViewController.swift; sourceTree = ""; }; + 33ACA5E523EACC08003689D6 /* DefaultButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultButton.swift; sourceTree = ""; }; + 33AE031423EAB0E00063D96F /* DiplomProject.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiplomProject.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33AE031723EAB0E00063D96F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33AE031923EAB0E00063D96F /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 33AE031E23EAB0E00063D96F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 33AE032023EAB0E90063D96F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 33AE032323EAB0E90063D96F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 33AE032523EAB0E90063D96F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A6EE0BCA1391491436C7DE5E /* Pods-DiplomProject.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-DiplomProject.debug.xcconfig"; path = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject.debug.xcconfig"; sourceTree = ""; }; + CA5F7B1A9BB503CCC596D78F /* Pods_DiplomProject.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_DiplomProject.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + DCF7EE9F1987319D5189B4E0 /* Pods-DiplomProject.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-DiplomProject.release.xcconfig"; path = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 33AE031123EAB0E00063D96F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0ECA698405B87A0BD2FD12D9 /* Pods_DiplomProject.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 3309EBCE23EAFFE0009C51E3 /* ExcenseScreenViewConroller */ = { + isa = PBXGroup; + children = ( + 3309EBCF23EB0012009C51E3 /* ExcenseScreenViewConroller.swift */, + 3310221223EB056800541354 /* ExcenseScreenViewConroller + Alerts.swift */, + ); + path = ExcenseScreenViewConroller; + sourceTree = ""; + }; + 330E009623EAD36900664CA2 /* MainScreen */ = { + isa = PBXGroup; + children = ( + 33ACA5E223EAC512003689D6 /* MainScreenViewController.swift */, + 330E009723EAD39600664CA2 /* MainScreenViewController+Alert.swift */, + ); + path = MainScreen; + sourceTree = ""; + }; + 3342A96123EAEC43004D3C0C /* ChartExpenseIncome */ = { + isa = PBXGroup; + children = ( + 3342A96223EAEC8E004D3C0C /* ChartExpenseIncomeViewController.swift */, + ); + path = ChartExpenseIncome; + sourceTree = ""; + }; + 33ACA5D023EAB3BE003689D6 /* Entity */ = { + isa = PBXGroup; + children = ( + 33ACA5D323EAB99D003689D6 /* Transaction.swift */, + 33ACA5DA23EABBBD003689D6 /* Income.swift */, + 33ACA5DC23EABC34003689D6 /* Expense.swift */, + 33ACA5DE23EABCC3003689D6 /* ExpenseCategory.swift */, + ); + path = Entity; + sourceTree = ""; + }; + 33ACA5D723EABAC6003689D6 /* Extensions */ = { + isa = PBXGroup; + children = ( + ); + path = Extensions; + sourceTree = ""; + }; + 33ACA5E423EACBE4003689D6 /* CustomView */ = { + isa = PBXGroup; + children = ( + 33ACA5E523EACC08003689D6 /* DefaultButton.swift */, + ); + path = CustomView; + sourceTree = ""; + }; + 33AE030B23EAB0E00063D96F = { + isa = PBXGroup; + children = ( + 33AE031623EAB0E00063D96F /* DiplomProject */, + 33AE031523EAB0E00063D96F /* Products */, + CB9FC0FFCF32756ED69CB060 /* Pods */, + 49293801E63129163FD7C3FB /* Frameworks */, + ); + sourceTree = ""; + }; + 33AE031523EAB0E00063D96F /* Products */ = { + isa = PBXGroup; + children = ( + 33AE031423EAB0E00063D96F /* DiplomProject.app */, + ); + name = Products; + sourceTree = ""; + }; + 33AE031623EAB0E00063D96F /* DiplomProject */ = { + isa = PBXGroup; + children = ( + 3309EBCE23EAFFE0009C51E3 /* ExcenseScreenViewConroller */, + 3342A96123EAEC43004D3C0C /* ChartExpenseIncome */, + 330E009623EAD36900664CA2 /* MainScreen */, + 33ACA5E423EACBE4003689D6 /* CustomView */, + 33ACA5D723EABAC6003689D6 /* Extensions */, + 33ACA5D023EAB3BE003689D6 /* Entity */, + 33AE031723EAB0E00063D96F /* AppDelegate.swift */, + 33AE031923EAB0E00063D96F /* SceneDelegate.swift */, + 33AE031D23EAB0E00063D96F /* Main.storyboard */, + 33AE032023EAB0E90063D96F /* Assets.xcassets */, + 33AE032223EAB0E90063D96F /* LaunchScreen.storyboard */, + 33AE032523EAB0E90063D96F /* Info.plist */, + 33ACA5D123EAB3E4003689D6 /* Persistence.swift */, + 33ACA5E023EAC32E003689D6 /* ExcensesCategoryTableViewCell.swift */, + 3342A96423EAF796004D3C0C /* TransactionTableViewCell.swift */, + ); + path = DiplomProject; + sourceTree = ""; + }; + 49293801E63129163FD7C3FB /* Frameworks */ = { + isa = PBXGroup; + children = ( + CA5F7B1A9BB503CCC596D78F /* Pods_DiplomProject.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + CB9FC0FFCF32756ED69CB060 /* Pods */ = { + isa = PBXGroup; + children = ( + A6EE0BCA1391491436C7DE5E /* Pods-DiplomProject.debug.xcconfig */, + DCF7EE9F1987319D5189B4E0 /* Pods-DiplomProject.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 33AE031323EAB0E00063D96F /* DiplomProject */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33AE032823EAB0E90063D96F /* Build configuration list for PBXNativeTarget "DiplomProject" */; + buildPhases = ( + BF66311C6E93A123B67AE9D0 /* [CP] Check Pods Manifest.lock */, + 33AE031023EAB0E00063D96F /* Sources */, + 33AE031123EAB0E00063D96F /* Frameworks */, + 33AE031223EAB0E00063D96F /* Resources */, + 5C651D027E2797B59A7298E2 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = DiplomProject; + productName = DiplomProject; + productReference = 33AE031423EAB0E00063D96F /* DiplomProject.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33AE030C23EAB0E00063D96F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1130; + LastUpgradeCheck = 1130; + ORGANIZATIONNAME = "Михаил Беленко"; + TargetAttributes = { + 33AE031323EAB0E00063D96F = { + CreatedOnToolsVersion = 11.3.1; + }; + }; + }; + buildConfigurationList = 33AE030F23EAB0E00063D96F /* Build configuration list for PBXProject "DiplomProject" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33AE030B23EAB0E00063D96F; + productRefGroup = 33AE031523EAB0E00063D96F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33AE031323EAB0E00063D96F /* DiplomProject */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 33AE031223EAB0E00063D96F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33AE032423EAB0E90063D96F /* LaunchScreen.storyboard in Resources */, + 33AE032123EAB0E90063D96F /* Assets.xcassets in Resources */, + 33AE031F23EAB0E00063D96F /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 5C651D027E2797B59A7298E2 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + BF66311C6E93A123B67AE9D0 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-DiplomProject-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 33AE031023EAB0E00063D96F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33ACA5DD23EABC34003689D6 /* Expense.swift in Sources */, + 3342A96323EAEC8E004D3C0C /* ChartExpenseIncomeViewController.swift in Sources */, + 330E009823EAD39600664CA2 /* MainScreenViewController+Alert.swift in Sources */, + 33ACA5D223EAB3E5003689D6 /* Persistence.swift in Sources */, + 33AE031823EAB0E00063D96F /* AppDelegate.swift in Sources */, + 33ACA5E123EAC32E003689D6 /* ExcensesCategoryTableViewCell.swift in Sources */, + 3309EBD023EB0012009C51E3 /* ExcenseScreenViewConroller.swift in Sources */, + 3342A96523EAF796004D3C0C /* TransactionTableViewCell.swift in Sources */, + 33AE031A23EAB0E00063D96F /* SceneDelegate.swift in Sources */, + 33ACA5E623EACC08003689D6 /* DefaultButton.swift in Sources */, + 33ACA5DB23EABBBD003689D6 /* Income.swift in Sources */, + 3310221323EB056800541354 /* ExcenseScreenViewConroller + Alerts.swift in Sources */, + 33ACA5DF23EABCC3003689D6 /* ExpenseCategory.swift in Sources */, + 33ACA5D423EAB99D003689D6 /* Transaction.swift in Sources */, + 33ACA5E323EAC512003689D6 /* MainScreenViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 33AE031D23EAB0E00063D96F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 33AE031E23EAB0E00063D96F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 33AE032223EAB0E90063D96F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 33AE032323EAB0E90063D96F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 33AE032623EAB0E90063D96F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33AE032723EAB0E90063D96F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 33AE032923EAB0E90063D96F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A6EE0BCA1391491436C7DE5E /* Pods-DiplomProject.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 8374DGJ7W4; + INFOPLIST_FILE = DiplomProject/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.DiplomProject; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 33AE032A23EAB0E90063D96F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DCF7EE9F1987319D5189B4E0 /* Pods-DiplomProject.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = 8374DGJ7W4; + INFOPLIST_FILE = DiplomProject/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.DiplomProject; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 33AE030F23EAB0E00063D96F /* Build configuration list for PBXProject "DiplomProject" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33AE032623EAB0E90063D96F /* Debug */, + 33AE032723EAB0E90063D96F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33AE032823EAB0E90063D96F /* Build configuration list for PBXNativeTarget "DiplomProject" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33AE032923EAB0E90063D96F /* Debug */, + 33AE032A23EAB0E90063D96F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33AE030C23EAB0E00063D96F /* Project object */; +} diff --git a/Lesson11/Lesson11.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/DiplomProject/DiplomProject.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 68% rename from Lesson11/Lesson11.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to DiplomProject/DiplomProject.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 11ea237..88d82aa 100644 --- a/Lesson11/Lesson11.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/DiplomProject/DiplomProject.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:DiplomProject.xcodeproj"> diff --git a/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/DiplomProject/DiplomProject.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to DiplomProject/DiplomProject.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/Lesson12/Lesson12.xcworkspace/contents.xcworkspacedata b/DiplomProject/DiplomProject.xcworkspace/contents.xcworkspacedata similarity index 78% rename from Lesson12/Lesson12.xcworkspace/contents.xcworkspacedata rename to DiplomProject/DiplomProject.xcworkspace/contents.xcworkspacedata index 244f16d..2be5e88 100644 --- a/Lesson12/Lesson12.xcworkspace/contents.xcworkspacedata +++ b/DiplomProject/DiplomProject.xcworkspace/contents.xcworkspacedata @@ -2,7 +2,7 @@ + location = "group:DiplomProject.xcodeproj"> diff --git a/Lesson10/Lesson10Task1/Lesson10Task1.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/DiplomProject/DiplomProject.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to DiplomProject/DiplomProject.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/Lesson13/Lesson13/AppDelegate.swift b/DiplomProject/DiplomProject/AppDelegate.swift similarity index 94% rename from Lesson13/Lesson13/AppDelegate.swift rename to DiplomProject/DiplomProject/AppDelegate.swift index 10cf7ec..a5eae6b 100644 --- a/Lesson13/Lesson13/AppDelegate.swift +++ b/DiplomProject/DiplomProject/AppDelegate.swift @@ -1,8 +1,8 @@ // // AppDelegate.swift -// Lesson13 +// DiplomProject // -// Created by Михаил Беленко on 03.02.2020. +// Created by Михаил Беленко on 05.02.2020. // Copyright © 2020 Михаил Беленко. All rights reserved. // diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/AppIcon.appiconset/Contents.json b/DiplomProject/DiplomProject/Assets 2.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/AppIcon.appiconset/Contents.json rename to DiplomProject/DiplomProject/Assets 2.xcassets/AppIcon.appiconset/Contents.json diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/Contents.json b/DiplomProject/DiplomProject/Assets 2.xcassets/Contents.json similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/Contents.json rename to DiplomProject/DiplomProject/Assets 2.xcassets/Contents.json diff --git a/Lesson11/Lesson11/Assets.xcassets/AppIcon.appiconset/Contents.json b/DiplomProject/DiplomProject/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from Lesson11/Lesson11/Assets.xcassets/AppIcon.appiconset/Contents.json rename to DiplomProject/DiplomProject/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/Contents.json b/DiplomProject/DiplomProject/Assets.xcassets/Contents.json similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/Contents.json rename to DiplomProject/DiplomProject/Assets.xcassets/Contents.json diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Base.lproj/LaunchScreen.storyboard b/DiplomProject/DiplomProject/Base.lproj/LaunchScreen.storyboard similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1/Base.lproj/LaunchScreen.storyboard rename to DiplomProject/DiplomProject/Base.lproj/LaunchScreen.storyboard diff --git a/DiplomProject/DiplomProject/Base.lproj/Main.storyboard b/DiplomProject/DiplomProject/Base.lproj/Main.storyboard new file mode 100644 index 0000000..37275aa --- /dev/null +++ b/DiplomProject/DiplomProject/Base.lproj/Main.storyboard @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DiplomProject/DiplomProject/ChartExpenseIncome/ChartExpenseIncomeViewController.swift b/DiplomProject/DiplomProject/ChartExpenseIncome/ChartExpenseIncomeViewController.swift new file mode 100644 index 0000000..7c66bee --- /dev/null +++ b/DiplomProject/DiplomProject/ChartExpenseIncome/ChartExpenseIncomeViewController.swift @@ -0,0 +1,43 @@ +// +// ChartExpenseIncomeViewController.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import DTTableViewManager + +class ChartExpenseIncomeViewController: UIViewController, DTTableViewManageable { + + @IBOutlet weak var tableView: UITableView! + @IBOutlet weak var segmentedControl: UISegmentedControl! + + override func viewDidLoad() { + super.viewDidLoad() + + setupUI() + manager.register(TransactionTableViewCell.self) + changeSegmen(self) + } + + private func setupUI() { + navigationItem.title = "График расходов/доходов" + } + + @IBAction func changeSegmen(_ sender: Any) { + switch segmentedControl.selectedSegmentIndex { + case 0: + manager.memoryStorage.setItems(Persistence.storage.getTransactionFromPeriod(with: Calendar.current.date(byAdding: .weekOfYear, value: -1, to: Date())!)) + case 1: + manager.memoryStorage.setItems(Persistence.storage.getTransactionFromPeriod(with: Calendar.current.date(byAdding: .month, value: -1, to: Date())!)) + case 2: + manager.memoryStorage.setItems(Persistence.storage.getTransactionFromPeriod(with: Calendar.current.date(byAdding: .month, value: -3, to: Date())!)) + case 3: + manager.memoryStorage.setItems(Persistence.storage.getTransactionFromPeriod(with: Date.init(timeIntervalSince1970: 0))) + default: + fatalError("imposible") + } + } +} diff --git a/DiplomProject/DiplomProject/CustomView/DefaultButton.swift b/DiplomProject/DiplomProject/CustomView/DefaultButton.swift new file mode 100644 index 0000000..ac1eadf --- /dev/null +++ b/DiplomProject/DiplomProject/CustomView/DefaultButton.swift @@ -0,0 +1,27 @@ +// +// DefaultButton.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit + +class DefaultButton: UIButton { + private var isSetuped = false + + override func layoutSubviews() { + super.layoutSubviews() + + if isSetuped { return } + isSetuped = true + + setTitleColor(.white, for: .normal) + + backgroundColor = .systemBlue + layer.cornerRadius = 10 + contentHorizontalAlignment = .center + contentVerticalAlignment = .center + } +} diff --git a/DiplomProject/DiplomProject/Entity/Expense.swift b/DiplomProject/DiplomProject/Entity/Expense.swift new file mode 100644 index 0000000..7269a0f --- /dev/null +++ b/DiplomProject/DiplomProject/Entity/Expense.swift @@ -0,0 +1,16 @@ +// +// Expense.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import RealmSwift +import Foundation + +class Expense: Object, Transaction { + @objc dynamic var value: Float = 0.0 + @objc dynamic var date: Date = Date() + @objc dynamic var category: ExpenseCategory? +} diff --git a/DiplomProject/DiplomProject/Entity/ExpenseCategory.swift b/DiplomProject/DiplomProject/Entity/ExpenseCategory.swift new file mode 100644 index 0000000..cb813e9 --- /dev/null +++ b/DiplomProject/DiplomProject/Entity/ExpenseCategory.swift @@ -0,0 +1,14 @@ +// +// ExpenseCategory.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import RealmSwift + +class ExpenseCategory: Object { + @objc dynamic var name: String = "" + let expensesList = List() +} diff --git a/DiplomProject/DiplomProject/Entity/Income.swift b/DiplomProject/DiplomProject/Entity/Income.swift new file mode 100644 index 0000000..35a7037 --- /dev/null +++ b/DiplomProject/DiplomProject/Entity/Income.swift @@ -0,0 +1,15 @@ +// +// Income.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import RealmSwift +import Foundation + +class Income: Object, Transaction { + @objc dynamic var value: Float = 0.0 + @objc dynamic var date: Date = Date() +} diff --git a/DiplomProject/DiplomProject/Entity/Transaction.swift b/DiplomProject/DiplomProject/Entity/Transaction.swift new file mode 100644 index 0000000..5a704c2 --- /dev/null +++ b/DiplomProject/DiplomProject/Entity/Transaction.swift @@ -0,0 +1,14 @@ +// +// Transaction.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import Foundation + +protocol Transaction { + var value: Float { get set } + var date: Date { get } +} diff --git a/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller + Alerts.swift b/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller + Alerts.swift new file mode 100644 index 0000000..7965cd5 --- /dev/null +++ b/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller + Alerts.swift @@ -0,0 +1,46 @@ +// +// ExcenseScreenViewConroller + Alerts.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit + +extension ExcenseScreenViewConroller { + + func showAddExcenseAlert() { + + let alert = UIAlertController(title: "Добавление расхода", message: "Введите сумму расхода", preferredStyle: .alert) + + alert.addTextField() + let textField = alert.textFields![0] // Force unwrapping because we know it exists. + + let saveAction = UIAlertAction(title: "OK", style: .default, handler: { [unowned self] (_) in + let expense = Expense() + expense.value = Float(textField.text!)! + Persistence.storage.addExpenseInCategory(expense: expense, nameCategory: self.nameCategory) + self.manager.memoryStorage.addItem(expense) + }) + + let cancelAction = UIAlertAction(title: "Отмена", + style: .default) { (action: UIAlertAction!) -> Void in + } + + textField.rx.text.subscribe(onNext: { text in + if let text = text, let value = Float(text), !text.isEmpty && value > 0 { + saveAction.isEnabled = true + } + else { + saveAction.isEnabled = false + } + }).disposed(by: disposeBag) + + alert.addAction(saveAction) + alert.addAction(cancelAction) + + + self.present(alert, animated: true, completion: nil) + } +} diff --git a/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller.swift b/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller.swift new file mode 100644 index 0000000..83192f8 --- /dev/null +++ b/DiplomProject/DiplomProject/ExcenseScreenViewConroller/ExcenseScreenViewConroller.swift @@ -0,0 +1,56 @@ +// +// ExcenseScreenViewConroller.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import DTTableViewManager +import RxSwift +import RxCocoa + +class ExcenseScreenViewConroller: UIViewController, DTTableViewManageable { + + var disposeBag = DisposeBag() + + @IBOutlet weak var tableView: UITableView! + + private lazy var addExcenseView: UIView = { + let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 70)) + let button = DefaultButton() + button.setTitle("Добавить расход", for: .normal) + + button.rx.controlEvent(.touchUpInside).subscribe(onNext: { [unowned self] _ in + self.showAddExcenseAlert() + }).disposed(by: disposeBag) + + view.addSubview(button) + + button.snp.makeConstraints { make in + make.edges.equalToSuperview().inset(16) + } + + return view + }() + + var nameCategory: String! + + override func viewDidLoad() { + super.viewDidLoad() + + manager.register(TransactionTableViewCell.self) + setupUI() + configureTableView() + manager.memoryStorage.setItems(Persistence.storage.getExpensesFromCategory(nameCategory: nameCategory)) + } + + private func setupUI() { + navigationItem.title = nameCategory + } + + private func configureTableView() { + tableView.tableFooterView = addExcenseView + } +} diff --git a/DiplomProject/DiplomProject/ExcensesCategoryTableViewCell.swift b/DiplomProject/DiplomProject/ExcensesCategoryTableViewCell.swift new file mode 100644 index 0000000..551f7d5 --- /dev/null +++ b/DiplomProject/DiplomProject/ExcensesCategoryTableViewCell.swift @@ -0,0 +1,57 @@ +// +// ExcensesCategoryTableViewCell.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import DTModelStorage +import SnapKit + +class ExcensesCategoryTableViewCell: UITableViewCell, ModelTransfer { + typealias ModelType = ExpenseCategory + + private lazy var nameLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .medium) + label.textColor = .systemBlue + return label + }() + + private lazy var expensesSumLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .regular) + label.textColor = .systemRed + return label + }() + + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + + contentView.addSubview(nameLabel) + contentView.addSubview(expensesSumLabel) + setupConstraints() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(with model: ExpenseCategory) { + nameLabel.text = model.name + expensesSumLabel.text = "-\(model.expensesList.reduce(0, { $0 + $1.value })) ₽" + } + + private func setupConstraints() { + nameLabel.snp.makeConstraints { make in + make.top.bottom.leading.equalToSuperview().inset(16) + } + + expensesSumLabel.snp.makeConstraints { make in + make.leading.equalTo(nameLabel.snp.trailing).offset(8) + make.top.bottom.trailing.equalToSuperview().inset(16) + } + } +} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Info.plist b/DiplomProject/DiplomProject/Info.plist similarity index 100% rename from Lesson10/Lesson10Task1/Lesson10Task1/Info.plist rename to DiplomProject/DiplomProject/Info.plist diff --git a/DiplomProject/DiplomProject/MainScreen/MainScreenViewController+Alert.swift b/DiplomProject/DiplomProject/MainScreen/MainScreenViewController+Alert.swift new file mode 100644 index 0000000..2aff2f6 --- /dev/null +++ b/DiplomProject/DiplomProject/MainScreen/MainScreenViewController+Alert.swift @@ -0,0 +1,82 @@ +// +// MainScreenViewController+Alert.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import RxSwift +import RxCocoa + +extension MainScreenViewController { + + func showAddCategotyAlert() { + + let alert = UIAlertController(title: "Добавление категории расходов", message: "Введите название категории", preferredStyle: .alert) + + alert.addTextField() + let textField = alert.textFields![0] // Force unwrapping because we know it exists. + + let saveAction = UIAlertAction(title: "OK", style: .default, handler: { [unowned self] (_) in + let category = ExpenseCategory() + category.name = textField.text! + Persistence.storage.addCategoryExpense(category: category) + self.manager.memoryStorage.addItem(category) + }) + + let cancelAction = UIAlertAction(title: "Отмена", + style: .default) { (action: UIAlertAction!) -> Void in + } + + textField.rx.text.subscribe(onNext: { text in + if let text = text, !text.isEmpty { + saveAction.isEnabled = true + } + else { + saveAction.isEnabled = false + } + }).disposed(by: disposeBag) + + alert.addAction(saveAction) + alert.addAction(cancelAction) + + + self.present(alert, animated: true, completion: nil) + } + + func showAddIncomeAlert() { + + let alert = UIAlertController(title: "Добавление дохода", message: "Введите сумму дохода", preferredStyle: .alert) + + alert.addTextField() + let textField = alert.textFields![0] // Force unwrapping because we know it exists. + + let saveAction = UIAlertAction(title: "OK", style: .default, handler: { [unowned self] (_) in + let income = Income() + income.value = Float(textField.text!)! + Persistence.storage.addIncome(income: income) + self.balanceLabel.text = "\(Persistence.storage.getBalance()) ₽" + }) + + let cancelAction = UIAlertAction(title: "Отмена", + style: .default) { (action: UIAlertAction!) -> Void in + } + + textField.rx.text.subscribe(onNext: { text in + if let text = text, let value = Float(text), !text.isEmpty && value > 0 { + saveAction.isEnabled = true + } + else { + saveAction.isEnabled = false + } + }).disposed(by: disposeBag) + + alert.addAction(saveAction) + alert.addAction(cancelAction) + + + self.present(alert, animated: true, completion: nil) + } +} diff --git a/DiplomProject/DiplomProject/MainScreen/MainScreenViewController.swift b/DiplomProject/DiplomProject/MainScreen/MainScreenViewController.swift new file mode 100644 index 0000000..3928edb --- /dev/null +++ b/DiplomProject/DiplomProject/MainScreen/MainScreenViewController.swift @@ -0,0 +1,92 @@ +// +// MainScreenViewController.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import DTTableViewManager +import RxSwift +import RxCocoa + +class MainScreenViewController: UIViewController, DTTableViewManageable { + + var disposeBag = DisposeBag() + + @IBOutlet weak var tableView: UITableView! + @IBOutlet weak var balanceLabel: UILabel! + @IBOutlet weak var addIncomeButton: UIButton! + @IBOutlet weak var goToExpenseIncomeChartButton: UIButton! + + private lazy var addCategoryView: UIView = { + let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 70)) + let button = DefaultButton() + button.setTitle("Добавить категорию", for: .normal) + + button.rx.controlEvent(.touchUpInside).subscribe(onNext: { [unowned self] _ in + self.showAddCategotyAlert() + }).disposed(by: disposeBag) + + view.addSubview(button) + + button.snp.makeConstraints { make in + make.edges.equalToSuperview().inset(16) + } + + return view + }() + + override func viewDidLoad() { + super.viewDidLoad() + + setupUI() + configureCells() + configureTableView() + balanceLabel.text = "\(Persistence.storage.getBalance()) ₽" + manager.memoryStorage.setItems(Persistence.storage.getCategories()) + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + balanceLabel.text = "\(Persistence.storage.getBalance()) ₽" + tableView.reloadData() + } + + private func setupUI() { + navigationItem.title = "Главный экран" + + addIncomeButton.layer.cornerRadius = 10 + goToExpenseIncomeChartButton.layer.cornerRadius = 10 + + balanceLabel.rx.observe(String.self, "text").subscribe(onNext: { [unowned self] _ in + self.balanceLabel.textColor = Persistence.storage.getBalance() >= 0 ? UIColor.systemGreen : UIColor.systemRed + }).disposed(by: disposeBag) + } + + private func configureCells() { + manager.register(ExcensesCategoryTableViewCell.self) + + manager.didSelect(ExcensesCategoryTableViewCell.self) { [unowned self] _, model, indexPath in + let vc = self.storyboard!.instantiateViewController(withIdentifier: "ExcenseScreenViewConroller") as! ExcenseScreenViewConroller + vc.nameCategory = model.name + self.navigationController?.pushViewController(vc, animated: true) + } + } + + private func configureTableView() { + tableView.tableFooterView = addCategoryView + } + + @IBAction func addIncomeClick(_ sender: Any) { + showAddIncomeAlert() + } + + @IBAction func goToExpenseIncomeChartClick(_ sender: Any) { + let vc = storyboard!.instantiateViewController(withIdentifier: "ChartExpenseIncomeViewController") + navigationController?.pushViewController(vc, animated: true) + } + +} diff --git a/DiplomProject/DiplomProject/Persistence.swift b/DiplomProject/DiplomProject/Persistence.swift new file mode 100644 index 0000000..437cb42 --- /dev/null +++ b/DiplomProject/DiplomProject/Persistence.swift @@ -0,0 +1,63 @@ +// +// Persistence.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import RealmSwift + +class Persistence { + + static var storage = Persistence() + + private lazy var incomes: [Income] = Array(self.realm.objects(Income.self)) + private lazy var expensesCategory: [ExpenseCategory] = Array(self.realm.objects(ExpenseCategory.self)) + private lazy var expenses: [Expense] = Array(self.realm.objects(Expense.self)) + + private let realm = try! Realm() + + func addIncome(income: Income) { + try! realm.write { + realm.add(income) + incomes.append(income) + } + } + + func addCategoryExpense(category: ExpenseCategory) { + try! realm.write { + realm.add(category) + expensesCategory.append(category) + } + } + + func addExpenseInCategory(expense: Expense, nameCategory: String) { + guard let category = realm.objects(ExpenseCategory.self).filter({ $0.name == nameCategory }).first else { fatalError("not found category") } + try! realm.write { + expense.category = category + realm.add(expense) + expenses.append(expense) + category.expensesList.append(expense) + } + } + + func getBalance() -> Float { + return incomes.reduce(0, { $0 + $1.value }) - expenses.reduce(0, { $0 + $1.value }) + } + + func getCategories() -> [ExpenseCategory] { + return expensesCategory + } + + func getTransactionFromPeriod(with date: Date) -> [Transaction] { + return (incomes + expenses) + .sorted(by: { $0.date > $1.date }) + .filter({ $0.date >= date }) + } + + func getExpensesFromCategory(nameCategory: String) -> [Expense] { + guard let category = realm.objects(ExpenseCategory.self).filter({ $0.name == nameCategory }).first else { fatalError("not found category") } + return Array(category.expensesList) + } +} diff --git a/Lesson12/Lesson12/SceneDelegate.swift b/DiplomProject/DiplomProject/SceneDelegate.swift similarity index 96% rename from Lesson12/Lesson12/SceneDelegate.swift rename to DiplomProject/DiplomProject/SceneDelegate.swift index b8bc8e2..2f8b9b4 100644 --- a/Lesson12/Lesson12/SceneDelegate.swift +++ b/DiplomProject/DiplomProject/SceneDelegate.swift @@ -1,8 +1,8 @@ // // SceneDelegate.swift -// Lesson12 +// DiplomProject // -// Created by Михаил Беленко on 31.01.2020. +// Created by Михаил Беленко on 05.02.2020. // Copyright © 2020 Михаил Беленко. All rights reserved. // diff --git a/DiplomProject/DiplomProject/TransactionTableViewCell.swift b/DiplomProject/DiplomProject/TransactionTableViewCell.swift new file mode 100644 index 0000000..af3ecbf --- /dev/null +++ b/DiplomProject/DiplomProject/TransactionTableViewCell.swift @@ -0,0 +1,69 @@ +// +// TransactionTableViewCell.swift +// DiplomProject +// +// Created by Михаил Беленко on 05.02.2020. +// Copyright © 2020 Михаил Беленко. All rights reserved. +// + +import UIKit +import DTModelStorage +import SnapKit + +class TransactionTableViewCell: UITableViewCell, ModelTransfer { + typealias ModelType = Transaction + + private lazy var dateLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .medium) + label.textColor = .systemBlue + return label + }() + + private lazy var valueLabel: UILabel = { + let label = UILabel() + label.font = .systemFont(ofSize: 20, weight: .regular) + return label + }() + + override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { + super.init(style: style, reuseIdentifier: reuseIdentifier) + + contentView.addSubview(dateLabel) + contentView.addSubview(valueLabel) + setupConstraints() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(with model: Transaction) { + if model is Income { + dateLabel.text = convertDate(date: model.date) + valueLabel.text = "\(model.value) ₽" + valueLabel.textColor = .systemGreen + } else if model is Expense { + dateLabel.text = convertDate(date: model.date) + valueLabel.text = "-\(model.value) ₽" + valueLabel.textColor = .systemRed + } else { fatalError("unknown model")} + } + + private func convertDate(date: Date) -> String { + let formatter = DateFormatter() + formatter.dateFormat = "dd MMMM yyyy HH:mm" + return formatter.string(from: date) + } + + private func setupConstraints() { + dateLabel.snp.makeConstraints { make in + make.top.bottom.leading.equalToSuperview().inset(16) + } + + valueLabel.snp.makeConstraints { make in + make.leading.equalTo(dateLabel.snp.trailing).offset(8) + make.top.bottom.trailing.equalToSuperview().inset(16) + } + } +} diff --git a/Lesson14/Podfile b/DiplomProject/Podfile similarity index 85% rename from Lesson14/Podfile rename to DiplomProject/Podfile index 339f35d..b5d62c2 100644 --- a/Lesson14/Podfile +++ b/DiplomProject/Podfile @@ -1,11 +1,11 @@ # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' -target 'Lesson14' do +target 'DiplomProject' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! - # Pods for Lesson14 + # Pods for DiplomProject pod 'RealmSwift' pod 'DTTableViewManager' pod 'SnapKit', '~> 5.0.0' diff --git a/Lesson14/Podfile.lock b/DiplomProject/Podfile.lock similarity index 95% rename from Lesson14/Podfile.lock rename to DiplomProject/Podfile.lock index 91589af..6165fc8 100644 --- a/Lesson14/Podfile.lock +++ b/DiplomProject/Podfile.lock @@ -45,6 +45,6 @@ SPEC CHECKSUMS: RxSwift: e2dc62b366a3adf6a0be44ba9f405efd4c94e0c4 SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb -PODFILE CHECKSUM: dc3af7023fc8bed261c2121f0c3d70c218960d49 +PODFILE CHECKSUM: c03bb246ea5767d149de039ed8cb11cae6bb6c4f COCOAPODS: 1.8.4 diff --git a/Lesson12/Pods/DTModelStorage/LICENSE b/DiplomProject/Pods/DTModelStorage/LICENSE similarity index 100% rename from Lesson12/Pods/DTModelStorage/LICENSE rename to DiplomProject/Pods/DTModelStorage/LICENSE diff --git a/Lesson12/Pods/DTModelStorage/README.md b/DiplomProject/Pods/DTModelStorage/README.md similarity index 100% rename from Lesson12/Pods/DTModelStorage/README.md rename to DiplomProject/Pods/DTModelStorage/README.md diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift diff --git a/Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift b/DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift similarity index 100% rename from Lesson12/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift rename to DiplomProject/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift diff --git a/Lesson12/Pods/DTTableViewManager/LICENSE b/DiplomProject/Pods/DTTableViewManager/LICENSE similarity index 100% rename from Lesson12/Pods/DTTableViewManager/LICENSE rename to DiplomProject/Pods/DTTableViewManager/LICENSE diff --git a/Lesson12/Pods/DTTableViewManager/README.md b/DiplomProject/Pods/DTTableViewManager/README.md similarity index 100% rename from Lesson12/Pods/DTTableViewManager/README.md rename to DiplomProject/Pods/DTTableViewManager/README.md diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift diff --git a/Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift b/DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift similarity index 100% rename from Lesson12/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift rename to DiplomProject/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift diff --git a/Lesson14/Pods/Manifest.lock b/DiplomProject/Pods/Manifest.lock similarity index 95% rename from Lesson14/Pods/Manifest.lock rename to DiplomProject/Pods/Manifest.lock index 91589af..6165fc8 100644 --- a/Lesson14/Pods/Manifest.lock +++ b/DiplomProject/Pods/Manifest.lock @@ -45,6 +45,6 @@ SPEC CHECKSUMS: RxSwift: e2dc62b366a3adf6a0be44ba9f405efd4c94e0c4 SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb -PODFILE CHECKSUM: dc3af7023fc8bed261c2121f0c3d70c218960d49 +PODFILE CHECKSUM: c03bb246ea5767d149de039ed8cb11cae6bb6c4f COCOAPODS: 1.8.4 diff --git a/Lesson14/Pods/Pods.xcodeproj/project.pbxproj b/DiplomProject/Pods/Pods.xcodeproj/project.pbxproj similarity index 97% rename from Lesson14/Pods/Pods.xcodeproj/project.pbxproj rename to DiplomProject/Pods/Pods.xcodeproj/project.pbxproj index 138cbef..4efd4be 100644 --- a/Lesson14/Pods/Pods.xcodeproj/project.pbxproj +++ b/DiplomProject/Pods/Pods.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 50; objects = { /* Begin PBXBuildFile section */ @@ -137,7 +137,6 @@ 30AA515CC73339676F3E4AD889BA0BD1 /* DTTableViewManager-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2C5EBD3384F850E993E6DEA520A6EA96 /* DTTableViewManager-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 31178C789D180A66D48BE5AA4499BF9C /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 384955720F10466556436E5843CF51B0 /* Scan.swift */; }; 32548F19AD8CE091C9B839D129A12ED3 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34A75454964E602B472BCD362B354DA6 /* LockOwnerType.swift */; }; - 326E3410EEF85E398A92CC6485147C06 /* Pods-Lesson14-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F96AA4B5D65D0833FEADB4CE32484DF /* Pods-Lesson14-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 329FC3E722DE36B8B00674D23CCB031E /* RLMSyncUser.h in Headers */ = {isa = PBXBuildFile; fileRef = 68EF0081E0D6262C3EC7FE3874A4A706 /* RLMSyncUser.h */; }; 32FAB693F35FD0A43BFAA96EE42C0592 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4222E7FFA6A71F758E109C01DDF491C2 /* AsyncSubject.swift */; }; 33DB58AF9288D79925FB91F693665208 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74EF4EE859A7814290D7DD29B514E4A1 /* PriorityQueue.swift */; }; @@ -169,13 +168,13 @@ 402FCFD173FEBF2B829919A6E709CB9A /* Signal+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13F520B1AAEE60F4B12422D4724E6080 /* Signal+Subscription.swift */; }; 407C9EDF0986C9BC13F8F9E826103758 /* UIStepper+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02114096E711DF11810F166DCFFB0765 /* UIStepper+Rx.swift */; }; 40843B33D64FD3C08201F5AF059E87BD /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 991B07B4CAAD2055CE861601735C7CE3 /* Sink.swift */; }; + 41156798567A16488F365777D718CD95 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7BB2C83D6264F337282BC8A547374066 /* Foundation.framework */; }; 41E004B17C010DF07FB2930289A4342A /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57E1201AE30768AE07347F06C99EEF2A /* ConnectableObservableType.swift */; }; 42243F8F8A3A333A3543A3798E0BB9B2 /* ObjectiveCSupport+Sync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 531CCB382C570567BD8B283494147C95 /* ObjectiveCSupport+Sync.swift */; }; 422E6B56ABB317844D12D62944E54BAE /* Driver+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = C588CF5E1E62938665CDA5CE93F3CB7C /* Driver+Subscription.swift */; }; 428269FAE739F3BF98900D0A8F653435 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B7F07974A8E59A5443E84ECB78C2B71 /* Utils.swift */; }; 430FBA64DC0FC3E07D39B0DAF4657C81 /* RLMNetworkClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = F574D2F6BDDC8F6B50636C162C800B0F /* RLMNetworkClient.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; 436803A8CCC81A15C5EA20B71B444217 /* RealmSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 114D0F4F2F2BAA698567F126F5C12158 /* RealmSwift-dummy.m */; }; - 43B65ECF0480AD0B4C55BD7406D7FAE8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7BB2C83D6264F337282BC8A547374066 /* Foundation.framework */; }; 43BA5EC8500B0ACE7F1AAA3A41FE58B1 /* ItemEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10BAC9853B695A2E2F895ACDDC40D882 /* ItemEvents.swift */; }; 44D7FC78DA96572DA949EDC39F164F5A /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07EA5B27FD3B05B9B8E037DE1B7840FC /* Disposables.swift */; }; 450905DBF81926149215CD678496C9A5 /* ObservableConvertibleType+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 184A6D472881682312A7FEF4CACC3D2B /* ObservableConvertibleType+Driver.swift */; }; @@ -402,7 +401,6 @@ AACEBC8596A841C7B61CD7E1A9AE2DE4 /* collection_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 637DFD45B72EA624A5C266FC2D4EE92D /* collection_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; AADBCD1B21CD4A8302788D60CBA914EB /* RLMSyncManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 0BE2C8872CFDC96131D5B3179919B3A0 /* RLMSyncManager.h */; }; AB378EF4F418F0A00D68FA7B37A60491 /* RLMOptionalBase.h in Headers */ = {isa = PBXBuildFile; fileRef = D285A3B870933790294B276D3589BB01 /* RLMOptionalBase.h */; }; - AC0B01497BE3B04DE61C61CCE1EC51E2 /* Pods-Lesson14-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CC5E59903D102D1200E648293CB400C1 /* Pods-Lesson14-dummy.m */; }; AC0F5BE9969AFF9FC4DBF4D3115917ED /* ObjectSchema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0BE410A62727BFF94C08BCC88708CF /* ObjectSchema.swift */; }; AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42D546E497FC664481223EC385E27B78 /* ConstraintDirectionalInsets.swift */; }; AC7D415C826932227566EB2B916A7C26 /* SortDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0A10A833335968F6C69C5DA93C3675A /* SortDescriptor.swift */; }; @@ -495,6 +493,7 @@ D1E16D8B852B793DC73D69F98267636C /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F06D0D5124A2E5A84399374AFA2555C1 /* Migration.swift */; }; D28C130F5F3012F587CC16763CBD3DBE /* collection_change_builder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0D12C5019FAEF3917498A2758BE788BE /* collection_change_builder.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; D2F86E2B73E53302B6123294BB834002 /* RxCollectionViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE05100E71B9936193B4A964D0E941E /* RxCollectionViewDelegateProxy.swift */; }; + D3C9F9AD099D6466F185B5DBC9C7DE69 /* Pods-DiplomProject-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D031597770068CA489961DAA2546D3C /* Pods-DiplomProject-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9E81ED292D3022E56D4387700980D07 /* ConstraintMultiplierTarget.swift */; }; D4DB8A02127BB87032E1DA5223CFF741 /* PublishRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD3CD14259AF1BDEBBA789C3279771C6 /* PublishRelay.swift */; }; D4EABA6421CCDD554276DC67D4DED21A /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E32F8775F03178B784A2843BF77FD8A /* TailRecursiveSink.swift */; }; @@ -540,6 +539,7 @@ EC8AA67E12A1AA5DD94C82859BDA6330 /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA50131D5240AD74D1DC29D5352A6F0F /* GroupBy.swift */; }; ECBFF9900B43E51EBAB4B771EF06A9EC /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767EBFD0C5AEC35526D8B0D04CB1AAD /* ConcurrentDispatchQueueScheduler.swift */; }; ED3035ABEBCD639F75DDC5C472795706 /* realm_coordinator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 063C338AEFFC8600F9C05A875ADABBBA /* realm_coordinator.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; + ED8360829F96DB7655A4359EB8613B05 /* Pods-DiplomProject-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A4752B5F723D20D9A09B43A116FD16E9 /* Pods-DiplomProject-dummy.m */; }; EE19F864673AF83DB4C21CA8464455AC /* object.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DAE590CB3FB3EAD516F58FEF831E71DC /* object.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; EE2A5AE21E43B6A17BFFFE1695AF66FE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7BB2C83D6264F337282BC8A547374066 /* Foundation.framework */; }; EE3322A4595447F7FC50F86C6E99BC1B /* TableViewFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFD34C7DF965FCE66DE8E3E15A3CA945 /* TableViewFactory.swift */; }; @@ -584,6 +584,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 03C3979BE1EC7C39874C8A462B597FB9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 3EF3490B4B0DD7F07469ADEE907B9E59; + remoteInfo = DTTableViewManager; + }; 04142E1DB41EC92EB296F3E757BCE4B7 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; @@ -591,6 +598,13 @@ remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; remoteInfo = RxSwift; }; + 04C6FFBC0EEEB7B26E6BA648AB99C579 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; 07E45B0AFEEED2846D13571956E582B3 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; @@ -605,34 +619,20 @@ remoteGlobalIDString = 68494F30B4A13F8E5E88BCCAEC25B0A4; remoteInfo = Realm; }; - 2502EA8234B4134CC6CCD79B35CD8171 /* PBXContainerItemProxy */ = { + 38798EE4C9A9293F3745F976F22ADABC /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = E1F697AE01D68453B8B3B86DA9E42200; remoteInfo = DTModelStorage; }; - 27EE226844E562BB17582F427CB146C4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 68494F30B4A13F8E5E88BCCAEC25B0A4; - remoteInfo = Realm; - }; - 2806DFE021724FE2A170FA769505C588 /* PBXContainerItemProxy */ = { + 38F8DDEF18D21DDC6590B672109819AB /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; remoteInfo = SnapKit; }; - 38798EE4C9A9293F3745F976F22ADABC /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = E1F697AE01D68453B8B3B86DA9E42200; - remoteInfo = DTModelStorage; - }; 3AA5F122E4B6C1CDC8306AE3F5C627D8 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; @@ -640,40 +640,40 @@ remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; remoteInfo = RxSwift; }; - 756BF60843A1E9E639A3BB2EC8CD216A /* PBXContainerItemProxy */ = { + 3FDE3B12860E9615FEA8811F78ED17B2 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 3EF3490B4B0DD7F07469ADEE907B9E59; - remoteInfo = DTTableViewManager; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; }; - 98932432ED5F0A43DA179C5B350F646C /* PBXContainerItemProxy */ = { + 4A442662546A638F8703AFD87641B74D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; - remoteInfo = RxRelay; + remoteGlobalIDString = 782725687624F8665247B84AB581BEB1; + remoteInfo = RealmSwift; }; - BCC8D6EA14ECD36D30063FC642910A60 /* PBXContainerItemProxy */ = { + 612452682302E0F2605732313104C46B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; - remoteInfo = RxSwift; + remoteGlobalIDString = E1F697AE01D68453B8B3B86DA9E42200; + remoteInfo = DTModelStorage; }; - C00E48E5E3A99D86267F0C1D0DEF8A7F /* PBXContainerItemProxy */ = { + D63EE6701221171E23062256E58FC8AE /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 782725687624F8665247B84AB581BEB1; - remoteInfo = RealmSwift; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; }; - F5186B6EC1A56D996136149A37078758 /* PBXContainerItemProxy */ = { + F2CF206110B8EA94052D1CD67B58E0A7 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; - remoteInfo = RxCocoa; + remoteGlobalIDString = 68494F30B4A13F8E5E88BCCAEC25B0A4; + remoteInfo = Realm; }; /* End PBXContainerItemProxy section */ @@ -752,7 +752,6 @@ 00A2ACFD98928CAFBF6936A480F2D171 /* RxCollectionViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift; sourceTree = ""; }; 00D2EAC0E945CF2B4B2642A8A57DC812 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; 02114096E711DF11810F166DCFFB0765 /* UIStepper+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIStepper+Rx.swift"; path = "RxCocoa/iOS/UIStepper+Rx.swift"; sourceTree = ""; }; - 02953B3E759046A6C51A39B349AA0C1C /* Pods-Lesson14-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Lesson14-frameworks.sh"; sourceTree = ""; }; 02A0B33B8E43BB8AB78326695EBEC4DA /* NSError+RLMSync.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSError+RLMSync.m"; path = "Realm/NSError+RLMSync.m"; sourceTree = ""; }; 03409D848A019694D37210E72A6A0507 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; 03496D6ED0F32F56C1547B1AC6D7F800 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; @@ -788,7 +787,6 @@ 0EA02F76FC40E8871C1E86A92BCE0589 /* DTTableViewManager+Drop.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+Drop.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+Drop.swift"; sourceTree = ""; }; 0EA3C592C2F4D3FA1471EFDF4A46157F /* DTModelStorage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "DTModelStorage-umbrella.h"; sourceTree = ""; }; 0FE0923DAB0FE37C21B0FA7FE2869754 /* RLMRealm.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealm.h; path = include/RLMRealm.h; sourceTree = ""; }; - 0FF3DDD2ABDF1E4BF6329FE7DE4A7292 /* Pods-Lesson14.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson14.debug.xcconfig"; sourceTree = ""; }; 104F566F53C92F0A65CDC6D3C6D403B0 /* RLMObjectSchema_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectSchema_Private.h; path = include/RLMObjectSchema_Private.h; sourceTree = ""; }; 106EE806083FF3906BBC6097A35A4E4D /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Source/ConstraintPriority.swift; sourceTree = ""; }; 10BAC9853B695A2E2F895ACDDC40D882 /* ItemEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemEvents.swift; path = RxCocoa/iOS/Events/ItemEvents.swift; sourceTree = ""; }; @@ -800,6 +798,7 @@ 11B760B1D06B290A99633FC35219D167 /* String+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Rx.swift"; path = "RxSwift/Extensions/String+Rx.swift"; sourceTree = ""; }; 11BDED584BD3E7170192B629CD1DDB07 /* Section.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Section.swift; path = Sources/DTModelStorage/Section.swift; sourceTree = ""; }; 1263C3CF3C6F44D273EA720E75E3F2B5 /* RLMRealmConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealmConfiguration.h; path = include/RLMRealmConfiguration.h; sourceTree = ""; }; + 1328D094615B82F9841F8F6EABF6D506 /* Pods_DiplomProject.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_DiplomProject.framework; path = "Pods-DiplomProject.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 139ACCF2AAA970C7EA7E189BE51B4778 /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.swift; sourceTree = ""; }; 13F520B1AAEE60F4B12422D4724E6080 /* Signal+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Signal+Subscription.swift"; path = "RxCocoa/Traits/Signal/Signal+Subscription.swift"; sourceTree = ""; }; 143E2F7267F0990FAFB8CEDE450CCAAE /* _RXKVOObserver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXKVOObserver.m; path = RxCocoa/Runtime/_RXKVOObserver.m; sourceTree = ""; }; @@ -839,6 +838,7 @@ 233DB4C732DE5E8D5C8C51FE839005EE /* _RXDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXDelegateProxy.h; path = RxCocoa/Runtime/include/_RXDelegateProxy.h; sourceTree = ""; }; 23406B8324B76BE30BD4F7147437C2AA /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; 235D61175AB09362DED65394760D757C /* RxSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.xcconfig; sourceTree = ""; }; + 2364E3058E0C7FE2F6F4A353B6F63F0D /* Pods-DiplomProject-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-DiplomProject-frameworks.sh"; sourceTree = ""; }; 243FB2841CE3DD9B9DD326E54E6281F2 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; 249177AF01679F1225C0C73CFFFB8B00 /* RxCocoa.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCocoa.swift; path = RxCocoa/RxCocoa.swift; sourceTree = ""; }; 263FFEE4DCBC4A91571FA91266E71752 /* RxRelay.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.xcconfig; sourceTree = ""; }; @@ -904,7 +904,6 @@ 3FF6907A16205E145149AF89CBB13ABE /* RLMRealm+Sync.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = "RLMRealm+Sync.mm"; path = "Realm/RLMRealm+Sync.mm"; sourceTree = ""; }; 406ADEEC9A0B46535A90560DD0EA581D /* RLMManagedArray.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMManagedArray.mm; path = Realm/RLMManagedArray.mm; sourceTree = ""; }; 407673B83AF3462B4E3F9A555A8BCAC6 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; - 408949819E12DABF70A3679D28C36AC2 /* Pods-Lesson14-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Lesson14-acknowledgements.markdown"; sourceTree = ""; }; 41AAB9B17FB7CEA90FD1119B150CB7A0 /* _RX.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RX.h; path = RxCocoa/Runtime/include/_RX.h; sourceTree = ""; }; 42004DAAD5C16CCB921B91023622671A /* shared_realm.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = shared_realm.cpp; path = Realm/ObjectStore/src/shared_realm.cpp; sourceTree = ""; }; 4222E7FFA6A71F758E109C01DDF491C2 /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; @@ -991,6 +990,7 @@ 69FB980DD901E5F306B88C6A66231A0F /* ViewModelMapping.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ViewModelMapping.swift; path = Sources/DTModelStorage/ViewModelMapping.swift; sourceTree = ""; }; 6AB878246F99C2118FC4281E240B6332 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; 6ABA6F913A337DDF5DBC2919862B0520 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+CoreGraphics.swift"; path = "RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; + 6D031597770068CA489961DAA2546D3C /* Pods-DiplomProject-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-DiplomProject-umbrella.h"; sourceTree = ""; }; 6DD32E38595128C91D818DE47EE56178 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; 6E21F41338312911E3F97F3A17B8F4F8 /* object_store.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = object_store.cpp; path = Realm/ObjectStore/src/object_store.cpp; sourceTree = ""; }; 6E32F8775F03178B784A2843BF77FD8A /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; @@ -998,6 +998,7 @@ 6EA4EEBE423E4919A9F358D3629F6E14 /* system_configuration.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = system_configuration.cpp; path = Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp; sourceTree = ""; }; 6EE8418222082BF2C58A5D1F888B3363 /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; 6F0A49BEA59396C3622A5C9F4A1E838A /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; + 6FFA10D5C5E8898EB8C382B4722CD292 /* Pods-DiplomProject.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiplomProject.release.xcconfig"; sourceTree = ""; }; 70345A7DD11A13B19A1186327ED713F9 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; 70DB924F3575A6ABA6A234D2E6BC030B /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; 71029819EF4F756C28C44DF1DC601FC0 /* DTTableViewDragDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDragDelegate.swift; path = Sources/DTTableViewManager/DTTableViewDragDelegate.swift; sourceTree = ""; }; @@ -1047,7 +1048,6 @@ 83005C3320FBF0BF16AF7AF69C4BFF44 /* sync_permission.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_permission.cpp; path = Realm/ObjectStore/src/sync/sync_permission.cpp; sourceTree = ""; }; 8376097DC8DCA921124770326FDC98A1 /* RxPickerViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift; sourceTree = ""; }; 83AEE66B05F5770FCCAA03132F0395A0 /* uuid.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = uuid.cpp; path = Realm/ObjectStore/src/util/uuid.cpp; sourceTree = ""; }; - 84207C312DDC4EFFC9E634B69C09B6A4 /* Pods-Lesson14.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Lesson14.modulemap"; sourceTree = ""; }; 84B2CE8B3070999028830B206CB89397 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; 84BFB0814BA359EEA2A1B0CF93366337 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; 84DAF014ABD64CFD965051B5B8967381 /* RLMRealmConfiguration+Sync.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = "RLMRealmConfiguration+Sync.mm"; path = "Realm/RLMRealmConfiguration+Sync.mm"; sourceTree = ""; }; @@ -1064,7 +1064,6 @@ 89486232AE8C3EF3A49F66BBAB386355 /* sync_file.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_file.cpp; path = Realm/ObjectStore/src/sync/impl/sync_file.cpp; sourceTree = ""; }; 8ADFDE931C5E5E5F3745B79215025318 /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; 8AE2C5CF0FDE8097681FB6446CE6EE79 /* SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SharedSequence.swift; path = RxCocoa/Traits/SharedSequence/SharedSequence.swift; sourceTree = ""; }; - 8B0BAA65B5FF348ED9DA6AAB1A2DB6DD /* Pods-Lesson14.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson14.release.xcconfig"; sourceTree = ""; }; 8B15BD9B1DE014E96B3841385DE2EC90 /* RLMSyncConfiguration_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncConfiguration_Private.h; path = include/RLMSyncConfiguration_Private.h; sourceTree = ""; }; 8B4ECA29C30CD64A64681936149E98C6 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; 8B7F07974A8E59A5443E84ECB78C2B71 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = RxRelay/Utils.swift; sourceTree = ""; }; @@ -1083,6 +1082,7 @@ 9232ADB36FFA1A3BA769D182E6FA1C77 /* RealmSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RealmSwift-umbrella.h"; sourceTree = ""; }; 93005079012095830194AD76AB910056 /* RLMQueryUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMQueryUtil.mm; path = Realm/RLMQueryUtil.mm; sourceTree = ""; }; 94CCA28C3A2D35CD096B2100B73A1C3B /* list_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = list_notifier.cpp; path = Realm/ObjectStore/src/impl/list_notifier.cpp; sourceTree = ""; }; + 9502A6F9B55D69EE04C5A480200EAEBB /* Pods-DiplomProject-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiplomProject-acknowledgements.plist"; sourceTree = ""; }; 95B57053105809CA66898A97C886182A /* results_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = results_notifier.cpp; path = Realm/ObjectStore/src/impl/results_notifier.cpp; sourceTree = ""; }; 969DC0D2E90A5822E3E51F28FFEDBC59 /* UISlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISlider+Rx.swift"; path = "RxCocoa/iOS/UISlider+Rx.swift"; sourceTree = ""; }; 97382B1A56C95809B3AE97985466A7F9 /* UIPageControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIPageControl+Rx.swift"; path = "RxCocoa/iOS/UIPageControl+Rx.swift"; sourceTree = ""; }; @@ -1101,10 +1101,9 @@ 9DA0D25B014B6C605C94F87007D07FFC /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; 9DCC32889D32623A0E0811E2CB7285B1 /* UIViewController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewController+Rx.swift"; path = "RxCocoa/iOS/UIViewController+Rx.swift"; sourceTree = ""; }; 9DDE20621816CD86C63D90497D426840 /* RxCollectionViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift; sourceTree = ""; }; + 9E52C0156999CFE0914C1614CCFDAABD /* Pods-DiplomProject-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiplomProject-Info.plist"; sourceTree = ""; }; 9EF9365E9C06068C4B8023560DCA742E /* external_commit_helper.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = external_commit_helper.cpp; path = Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp; sourceTree = ""; }; 9EFE3FCCF6F5BAC467A0AC6CC2FE5B90 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; - 9F1412CCC668E626AB645A48C1B5DD4E /* Pods-Lesson14-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson14-acknowledgements.plist"; sourceTree = ""; }; - 9F96AA4B5D65D0833FEADB4CE32484DF /* Pods-Lesson14-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Lesson14-umbrella.h"; sourceTree = ""; }; 9FE55386E6DD525E46D2CD62B759B745 /* RxSearchBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift; sourceTree = ""; }; A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = DTTableViewManager.framework; path = DTTableViewManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A0777D777B73FF264684F5EBB01DED80 /* NSObject+Rx+RawRepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+RawRepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift"; sourceTree = ""; }; @@ -1118,6 +1117,7 @@ A404BF6FCF8F8B2CC2819EB5F9611B1A /* RxTextViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift; sourceTree = ""; }; A40F9CD8C876605E386AEBEFDD305F96 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; A45FC2B2E9255305CABF97217A51A73C /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + A4752B5F723D20D9A09B43A116FD16E9 /* Pods-DiplomProject-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-DiplomProject-dummy.m"; sourceTree = ""; }; A60EC9880F00A9BA26A79A11EBA495FD /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = List.swift; path = RealmSwift/List.swift; sourceTree = ""; }; A6B66B5A7EC2BFCA8F36B8CD4852D754 /* Object.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Object.swift; path = RealmSwift/Object.swift; sourceTree = ""; }; A72F91610072D0131899F63556CC801D /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; @@ -1217,7 +1217,6 @@ CA833FBF95CD5F309CA3DC6E51FCB7B2 /* RLMRealm_Dynamic.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealm_Dynamic.h; path = include/RLMRealm_Dynamic.h; sourceTree = ""; }; CB501E9E9EF4CFE11F8FABAEE9A0F7F2 /* NSError+RLMSync.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+RLMSync.h"; path = "include/NSError+RLMSync.h"; sourceTree = ""; }; CC2D10C8A58BFFAFDBC8B8017A3BA8EA /* RxTabBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift; sourceTree = ""; }; - CC5E59903D102D1200E648293CB400C1 /* Pods-Lesson14-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Lesson14-dummy.m"; sourceTree = ""; }; CCA4FD89127B670C317A95AD5F3DE379 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; CD873B1241169FF26225EB641D77DA48 /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; CDAF4CF19F07B2F9E0722C5A0E76FCD4 /* DTModelStorage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "DTModelStorage-dummy.m"; sourceTree = ""; }; @@ -1228,7 +1227,6 @@ D075EEA5121755ACBE1A9AF6AD078217 /* Realm.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Realm.h; path = include/Realm.h; sourceTree = ""; }; D13118F9B7FFC58DD7B545383E1BD096 /* results.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = results.cpp; path = Realm/ObjectStore/src/results.cpp; sourceTree = ""; }; D1CDBE361CA49130C34A5B56439AB4AB /* DTTableViewManagerAnomalyHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewManagerAnomalyHandler.swift; path = Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift; sourceTree = ""; }; - D230467C895D33F10A8EAA855DCB605C /* Pods-Lesson14-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson14-Info.plist"; sourceTree = ""; }; D25D2215B26E4DAB57A599DBF47858D2 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; D285A3B870933790294B276D3589BB01 /* RLMOptionalBase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMOptionalBase.h; path = include/RLMOptionalBase.h; sourceTree = ""; }; D29353153874410D41A8F0B8BB35A75C /* RLMObjectSchema.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObjectSchema.mm; path = Realm/RLMObjectSchema.mm; sourceTree = ""; }; @@ -1274,19 +1272,21 @@ E6B74313B174401C9AD7737DDDFCBB86 /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; E71BD559E366E8B4887FA243D03D148B /* RxPickerViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift; sourceTree = ""; }; E75343A45935385FC56F6F5CBBC2E2E9 /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + E7C8AFE38022614F01148D03831E6330 /* Pods-DiplomProject.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiplomProject.debug.xcconfig"; sourceTree = ""; }; E8252B7E4260C493825AA24ECFECFBAE /* UICollectionView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Rx.swift"; path = "RxCocoa/iOS/UICollectionView+Rx.swift"; sourceTree = ""; }; E912ED414A4C80081FBDE49D92AB27DD /* RealmSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RealmSwift.xcconfig; sourceTree = ""; }; - E9385482884D20E0772E779F4F0A34B6 /* Pods_Lesson14.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Lesson14.framework; path = "Pods-Lesson14.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; E95DF3800B40077A87B583C5023683AF /* UIRefreshControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIRefreshControl+Rx.swift"; path = "RxCocoa/iOS/UIRefreshControl+Rx.swift"; sourceTree = ""; }; E9668A57714E09121110B680B5FDF467 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; E98C69D8773FB166A6D35EE0745BA59A /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; EA51FA576AADD94EC7D784B3A7C83287 /* TakeUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeUntil.swift; path = RxSwift/Observables/TakeUntil.swift; sourceTree = ""; }; EAB1F344AA6500863B8A1BDB34F18995 /* UIImageView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIImageView+Rx.swift"; path = "RxCocoa/iOS/UIImageView+Rx.swift"; sourceTree = ""; }; + EAE3EF287C9A2A59D7F35C336299F9B1 /* Pods-DiplomProject-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-DiplomProject-acknowledgements.markdown"; sourceTree = ""; }; EB29B3B334DD6262A94CEBD1B974F31C /* KeyPathBinder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeyPathBinder.swift; path = RxCocoa/Common/KeyPathBinder.swift; sourceTree = ""; }; EB544E6B42E5C1181D45893F0DEB3D44 /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; EC0583EAB2FEC444E4C7885B5BC15316 /* RxTableViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift; sourceTree = ""; }; EC11B552824A1482BDD6434992A1F992 /* UIDatePicker+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIDatePicker+Rx.swift"; path = "RxCocoa/iOS/UIDatePicker+Rx.swift"; sourceTree = ""; }; EC206BC9EE3BA4710BC5FC31E22157F8 /* Property.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Property.swift; path = RealmSwift/Property.swift; sourceTree = ""; }; + ECDBF3AE6144640539F726D338B904A2 /* Pods-DiplomProject.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-DiplomProject.modulemap"; sourceTree = ""; }; EE1E3110F9B2080BF53A3C6CE08BF3BB /* RLMRealmConfiguration_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealmConfiguration_Private.h; path = include/RLMRealmConfiguration_Private.h; sourceTree = ""; }; EE22AF1942933161FE0C9D7C924C190D /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxCocoa/Common/Observable+Bind.swift"; sourceTree = ""; }; F06D0D5124A2E5A84399374AFA2555C1 /* Migration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Migration.swift; path = RealmSwift/Migration.swift; sourceTree = ""; }; @@ -1383,33 +1383,25 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 97D95639392A8091F2F97920DF5C9782 /* Frameworks */ = { + 9839587E8C51FE1968987323830C1254 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 43B65ECF0480AD0B4C55BD7406D7FAE8 /* Foundation.framework in Frameworks */, + 65FF91A9492E4E08B8B4D8B5878FC196 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - 9839587E8C51FE1968987323830C1254 /* Frameworks */ = { + F66DA09E71C28AB034C9F4B41854A048 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 65FF91A9492E4E08B8B4D8B5878FC196 /* Foundation.framework in Frameworks */, + 41156798567A16488F365777D718CD95 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 0026325A52BE2E74EABFD1E937843243 /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - 65895C0227919DBDB1687E76F5C6EF9A /* Pods-Lesson14 */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; 011E2F08B4CB74C9E6721E40B5547A21 /* RxCocoa */ = { isa = PBXGroup; children = ( @@ -1615,6 +1607,14 @@ name = Frameworks; sourceTree = ""; }; + 4867559ADEBEC998C7D808EA43814819 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + C58B77775DCA708AD6C7C31554352383 /* Pods-DiplomProject */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; 4A732A011891239D1BC07408E38463D5 /* Headers */ = { isa = PBXGroup; children = ( @@ -1650,39 +1650,6 @@ name = Headers; sourceTree = ""; }; - 65895C0227919DBDB1687E76F5C6EF9A /* Pods-Lesson14 */ = { - isa = PBXGroup; - children = ( - 84207C312DDC4EFFC9E634B69C09B6A4 /* Pods-Lesson14.modulemap */, - 408949819E12DABF70A3679D28C36AC2 /* Pods-Lesson14-acknowledgements.markdown */, - 9F1412CCC668E626AB645A48C1B5DD4E /* Pods-Lesson14-acknowledgements.plist */, - CC5E59903D102D1200E648293CB400C1 /* Pods-Lesson14-dummy.m */, - 02953B3E759046A6C51A39B349AA0C1C /* Pods-Lesson14-frameworks.sh */, - D230467C895D33F10A8EAA855DCB605C /* Pods-Lesson14-Info.plist */, - 9F96AA4B5D65D0833FEADB4CE32484DF /* Pods-Lesson14-umbrella.h */, - 0FF3DDD2ABDF1E4BF6329FE7DE4A7292 /* Pods-Lesson14.debug.xcconfig */, - 8B0BAA65B5FF348ED9DA6AAB1A2DB6DD /* Pods-Lesson14.release.xcconfig */, - ); - name = "Pods-Lesson14"; - path = "Target Support Files/Pods-Lesson14"; - sourceTree = ""; - }; - 6A8B940AFFF1141846E92F9A9B1FEB51 /* Products */ = { - isa = PBXGroup; - children = ( - 8D7F44C29F5C323A93E174DED4DDB254 /* DTModelStorage.framework */, - A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */, - E9385482884D20E0772E779F4F0A34B6 /* Pods_Lesson14.framework */, - 921BE4A82C4A7A5C72A0C6F8B8FEF200 /* Realm.framework */, - 437919EE08EC6BFCCBAC3BD346309742 /* RealmSwift.framework */, - BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa.framework */, - FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay.framework */, - 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift.framework */, - 979486118B3E90C08386079D57962701 /* SnapKit.framework */, - ); - name = Products; - sourceTree = ""; - }; 8759407BE31458AC2068B47B73AB9CB8 /* Realm */ = { isa = PBXGroup; children = ( @@ -2044,6 +2011,23 @@ path = DTModelStorage; sourceTree = ""; }; + C58B77775DCA708AD6C7C31554352383 /* Pods-DiplomProject */ = { + isa = PBXGroup; + children = ( + ECDBF3AE6144640539F726D338B904A2 /* Pods-DiplomProject.modulemap */, + EAE3EF287C9A2A59D7F35C336299F9B1 /* Pods-DiplomProject-acknowledgements.markdown */, + 9502A6F9B55D69EE04C5A480200EAEBB /* Pods-DiplomProject-acknowledgements.plist */, + A4752B5F723D20D9A09B43A116FD16E9 /* Pods-DiplomProject-dummy.m */, + 2364E3058E0C7FE2F6F4A353B6F63F0D /* Pods-DiplomProject-frameworks.sh */, + 9E52C0156999CFE0914C1614CCFDAABD /* Pods-DiplomProject-Info.plist */, + 6D031597770068CA489961DAA2546D3C /* Pods-DiplomProject-umbrella.h */, + E7C8AFE38022614F01148D03831E6330 /* Pods-DiplomProject.debug.xcconfig */, + 6FFA10D5C5E8898EB8C382B4722CD292 /* Pods-DiplomProject.release.xcconfig */, + ); + name = "Pods-DiplomProject"; + path = "Target Support Files/Pods-DiplomProject"; + sourceTree = ""; + }; C59F9B62C431C67F617130ECC7745E11 /* DTTableViewManager */ = { isa = PBXGroup; children = ( @@ -2071,6 +2055,22 @@ path = DTTableViewManager; sourceTree = ""; }; + CC8EE40723D7B73B12ED8537C0A2B6EA /* Products */ = { + isa = PBXGroup; + children = ( + 8D7F44C29F5C323A93E174DED4DDB254 /* DTModelStorage.framework */, + A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */, + 1328D094615B82F9841F8F6EABF6D506 /* Pods_DiplomProject.framework */, + 921BE4A82C4A7A5C72A0C6F8B8FEF200 /* Realm.framework */, + 437919EE08EC6BFCCBAC3BD346309742 /* RealmSwift.framework */, + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa.framework */, + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay.framework */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift.framework */, + 979486118B3E90C08386079D57962701 /* SnapKit.framework */, + ); + name = Products; + sourceTree = ""; + }; CEC98545FECFEFD915D82BB5E5812AD2 /* Support Files */ = { isa = PBXGroup; children = ( @@ -2091,8 +2091,8 @@ 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, 26C4D70FC891B2FCD25FDCD407748CD3 /* Frameworks */, BA4563BE2B3CC8402E15FDC09C355CC6 /* Pods */, - 6A8B940AFFF1141846E92F9A9B1FEB51 /* Products */, - 0026325A52BE2E74EABFD1E937843243 /* Targets Support Files */, + CC8EE40723D7B73B12ED8537C0A2B6EA /* Products */, + 4867559ADEBEC998C7D808EA43814819 /* Targets Support Files */, ); sourceTree = ""; }; @@ -2234,27 +2234,27 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 6F8A95E2F5B54605BC24D7D0C092972A /* Headers */ = { + 722E475DE0CF9919A20939E5C73B50DC /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 326E3410EEF85E398A92CC6485147C06 /* Pods-Lesson14-umbrella.h in Headers */, + 1A73743D0ACF79E17620444695C737D9 /* RxRelay-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 722E475DE0CF9919A20939E5C73B50DC /* Headers */ = { + 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 1A73743D0ACF79E17620444695C737D9 /* RxRelay-umbrella.h in Headers */, + A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */ = { + 7E416A3DB398F4B14C4BCFD634253F0D /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */, + D3C9F9AD099D6466F185B5DBC9C7DE69 /* Pods-DiplomProject-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2435,30 +2435,30 @@ productReference = BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa.framework */; productType = "com.apple.product-type.framework"; }; - B0C3941F7472DEBFD2FC317AA7469DF1 /* Pods-Lesson14 */ = { + A4F4BA620B813F46AE18CA22D4C61EDC /* Pods-DiplomProject */ = { isa = PBXNativeTarget; - buildConfigurationList = 87212F28B46D140A3FF0327A2E5A422C /* Build configuration list for PBXNativeTarget "Pods-Lesson14" */; + buildConfigurationList = 0DA7F9A4F9DE964785982338CB002AA6 /* Build configuration list for PBXNativeTarget "Pods-DiplomProject" */; buildPhases = ( - 6F8A95E2F5B54605BC24D7D0C092972A /* Headers */, - FF1E9205411404BF84CB669B83F428B3 /* Sources */, - 97D95639392A8091F2F97920DF5C9782 /* Frameworks */, - 12218AC9902A620A96A491310D2ACF39 /* Resources */, + 7E416A3DB398F4B14C4BCFD634253F0D /* Headers */, + 4A51719E172F9DA3D0B857E6A2930FC7 /* Sources */, + F66DA09E71C28AB034C9F4B41854A048 /* Frameworks */, + BBC9C24F086A359062FEF57D8000E72A /* Resources */, ); buildRules = ( ); dependencies = ( - ADF5BE5BEA21582215FD2E8A56C5C0E7 /* PBXTargetDependency */, - 1DDB6B15DE353481466AECAA6218BB3A /* PBXTargetDependency */, - 0162B1DBD18B05C2A5E2A064DF2B226A /* PBXTargetDependency */, - 5B142144E98301F6801AE08EC8970CD1 /* PBXTargetDependency */, - 55CD9FF0DEFE71F420D1927C9F7041EB /* PBXTargetDependency */, - 947E049CC4473F7D4B150F546C433257 /* PBXTargetDependency */, - D330E08C8B590F1554134A5FEB72D84B /* PBXTargetDependency */, - 7D428BCC95E3CEAA192881BF2D259EB8 /* PBXTargetDependency */, - ); - name = "Pods-Lesson14"; - productName = "Pods-Lesson14"; - productReference = E9385482884D20E0772E779F4F0A34B6 /* Pods_Lesson14.framework */; + 97E7C5DFDFA8803A26EFA8754A9FD5C7 /* PBXTargetDependency */, + 0E8E3AAEDDF6C9CBAA53C18F6FDA05E4 /* PBXTargetDependency */, + 19BB911B697D4C6D2FCC486E3FF18755 /* PBXTargetDependency */, + 4C52CEA9C66F75DD0FD072FBA9856F4D /* PBXTargetDependency */, + 251C2D2D031821C238EDE92E11483F22 /* PBXTargetDependency */, + C7286D42D4EABC1BDCB8CAF99535BC74 /* PBXTargetDependency */, + A30DD297C02CB03F20C6C1A6A7BE0920 /* PBXTargetDependency */, + DD07926F8C28DC3BA6E581BF06927A2F /* PBXTargetDependency */, + ); + name = "Pods-DiplomProject"; + productName = "Pods-DiplomProject"; + productReference = 1328D094615B82F9841F8F6EABF6D506 /* Pods_DiplomProject.framework */; productType = "com.apple.product-type.framework"; }; E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */ = { @@ -2507,7 +2507,7 @@ LastUpgradeCheck = 1100; }; buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 10.0"; + compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -2515,13 +2515,13 @@ Base, ); mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 6A8B940AFFF1141846E92F9A9B1FEB51 /* Products */; + productRefGroup = CC8EE40723D7B73B12ED8537C0A2B6EA /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */, 3EF3490B4B0DD7F07469ADEE907B9E59 /* DTTableViewManager */, - B0C3941F7472DEBFD2FC317AA7469DF1 /* Pods-Lesson14 */, + A4F4BA620B813F46AE18CA22D4C61EDC /* Pods-DiplomProject */, 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */, 782725687624F8665247B84AB581BEB1 /* RealmSwift */, 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */, @@ -2533,42 +2533,42 @@ /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 12218AC9902A620A96A491310D2ACF39 /* Resources */ = { + 13B653C20CC1D0B28162EEB3B2D27AE7 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 13B653C20CC1D0B28162EEB3B2D27AE7 /* Resources */ = { + 2E56BAEC8FC1712ABED087B85C390643 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 2E56BAEC8FC1712ABED087B85C390643 /* Resources */ = { + 6E8C1AE67879928E1C17593D9565D540 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 6E8C1AE67879928E1C17593D9565D540 /* Resources */ = { + 76BE90AD3450229977577041A0B3137B /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 76BE90AD3450229977577041A0B3137B /* Resources */ = { + 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */ = { + BBC9C24F086A359062FEF57D8000E72A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -2739,6 +2739,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 4A51719E172F9DA3D0B857E6A2930FC7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ED8360829F96DB7655A4359EB8613B05 /* Pods-DiplomProject-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 4C3D851FEBEB90EA47E2CCD1A8900D81 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -3106,52 +3114,38 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - FF1E9205411404BF84CB669B83F428B3 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - AC0B01497BE3B04DE61C61CCE1EC51E2 /* Pods-Lesson14-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 0162B1DBD18B05C2A5E2A064DF2B226A /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Realm; - target = 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */; - targetProxy = 27EE226844E562BB17582F427CB146C4 /* PBXContainerItemProxy */; - }; - 1DDB6B15DE353481466AECAA6218BB3A /* PBXTargetDependency */ = { + 0E8E3AAEDDF6C9CBAA53C18F6FDA05E4 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = DTTableViewManager; target = 3EF3490B4B0DD7F07469ADEE907B9E59 /* DTTableViewManager */; - targetProxy = 756BF60843A1E9E639A3BB2EC8CD216A /* PBXContainerItemProxy */; + targetProxy = 03C3979BE1EC7C39874C8A462B597FB9 /* PBXContainerItemProxy */; }; - 55CD9FF0DEFE71F420D1927C9F7041EB /* PBXTargetDependency */ = { + 19BB911B697D4C6D2FCC486E3FF18755 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = RxCocoa; - target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; - targetProxy = F5186B6EC1A56D996136149A37078758 /* PBXContainerItemProxy */; + name = Realm; + target = 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */; + targetProxy = F2CF206110B8EA94052D1CD67B58E0A7 /* PBXContainerItemProxy */; }; - 573F8FF351F0F1AAB796DAE14F0B18F1 /* PBXTargetDependency */ = { + 251C2D2D031821C238EDE92E11483F22 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = RxRelay; - target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; - targetProxy = 07E45B0AFEEED2846D13571956E582B3 /* PBXContainerItemProxy */; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = 04C6FFBC0EEEB7B26E6BA648AB99C579 /* PBXContainerItemProxy */; }; - 5B142144E98301F6801AE08EC8970CD1 /* PBXTargetDependency */ = { + 4C52CEA9C66F75DD0FD072FBA9856F4D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = RealmSwift; target = 782725687624F8665247B84AB581BEB1 /* RealmSwift */; - targetProxy = C00E48E5E3A99D86267F0C1D0DEF8A7F /* PBXContainerItemProxy */; + targetProxy = 4A442662546A638F8703AFD87641B74D /* PBXContainerItemProxy */; }; - 7D428BCC95E3CEAA192881BF2D259EB8 /* PBXTargetDependency */ = { + 573F8FF351F0F1AAB796DAE14F0B18F1 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SnapKit; - target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; - targetProxy = 2806DFE021724FE2A170FA769505C588 /* PBXContainerItemProxy */; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 07E45B0AFEEED2846D13571956E582B3 /* PBXContainerItemProxy */; }; 904D619A8DD745E4591136B946231ACB /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -3159,11 +3153,11 @@ target = E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */; targetProxy = 38798EE4C9A9293F3745F976F22ADABC /* PBXContainerItemProxy */; }; - 947E049CC4473F7D4B150F546C433257 /* PBXTargetDependency */ = { + 97E7C5DFDFA8803A26EFA8754A9FD5C7 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = RxRelay; - target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; - targetProxy = 98932432ED5F0A43DA179C5B350F646C /* PBXContainerItemProxy */; + name = DTModelStorage; + target = E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */; + targetProxy = 612452682302E0F2605732313104C46B /* PBXContainerItemProxy */; }; 9CC239530FF1F8F22ED406CAD9C614F6 /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -3171,11 +3165,11 @@ target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; targetProxy = 04142E1DB41EC92EB296F3E757BCE4B7 /* PBXContainerItemProxy */; }; - ADF5BE5BEA21582215FD2E8A56C5C0E7 /* PBXTargetDependency */ = { + A30DD297C02CB03F20C6C1A6A7BE0920 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = DTModelStorage; - target = E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */; - targetProxy = 2502EA8234B4134CC6CCD79B35CD8171 /* PBXContainerItemProxy */; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = D63EE6701221171E23062256E58FC8AE /* PBXContainerItemProxy */; }; B0F2CB59E7E3549DFC145C2E0973B40E /* PBXTargetDependency */ = { isa = PBXTargetDependency; @@ -3183,17 +3177,23 @@ target = 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */; targetProxy = 2241096BF52D154C2390A33A7C459082 /* PBXContainerItemProxy */; }; + C7286D42D4EABC1BDCB8CAF99535BC74 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 3FDE3B12860E9615FEA8811F78ED17B2 /* PBXContainerItemProxy */; + }; CCCA4B7752069A69459186957330D49D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = RxSwift; target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; targetProxy = 3AA5F122E4B6C1CDC8306AE3F5C627D8 /* PBXContainerItemProxy */; }; - D330E08C8B590F1554134A5FEB72D84B /* PBXTargetDependency */ = { + DD07926F8C28DC3BA6E581BF06927A2F /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = RxSwift; - target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; - targetProxy = BCC8D6EA14ECD36D30063FC642910A60 /* PBXContainerItemProxy */; + name = SnapKit; + target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; + targetProxy = 38F8DDEF18D21DDC6590B672109819AB /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -3484,10 +3484,12 @@ }; name = Debug; }; - 7095013B95D75BE17FD8027ECC325D00 /* Release */ = { + 61942C18A802D48BF8A3D314FB5ADF15 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 3601F5078118EFBB071FA7D5BE73D356 /* DTModelStorage.xcconfig */; + baseConfigurationReference = 6FFA10D5C5E8898EB8C382B4722CD292 /* Pods-DiplomProject.release.xcconfig */; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -3497,22 +3499,23 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/DTModelStorage/DTModelStorage-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/DTModelStorage/DTModelStorage-Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); - MODULEMAP_FILE = "Target Support Files/DTModelStorage/DTModelStorage.modulemap"; - PRODUCT_MODULE_NAME = DTModelStorage; - PRODUCT_NAME = DTModelStorage; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -3520,10 +3523,12 @@ }; name = Release; }; - 76B04784E199F9E057C51FBC85B40AF9 /* Debug */ = { + 6FCC954F5ED11C8E1B1B7556A511C793 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1E49969559DCD111868A299A6FC207FE /* Realm.xcconfig */; + baseConfigurationReference = E7C8AFE38022614F01148D03831E6330 /* Pods-DiplomProject.debug.xcconfig */; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -3533,8 +3538,44 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Realm/Realm-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Realm/Realm-Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-DiplomProject/Pods-DiplomProject.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 7095013B95D75BE17FD8027ECC325D00 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3601F5078118EFBB071FA7D5BE73D356 /* DTModelStorage.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/DTModelStorage/DTModelStorage-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/DTModelStorage/DTModelStorage-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = ( @@ -3542,25 +3583,24 @@ "@executable_path/Frameworks", "@loader_path/Frameworks", ); - MODULEMAP_FILE = "Target Support Files/Realm/Realm.modulemap"; - PRODUCT_MODULE_NAME = Realm; - PRODUCT_NAME = Realm; + MODULEMAP_FILE = "Target Support Files/DTModelStorage/DTModelStorage.modulemap"; + PRODUCT_MODULE_NAME = DTModelStorage; + PRODUCT_NAME = DTModelStorage; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - 88F6CC4B22F1BB2C8C4C94D6023B0754 /* Debug */ = { + 76B04784E199F9E057C51FBC85B40AF9 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 0FF3DDD2ABDF1E4BF6329FE7DE4A7292 /* Pods-Lesson14.debug.xcconfig */; + baseConfigurationReference = 1E49969559DCD111868A299A6FC207FE /* Realm.xcconfig */; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -3570,23 +3610,22 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson14/Pods-Lesson14-Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/Realm/Realm-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Realm/Realm-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson14/Pods-Lesson14.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + MODULEMAP_FILE = "Target Support Files/Realm/Realm.modulemap"; + PRODUCT_MODULE_NAME = Realm; + PRODUCT_NAME = Realm; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -3834,45 +3873,6 @@ }; name = Release; }; - D63B9A6F996149BFA6652774D3CAD4A6 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 8B0BAA65B5FF348ED9DA6AAB1A2DB6DD /* Pods-Lesson14.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson14/Pods-Lesson14-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson14/Pods-Lesson14.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; ECB437504DF805BD96CAABF97400B526 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -3972,6 +3972,15 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 0DA7F9A4F9DE964785982338CB002AA6 /* Build configuration list for PBXNativeTarget "Pods-DiplomProject" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6FCC954F5ED11C8E1B1B7556A511C793 /* Debug */, + 61942C18A802D48BF8A3D314FB5ADF15 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 1A342D90638B02D992A14313597765C2 /* Build configuration list for PBXNativeTarget "DTTableViewManager" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -4017,15 +4026,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 87212F28B46D140A3FF0327A2E5A422C /* Build configuration list for PBXNativeTarget "Pods-Lesson14" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 88F6CC4B22F1BB2C8C4C94D6023B0754 /* Debug */, - D63B9A6F996149BFA6652774D3CAD4A6 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; BA6271B202E8EC84ACB5775DDA67F32F /* Build configuration list for PBXNativeTarget "DTModelStorage" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Lesson12/Pods/Realm/LICENSE b/DiplomProject/Pods/Realm/LICENSE similarity index 100% rename from Lesson12/Pods/Realm/LICENSE rename to DiplomProject/Pods/Realm/LICENSE diff --git a/Lesson12/Pods/Realm/README.md b/DiplomProject/Pods/Realm/README.md similarity index 100% rename from Lesson12/Pods/Realm/README.md rename to DiplomProject/Pods/Realm/README.md diff --git a/Lesson12/Pods/Realm/Realm/NSError+RLMSync.m b/DiplomProject/Pods/Realm/Realm/NSError+RLMSync.m similarity index 100% rename from Lesson12/Pods/Realm/Realm/NSError+RLMSync.m rename to DiplomProject/Pods/Realm/Realm/NSError+RLMSync.m diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/index_set.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/index_set.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/index_set.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/index_set.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/list.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/list.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/list.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/list.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/object.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/object.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/object.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/object.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/object_store.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/object_store.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/object_store.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/object_store.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/results.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/results.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/results.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/results.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/schema.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/schema.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/schema.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/schema.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp diff --git a/Lesson12/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp b/DiplomProject/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp similarity index 100% rename from Lesson12/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp rename to DiplomProject/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp diff --git a/Lesson12/Pods/Realm/Realm/RLMAccessor.mm b/DiplomProject/Pods/Realm/Realm/RLMAccessor.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMAccessor.mm rename to DiplomProject/Pods/Realm/Realm/RLMAccessor.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMAnalytics.mm b/DiplomProject/Pods/Realm/Realm/RLMAnalytics.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMAnalytics.mm rename to DiplomProject/Pods/Realm/Realm/RLMAnalytics.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMArray.mm b/DiplomProject/Pods/Realm/Realm/RLMArray.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMArray.mm rename to DiplomProject/Pods/Realm/Realm/RLMArray.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMClassInfo.mm b/DiplomProject/Pods/Realm/Realm/RLMClassInfo.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMClassInfo.mm rename to DiplomProject/Pods/Realm/Realm/RLMClassInfo.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMCollection.mm b/DiplomProject/Pods/Realm/Realm/RLMCollection.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMCollection.mm rename to DiplomProject/Pods/Realm/Realm/RLMCollection.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMConstants.m b/DiplomProject/Pods/Realm/Realm/RLMConstants.m similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMConstants.m rename to DiplomProject/Pods/Realm/Realm/RLMConstants.m diff --git a/Lesson12/Pods/Realm/Realm/RLMJSONModels.m b/DiplomProject/Pods/Realm/Realm/RLMJSONModels.m similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMJSONModels.m rename to DiplomProject/Pods/Realm/Realm/RLMJSONModels.m diff --git a/Lesson12/Pods/Realm/Realm/RLMListBase.mm b/DiplomProject/Pods/Realm/Realm/RLMListBase.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMListBase.mm rename to DiplomProject/Pods/Realm/Realm/RLMListBase.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMManagedArray.mm b/DiplomProject/Pods/Realm/Realm/RLMManagedArray.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMManagedArray.mm rename to DiplomProject/Pods/Realm/Realm/RLMManagedArray.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMMigration.mm b/DiplomProject/Pods/Realm/Realm/RLMMigration.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMMigration.mm rename to DiplomProject/Pods/Realm/Realm/RLMMigration.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMNetworkClient.mm b/DiplomProject/Pods/Realm/Realm/RLMNetworkClient.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMNetworkClient.mm rename to DiplomProject/Pods/Realm/Realm/RLMNetworkClient.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMObject.mm b/DiplomProject/Pods/Realm/Realm/RLMObject.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMObject.mm rename to DiplomProject/Pods/Realm/Realm/RLMObject.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMObjectBase.mm b/DiplomProject/Pods/Realm/Realm/RLMObjectBase.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMObjectBase.mm rename to DiplomProject/Pods/Realm/Realm/RLMObjectBase.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMObjectSchema.mm b/DiplomProject/Pods/Realm/Realm/RLMObjectSchema.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMObjectSchema.mm rename to DiplomProject/Pods/Realm/Realm/RLMObjectSchema.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMObjectStore.mm b/DiplomProject/Pods/Realm/Realm/RLMObjectStore.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMObjectStore.mm rename to DiplomProject/Pods/Realm/Realm/RLMObjectStore.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMObservation.mm b/DiplomProject/Pods/Realm/Realm/RLMObservation.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMObservation.mm rename to DiplomProject/Pods/Realm/Realm/RLMObservation.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMOptionalBase.mm b/DiplomProject/Pods/Realm/Realm/RLMOptionalBase.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMOptionalBase.mm rename to DiplomProject/Pods/Realm/Realm/RLMOptionalBase.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMPredicateUtil.mm b/DiplomProject/Pods/Realm/Realm/RLMPredicateUtil.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMPredicateUtil.mm rename to DiplomProject/Pods/Realm/Realm/RLMPredicateUtil.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMProperty.mm b/DiplomProject/Pods/Realm/Realm/RLMProperty.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMProperty.mm rename to DiplomProject/Pods/Realm/Realm/RLMProperty.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMQueryUtil.mm b/DiplomProject/Pods/Realm/Realm/RLMQueryUtil.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMQueryUtil.mm rename to DiplomProject/Pods/Realm/Realm/RLMQueryUtil.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMRealm+Sync.mm b/DiplomProject/Pods/Realm/Realm/RLMRealm+Sync.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMRealm+Sync.mm rename to DiplomProject/Pods/Realm/Realm/RLMRealm+Sync.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMRealm.mm b/DiplomProject/Pods/Realm/Realm/RLMRealm.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMRealm.mm rename to DiplomProject/Pods/Realm/Realm/RLMRealm.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm b/DiplomProject/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm rename to DiplomProject/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMRealmConfiguration.mm b/DiplomProject/Pods/Realm/Realm/RLMRealmConfiguration.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMRealmConfiguration.mm rename to DiplomProject/Pods/Realm/Realm/RLMRealmConfiguration.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMRealmUtil.mm b/DiplomProject/Pods/Realm/Realm/RLMRealmUtil.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMRealmUtil.mm rename to DiplomProject/Pods/Realm/Realm/RLMRealmUtil.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMResults.mm b/DiplomProject/Pods/Realm/Realm/RLMResults.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMResults.mm rename to DiplomProject/Pods/Realm/Realm/RLMResults.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSchema.mm b/DiplomProject/Pods/Realm/Realm/RLMSchema.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSchema.mm rename to DiplomProject/Pods/Realm/Realm/RLMSchema.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSwiftSupport.m b/DiplomProject/Pods/Realm/Realm/RLMSwiftSupport.m similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSwiftSupport.m rename to DiplomProject/Pods/Realm/Realm/RLMSwiftSupport.m diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncConfiguration.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncConfiguration.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncConfiguration.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncConfiguration.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncCredentials.m b/DiplomProject/Pods/Realm/Realm/RLMSyncCredentials.m similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncCredentials.m rename to DiplomProject/Pods/Realm/Realm/RLMSyncCredentials.m diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncManager.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncManager.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncManager.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncManager.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncPermission.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncPermission.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncPermission.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncPermission.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncSession.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncSession.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncSession.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncSession.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncSubscription.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncSubscription.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncSubscription.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncSubscription.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncUser.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncUser.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncUser.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncUser.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMSyncUtil.mm b/DiplomProject/Pods/Realm/Realm/RLMSyncUtil.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMSyncUtil.mm rename to DiplomProject/Pods/Realm/Realm/RLMSyncUtil.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMThreadSafeReference.mm b/DiplomProject/Pods/Realm/Realm/RLMThreadSafeReference.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMThreadSafeReference.mm rename to DiplomProject/Pods/Realm/Realm/RLMThreadSafeReference.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMUpdateChecker.mm b/DiplomProject/Pods/Realm/Realm/RLMUpdateChecker.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMUpdateChecker.mm rename to DiplomProject/Pods/Realm/Realm/RLMUpdateChecker.mm diff --git a/Lesson12/Pods/Realm/Realm/RLMUtil.mm b/DiplomProject/Pods/Realm/Realm/RLMUtil.mm similarity index 100% rename from Lesson12/Pods/Realm/Realm/RLMUtil.mm rename to DiplomProject/Pods/Realm/Realm/RLMUtil.mm diff --git a/Lesson12/Pods/Realm/Realm/Realm.modulemap b/DiplomProject/Pods/Realm/Realm/Realm.modulemap similarity index 100% rename from Lesson12/Pods/Realm/Realm/Realm.modulemap rename to DiplomProject/Pods/Realm/Realm/Realm.modulemap diff --git a/Lesson12/Pods/Realm/build.sh b/DiplomProject/Pods/Realm/build.sh similarity index 100% rename from Lesson12/Pods/Realm/build.sh rename to DiplomProject/Pods/Realm/build.sh diff --git a/Lesson12/Pods/Realm/core/librealmcore-ios.a b/DiplomProject/Pods/Realm/core/librealmcore-ios.a similarity index 100% rename from Lesson12/Pods/Realm/core/librealmcore-ios.a rename to DiplomProject/Pods/Realm/core/librealmcore-ios.a diff --git a/Lesson12/Pods/Realm/include/NSError+RLMSync.h b/DiplomProject/Pods/Realm/include/NSError+RLMSync.h similarity index 100% rename from Lesson12/Pods/Realm/include/NSError+RLMSync.h rename to DiplomProject/Pods/Realm/include/NSError+RLMSync.h diff --git a/Lesson12/Pods/Realm/include/RLMAccessor.h b/DiplomProject/Pods/Realm/include/RLMAccessor.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMAccessor.h rename to DiplomProject/Pods/Realm/include/RLMAccessor.h diff --git a/Lesson12/Pods/Realm/include/RLMAccessor.hpp b/DiplomProject/Pods/Realm/include/RLMAccessor.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMAccessor.hpp rename to DiplomProject/Pods/Realm/include/RLMAccessor.hpp diff --git a/Lesson12/Pods/Realm/include/RLMAnalytics.hpp b/DiplomProject/Pods/Realm/include/RLMAnalytics.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMAnalytics.hpp rename to DiplomProject/Pods/Realm/include/RLMAnalytics.hpp diff --git a/Lesson12/Pods/Realm/include/RLMArray.h b/DiplomProject/Pods/Realm/include/RLMArray.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMArray.h rename to DiplomProject/Pods/Realm/include/RLMArray.h diff --git a/Lesson12/Pods/Realm/include/RLMArray_Private.h b/DiplomProject/Pods/Realm/include/RLMArray_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMArray_Private.h rename to DiplomProject/Pods/Realm/include/RLMArray_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMArray_Private.hpp b/DiplomProject/Pods/Realm/include/RLMArray_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMArray_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMArray_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMClassInfo.hpp b/DiplomProject/Pods/Realm/include/RLMClassInfo.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMClassInfo.hpp rename to DiplomProject/Pods/Realm/include/RLMClassInfo.hpp diff --git a/Lesson12/Pods/Realm/include/RLMCollection.h b/DiplomProject/Pods/Realm/include/RLMCollection.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMCollection.h rename to DiplomProject/Pods/Realm/include/RLMCollection.h diff --git a/Lesson12/Pods/Realm/include/RLMCollection_Private.h b/DiplomProject/Pods/Realm/include/RLMCollection_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMCollection_Private.h rename to DiplomProject/Pods/Realm/include/RLMCollection_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMCollection_Private.hpp b/DiplomProject/Pods/Realm/include/RLMCollection_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMCollection_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMCollection_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMConstants.h b/DiplomProject/Pods/Realm/include/RLMConstants.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMConstants.h rename to DiplomProject/Pods/Realm/include/RLMConstants.h diff --git a/Lesson12/Pods/Realm/include/RLMJSONModels.h b/DiplomProject/Pods/Realm/include/RLMJSONModels.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMJSONModels.h rename to DiplomProject/Pods/Realm/include/RLMJSONModels.h diff --git a/Lesson12/Pods/Realm/include/RLMListBase.h b/DiplomProject/Pods/Realm/include/RLMListBase.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMListBase.h rename to DiplomProject/Pods/Realm/include/RLMListBase.h diff --git a/Lesson12/Pods/Realm/include/RLMMigration.h b/DiplomProject/Pods/Realm/include/RLMMigration.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMMigration.h rename to DiplomProject/Pods/Realm/include/RLMMigration.h diff --git a/Lesson12/Pods/Realm/include/RLMMigration_Private.h b/DiplomProject/Pods/Realm/include/RLMMigration_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMMigration_Private.h rename to DiplomProject/Pods/Realm/include/RLMMigration_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMNetworkClient.h b/DiplomProject/Pods/Realm/include/RLMNetworkClient.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMNetworkClient.h rename to DiplomProject/Pods/Realm/include/RLMNetworkClient.h diff --git a/Lesson12/Pods/Realm/include/RLMObject.h b/DiplomProject/Pods/Realm/include/RLMObject.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObject.h rename to DiplomProject/Pods/Realm/include/RLMObject.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectBase.h b/DiplomProject/Pods/Realm/include/RLMObjectBase.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectBase.h rename to DiplomProject/Pods/Realm/include/RLMObjectBase.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectBase_Dynamic.h b/DiplomProject/Pods/Realm/include/RLMObjectBase_Dynamic.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectBase_Dynamic.h rename to DiplomProject/Pods/Realm/include/RLMObjectBase_Dynamic.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectBase_Private.h b/DiplomProject/Pods/Realm/include/RLMObjectBase_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectBase_Private.h rename to DiplomProject/Pods/Realm/include/RLMObjectBase_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectSchema.h b/DiplomProject/Pods/Realm/include/RLMObjectSchema.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectSchema.h rename to DiplomProject/Pods/Realm/include/RLMObjectSchema.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectSchema_Private.h b/DiplomProject/Pods/Realm/include/RLMObjectSchema_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectSchema_Private.h rename to DiplomProject/Pods/Realm/include/RLMObjectSchema_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMObjectSchema_Private.hpp b/DiplomProject/Pods/Realm/include/RLMObjectSchema_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectSchema_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMObjectSchema_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMObjectStore.h b/DiplomProject/Pods/Realm/include/RLMObjectStore.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObjectStore.h rename to DiplomProject/Pods/Realm/include/RLMObjectStore.h diff --git a/Lesson12/Pods/Realm/include/RLMObject_Private.h b/DiplomProject/Pods/Realm/include/RLMObject_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObject_Private.h rename to DiplomProject/Pods/Realm/include/RLMObject_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMObject_Private.hpp b/DiplomProject/Pods/Realm/include/RLMObject_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObject_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMObject_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMObservation.hpp b/DiplomProject/Pods/Realm/include/RLMObservation.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMObservation.hpp rename to DiplomProject/Pods/Realm/include/RLMObservation.hpp diff --git a/Lesson12/Pods/Realm/include/RLMOptionalBase.h b/DiplomProject/Pods/Realm/include/RLMOptionalBase.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMOptionalBase.h rename to DiplomProject/Pods/Realm/include/RLMOptionalBase.h diff --git a/Lesson12/Pods/Realm/include/RLMPlatform.h b/DiplomProject/Pods/Realm/include/RLMPlatform.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMPlatform.h rename to DiplomProject/Pods/Realm/include/RLMPlatform.h diff --git a/Lesson12/Pods/Realm/include/RLMPredicateUtil.hpp b/DiplomProject/Pods/Realm/include/RLMPredicateUtil.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMPredicateUtil.hpp rename to DiplomProject/Pods/Realm/include/RLMPredicateUtil.hpp diff --git a/Lesson12/Pods/Realm/include/RLMPrefix.h b/DiplomProject/Pods/Realm/include/RLMPrefix.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMPrefix.h rename to DiplomProject/Pods/Realm/include/RLMPrefix.h diff --git a/Lesson12/Pods/Realm/include/RLMProperty.h b/DiplomProject/Pods/Realm/include/RLMProperty.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMProperty.h rename to DiplomProject/Pods/Realm/include/RLMProperty.h diff --git a/Lesson12/Pods/Realm/include/RLMProperty_Private.h b/DiplomProject/Pods/Realm/include/RLMProperty_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMProperty_Private.h rename to DiplomProject/Pods/Realm/include/RLMProperty_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMProperty_Private.hpp b/DiplomProject/Pods/Realm/include/RLMProperty_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMProperty_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMProperty_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMQueryUtil.hpp b/DiplomProject/Pods/Realm/include/RLMQueryUtil.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMQueryUtil.hpp rename to DiplomProject/Pods/Realm/include/RLMQueryUtil.hpp diff --git a/Lesson12/Pods/Realm/include/RLMRealm+Sync.h b/DiplomProject/Pods/Realm/include/RLMRealm+Sync.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealm+Sync.h rename to DiplomProject/Pods/Realm/include/RLMRealm+Sync.h diff --git a/Lesson12/Pods/Realm/include/RLMRealm.h b/DiplomProject/Pods/Realm/include/RLMRealm.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealm.h rename to DiplomProject/Pods/Realm/include/RLMRealm.h diff --git a/Lesson12/Pods/Realm/include/RLMRealmConfiguration+Sync.h b/DiplomProject/Pods/Realm/include/RLMRealmConfiguration+Sync.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealmConfiguration+Sync.h rename to DiplomProject/Pods/Realm/include/RLMRealmConfiguration+Sync.h diff --git a/Lesson12/Pods/Realm/include/RLMRealmConfiguration.h b/DiplomProject/Pods/Realm/include/RLMRealmConfiguration.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealmConfiguration.h rename to DiplomProject/Pods/Realm/include/RLMRealmConfiguration.h diff --git a/Lesson12/Pods/Realm/include/RLMRealmConfiguration_Private.h b/DiplomProject/Pods/Realm/include/RLMRealmConfiguration_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealmConfiguration_Private.h rename to DiplomProject/Pods/Realm/include/RLMRealmConfiguration_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMRealmConfiguration_Private.hpp b/DiplomProject/Pods/Realm/include/RLMRealmConfiguration_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealmConfiguration_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMRealmConfiguration_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMRealmUtil.hpp b/DiplomProject/Pods/Realm/include/RLMRealmUtil.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealmUtil.hpp rename to DiplomProject/Pods/Realm/include/RLMRealmUtil.hpp diff --git a/Lesson12/Pods/Realm/include/RLMRealm_Dynamic.h b/DiplomProject/Pods/Realm/include/RLMRealm_Dynamic.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealm_Dynamic.h rename to DiplomProject/Pods/Realm/include/RLMRealm_Dynamic.h diff --git a/Lesson12/Pods/Realm/include/RLMRealm_Private.h b/DiplomProject/Pods/Realm/include/RLMRealm_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealm_Private.h rename to DiplomProject/Pods/Realm/include/RLMRealm_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMRealm_Private.hpp b/DiplomProject/Pods/Realm/include/RLMRealm_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMRealm_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMRealm_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMResults.h b/DiplomProject/Pods/Realm/include/RLMResults.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMResults.h rename to DiplomProject/Pods/Realm/include/RLMResults.h diff --git a/Lesson12/Pods/Realm/include/RLMResults_Private.h b/DiplomProject/Pods/Realm/include/RLMResults_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMResults_Private.h rename to DiplomProject/Pods/Realm/include/RLMResults_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMResults_Private.hpp b/DiplomProject/Pods/Realm/include/RLMResults_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMResults_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMResults_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSchema.h b/DiplomProject/Pods/Realm/include/RLMSchema.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSchema.h rename to DiplomProject/Pods/Realm/include/RLMSchema.h diff --git a/Lesson12/Pods/Realm/include/RLMSchema_Private.h b/DiplomProject/Pods/Realm/include/RLMSchema_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSchema_Private.h rename to DiplomProject/Pods/Realm/include/RLMSchema_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMSchema_Private.hpp b/DiplomProject/Pods/Realm/include/RLMSchema_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSchema_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMSchema_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSwiftBridgingHeader.h b/DiplomProject/Pods/Realm/include/RLMSwiftBridgingHeader.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSwiftBridgingHeader.h rename to DiplomProject/Pods/Realm/include/RLMSwiftBridgingHeader.h diff --git a/Lesson12/Pods/Realm/include/RLMSwiftSupport.h b/DiplomProject/Pods/Realm/include/RLMSwiftSupport.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSwiftSupport.h rename to DiplomProject/Pods/Realm/include/RLMSwiftSupport.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncConfiguration.h b/DiplomProject/Pods/Realm/include/RLMSyncConfiguration.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncConfiguration.h rename to DiplomProject/Pods/Realm/include/RLMSyncConfiguration.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncConfiguration_Private.h b/DiplomProject/Pods/Realm/include/RLMSyncConfiguration_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncConfiguration_Private.h rename to DiplomProject/Pods/Realm/include/RLMSyncConfiguration_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncConfiguration_Private.hpp b/DiplomProject/Pods/Realm/include/RLMSyncConfiguration_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncConfiguration_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMSyncConfiguration_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSyncCredentials.h b/DiplomProject/Pods/Realm/include/RLMSyncCredentials.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncCredentials.h rename to DiplomProject/Pods/Realm/include/RLMSyncCredentials.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncManager.h b/DiplomProject/Pods/Realm/include/RLMSyncManager.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncManager.h rename to DiplomProject/Pods/Realm/include/RLMSyncManager.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncManager_Private.h b/DiplomProject/Pods/Realm/include/RLMSyncManager_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncManager_Private.h rename to DiplomProject/Pods/Realm/include/RLMSyncManager_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncPermission.h b/DiplomProject/Pods/Realm/include/RLMSyncPermission.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncPermission.h rename to DiplomProject/Pods/Realm/include/RLMSyncPermission.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncSession.h b/DiplomProject/Pods/Realm/include/RLMSyncSession.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncSession.h rename to DiplomProject/Pods/Realm/include/RLMSyncSession.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncSessionRefreshHandle.h b/DiplomProject/Pods/Realm/include/RLMSyncSessionRefreshHandle.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncSessionRefreshHandle.h rename to DiplomProject/Pods/Realm/include/RLMSyncSessionRefreshHandle.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp b/DiplomProject/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp rename to DiplomProject/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSyncSession_Private.hpp b/DiplomProject/Pods/Realm/include/RLMSyncSession_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncSession_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMSyncSession_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSyncSubscription.h b/DiplomProject/Pods/Realm/include/RLMSyncSubscription.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncSubscription.h rename to DiplomProject/Pods/Realm/include/RLMSyncSubscription.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncUser.h b/DiplomProject/Pods/Realm/include/RLMSyncUser.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncUser.h rename to DiplomProject/Pods/Realm/include/RLMSyncUser.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncUser_Private.hpp b/DiplomProject/Pods/Realm/include/RLMSyncUser_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncUser_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMSyncUser_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMSyncUtil.h b/DiplomProject/Pods/Realm/include/RLMSyncUtil.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncUtil.h rename to DiplomProject/Pods/Realm/include/RLMSyncUtil.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncUtil_Private.h b/DiplomProject/Pods/Realm/include/RLMSyncUtil_Private.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncUtil_Private.h rename to DiplomProject/Pods/Realm/include/RLMSyncUtil_Private.h diff --git a/Lesson12/Pods/Realm/include/RLMSyncUtil_Private.hpp b/DiplomProject/Pods/Realm/include/RLMSyncUtil_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMSyncUtil_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMSyncUtil_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMThreadSafeReference.h b/DiplomProject/Pods/Realm/include/RLMThreadSafeReference.h similarity index 100% rename from Lesson12/Pods/Realm/include/RLMThreadSafeReference.h rename to DiplomProject/Pods/Realm/include/RLMThreadSafeReference.h diff --git a/Lesson12/Pods/Realm/include/RLMThreadSafeReference_Private.hpp b/DiplomProject/Pods/Realm/include/RLMThreadSafeReference_Private.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMThreadSafeReference_Private.hpp rename to DiplomProject/Pods/Realm/include/RLMThreadSafeReference_Private.hpp diff --git a/Lesson12/Pods/Realm/include/RLMUpdateChecker.hpp b/DiplomProject/Pods/Realm/include/RLMUpdateChecker.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMUpdateChecker.hpp rename to DiplomProject/Pods/Realm/include/RLMUpdateChecker.hpp diff --git a/Lesson12/Pods/Realm/include/RLMUtil.hpp b/DiplomProject/Pods/Realm/include/RLMUtil.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/RLMUtil.hpp rename to DiplomProject/Pods/Realm/include/RLMUtil.hpp diff --git a/Lesson12/Pods/Realm/include/Realm.h b/DiplomProject/Pods/Realm/include/Realm.h similarity index 100% rename from Lesson12/Pods/Realm/include/Realm.h rename to DiplomProject/Pods/Realm/include/Realm.h diff --git a/Lesson12/Pods/Realm/include/audit.hpp b/DiplomProject/Pods/Realm/include/audit.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/audit.hpp rename to DiplomProject/Pods/Realm/include/audit.hpp diff --git a/Lesson12/Pods/Realm/include/binding_callback_thread_observer.hpp b/DiplomProject/Pods/Realm/include/binding_callback_thread_observer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/binding_callback_thread_observer.hpp rename to DiplomProject/Pods/Realm/include/binding_callback_thread_observer.hpp diff --git a/Lesson12/Pods/Realm/include/binding_context.hpp b/DiplomProject/Pods/Realm/include/binding_context.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/binding_context.hpp rename to DiplomProject/Pods/Realm/include/binding_context.hpp diff --git a/Lesson12/Pods/Realm/include/collection_notifications.hpp b/DiplomProject/Pods/Realm/include/collection_notifications.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/collection_notifications.hpp rename to DiplomProject/Pods/Realm/include/collection_notifications.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm.hpp b/DiplomProject/Pods/Realm/include/core/realm.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm.hpp rename to DiplomProject/Pods/Realm/include/core/realm.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/alloc.hpp b/DiplomProject/Pods/Realm/include/core/realm/alloc.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/alloc.hpp rename to DiplomProject/Pods/Realm/include/core/realm/alloc.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/alloc_slab.hpp b/DiplomProject/Pods/Realm/include/core/realm/alloc_slab.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/alloc_slab.hpp rename to DiplomProject/Pods/Realm/include/core/realm/alloc_slab.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array.hpp b/DiplomProject/Pods/Realm/include/core/realm/array.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_basic.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_basic.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_basic.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_basic.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_basic_tpl.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_basic_tpl.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_basic_tpl.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_basic_tpl.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_binary.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_binary.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_binary.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_binary.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_blob.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_blob.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_blob.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_blob.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_blobs_big.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_blobs_big.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_blobs_big.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_blobs_big.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_direct.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_direct.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_direct.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_direct.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_integer.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_integer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_integer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_integer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_string.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_string.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_string.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_string.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/array_string_long.hpp b/DiplomProject/Pods/Realm/include/core/realm/array_string_long.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/array_string_long.hpp rename to DiplomProject/Pods/Realm/include/core/realm/array_string_long.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/binary_data.hpp b/DiplomProject/Pods/Realm/include/core/realm/binary_data.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/binary_data.hpp rename to DiplomProject/Pods/Realm/include/core/realm/binary_data.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/bptree.hpp b/DiplomProject/Pods/Realm/include/core/realm/bptree.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/bptree.hpp rename to DiplomProject/Pods/Realm/include/core/realm/bptree.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/chunked_binary.hpp b/DiplomProject/Pods/Realm/include/core/realm/chunked_binary.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/chunked_binary.hpp rename to DiplomProject/Pods/Realm/include/core/realm/chunked_binary.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column.hpp b/DiplomProject/Pods/Realm/include/core/realm/column.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_backlink.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_backlink.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_backlink.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_backlink.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_binary.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_binary.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_binary.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_binary.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_fwd.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_fwd.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_fwd.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_fwd.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_link.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_link.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_link.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_link.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_linkbase.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_linkbase.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_linkbase.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_linkbase.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_linklist.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_linklist.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_linklist.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_linklist.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_mixed.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_mixed.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_mixed.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_mixed.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_mixed_tpl.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_mixed_tpl.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_mixed_tpl.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_mixed_tpl.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_string.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_string.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_string.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_string.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_string_enum.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_string_enum.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_string_enum.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_string_enum.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_table.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_table.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_table.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_table.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_timestamp.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_timestamp.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_timestamp.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_timestamp.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_tpl.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_tpl.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_tpl.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_tpl.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_type.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_type.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_type.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_type.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/column_type_traits.hpp b/DiplomProject/Pods/Realm/include/core/realm/column_type_traits.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/column_type_traits.hpp rename to DiplomProject/Pods/Realm/include/core/realm/column_type_traits.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/data_type.hpp b/DiplomProject/Pods/Realm/include/core/realm/data_type.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/data_type.hpp rename to DiplomProject/Pods/Realm/include/core/realm/data_type.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/descriptor.hpp b/DiplomProject/Pods/Realm/include/core/realm/descriptor.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/descriptor.hpp rename to DiplomProject/Pods/Realm/include/core/realm/descriptor.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/descriptor_fwd.hpp b/DiplomProject/Pods/Realm/include/core/realm/descriptor_fwd.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/descriptor_fwd.hpp rename to DiplomProject/Pods/Realm/include/core/realm/descriptor_fwd.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp b/DiplomProject/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp rename to DiplomProject/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/exceptions.hpp b/DiplomProject/Pods/Realm/include/core/realm/exceptions.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/exceptions.hpp rename to DiplomProject/Pods/Realm/include/core/realm/exceptions.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/group.hpp b/DiplomProject/Pods/Realm/include/core/realm/group.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/group.hpp rename to DiplomProject/Pods/Realm/include/core/realm/group.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/group_shared.hpp b/DiplomProject/Pods/Realm/include/core/realm/group_shared.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/group_shared.hpp rename to DiplomProject/Pods/Realm/include/core/realm/group_shared.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/group_shared_options.hpp b/DiplomProject/Pods/Realm/include/core/realm/group_shared_options.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/group_shared_options.hpp rename to DiplomProject/Pods/Realm/include/core/realm/group_shared_options.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/group_writer.hpp b/DiplomProject/Pods/Realm/include/core/realm/group_writer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/group_writer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/group_writer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/handover_defs.hpp b/DiplomProject/Pods/Realm/include/core/realm/handover_defs.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/handover_defs.hpp rename to DiplomProject/Pods/Realm/include/core/realm/handover_defs.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/history.hpp b/DiplomProject/Pods/Realm/include/core/realm/history.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/history.hpp rename to DiplomProject/Pods/Realm/include/core/realm/history.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/array_writer.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/array_writer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/array_writer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/array_writer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/clock.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/clock.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/clock.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/clock.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/destroy_guard.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/destroy_guard.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/destroy_guard.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/destroy_guard.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/input_stream.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/input_stream.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/input_stream.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/input_stream.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/output_stream.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/output_stream.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/output_stream.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/output_stream.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/sequential_getter.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/sequential_getter.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/sequential_getter.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/sequential_getter.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/simulated_failure.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/simulated_failure.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/simulated_failure.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/simulated_failure.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/impl/transact_log.hpp b/DiplomProject/Pods/Realm/include/core/realm/impl/transact_log.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/impl/transact_log.hpp rename to DiplomProject/Pods/Realm/include/core/realm/impl/transact_log.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/index_string.hpp b/DiplomProject/Pods/Realm/include/core/realm/index_string.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/index_string.hpp rename to DiplomProject/Pods/Realm/include/core/realm/index_string.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/lang_bind_helper.hpp b/DiplomProject/Pods/Realm/include/core/realm/lang_bind_helper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/lang_bind_helper.hpp rename to DiplomProject/Pods/Realm/include/core/realm/lang_bind_helper.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/link_view.hpp b/DiplomProject/Pods/Realm/include/core/realm/link_view.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/link_view.hpp rename to DiplomProject/Pods/Realm/include/core/realm/link_view.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/link_view_fwd.hpp b/DiplomProject/Pods/Realm/include/core/realm/link_view_fwd.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/link_view_fwd.hpp rename to DiplomProject/Pods/Realm/include/core/realm/link_view_fwd.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/metrics/metric_timer.hpp b/DiplomProject/Pods/Realm/include/core/realm/metrics/metric_timer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/metrics/metric_timer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/metrics/metric_timer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/metrics/metrics.hpp b/DiplomProject/Pods/Realm/include/core/realm/metrics/metrics.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/metrics/metrics.hpp rename to DiplomProject/Pods/Realm/include/core/realm/metrics/metrics.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/metrics/query_info.hpp b/DiplomProject/Pods/Realm/include/core/realm/metrics/query_info.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/metrics/query_info.hpp rename to DiplomProject/Pods/Realm/include/core/realm/metrics/query_info.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/metrics/transaction_info.hpp b/DiplomProject/Pods/Realm/include/core/realm/metrics/transaction_info.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/metrics/transaction_info.hpp rename to DiplomProject/Pods/Realm/include/core/realm/metrics/transaction_info.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/mixed.hpp b/DiplomProject/Pods/Realm/include/core/realm/mixed.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/mixed.hpp rename to DiplomProject/Pods/Realm/include/core/realm/mixed.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/null.hpp b/DiplomProject/Pods/Realm/include/core/realm/null.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/null.hpp rename to DiplomProject/Pods/Realm/include/core/realm/null.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/olddatetime.hpp b/DiplomProject/Pods/Realm/include/core/realm/olddatetime.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/olddatetime.hpp rename to DiplomProject/Pods/Realm/include/core/realm/olddatetime.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/owned_data.hpp b/DiplomProject/Pods/Realm/include/core/realm/owned_data.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/owned_data.hpp rename to DiplomProject/Pods/Realm/include/core/realm/owned_data.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/expression_container.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/expression_container.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/expression_container.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/expression_container.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/parser.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/parser.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/parser.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/parser.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/parser_utils.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/parser_utils.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/parser_utils.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/parser_utils.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/property_expression.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/property_expression.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/property_expression.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/property_expression.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/query_builder.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/query_builder.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/query_builder.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/query_builder.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/subquery_expression.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/subquery_expression.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/subquery_expression.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/subquery_expression.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/parser/value_expression.hpp b/DiplomProject/Pods/Realm/include/core/realm/parser/value_expression.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/parser/value_expression.hpp rename to DiplomProject/Pods/Realm/include/core/realm/parser/value_expression.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/query.hpp b/DiplomProject/Pods/Realm/include/core/realm/query.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/query.hpp rename to DiplomProject/Pods/Realm/include/core/realm/query.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/query_conditions.hpp b/DiplomProject/Pods/Realm/include/core/realm/query_conditions.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/query_conditions.hpp rename to DiplomProject/Pods/Realm/include/core/realm/query_conditions.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/query_engine.hpp b/DiplomProject/Pods/Realm/include/core/realm/query_engine.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/query_engine.hpp rename to DiplomProject/Pods/Realm/include/core/realm/query_engine.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/query_expression.hpp b/DiplomProject/Pods/Realm/include/core/realm/query_expression.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/query_expression.hpp rename to DiplomProject/Pods/Realm/include/core/realm/query_expression.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/query_operators.hpp b/DiplomProject/Pods/Realm/include/core/realm/query_operators.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/query_operators.hpp rename to DiplomProject/Pods/Realm/include/core/realm/query_operators.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/realm_nmmintrin.h b/DiplomProject/Pods/Realm/include/core/realm/realm_nmmintrin.h similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/realm_nmmintrin.h rename to DiplomProject/Pods/Realm/include/core/realm/realm_nmmintrin.h diff --git a/Lesson12/Pods/Realm/include/core/realm/replication.hpp b/DiplomProject/Pods/Realm/include/core/realm/replication.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/replication.hpp rename to DiplomProject/Pods/Realm/include/core/realm/replication.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/row.hpp b/DiplomProject/Pods/Realm/include/core/realm/row.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/row.hpp rename to DiplomProject/Pods/Realm/include/core/realm/row.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/spec.hpp b/DiplomProject/Pods/Realm/include/core/realm/spec.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/spec.hpp rename to DiplomProject/Pods/Realm/include/core/realm/spec.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/string_data.hpp b/DiplomProject/Pods/Realm/include/core/realm/string_data.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/string_data.hpp rename to DiplomProject/Pods/Realm/include/core/realm/string_data.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/changeset.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/changeset.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/changeset.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/changeset.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/changeset_parser.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/changeset_parser.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/changeset_parser.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/changeset_parser.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/client.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/client.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/client.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/client.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/crypto.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/crypto.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/crypto.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/crypto.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/crypto_server.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/crypto_server.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/crypto_server.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/crypto_server.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/feature_token.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/feature_token.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/feature_token.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/feature_token.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/fingerprint.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/fingerprint.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/fingerprint.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/fingerprint.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/history.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/history.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/history.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/history.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/instruction_applier.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/instruction_applier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/instruction_applier.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/instruction_applier.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/instruction_replication.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/instruction_replication.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/instruction_replication.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/instruction_replication.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/instructions.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/instructions.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/instructions.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/instructions.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/object.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/object.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/object.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/object.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/object_id.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/object_id.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/object_id.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/object_id.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/permissions.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/permissions.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/permissions.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/permissions.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/protocol.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/protocol.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/protocol.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/protocol.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/transform.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/transform.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/transform.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/transform.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/sync/version.hpp b/DiplomProject/Pods/Realm/include/core/realm/sync/version.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/sync/version.hpp rename to DiplomProject/Pods/Realm/include/core/realm/sync/version.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/table.hpp b/DiplomProject/Pods/Realm/include/core/realm/table.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/table.hpp rename to DiplomProject/Pods/Realm/include/core/realm/table.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/table_ref.hpp b/DiplomProject/Pods/Realm/include/core/realm/table_ref.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/table_ref.hpp rename to DiplomProject/Pods/Realm/include/core/realm/table_ref.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/table_view.hpp b/DiplomProject/Pods/Realm/include/core/realm/table_view.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/table_view.hpp rename to DiplomProject/Pods/Realm/include/core/realm/table_view.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/timestamp.hpp b/DiplomProject/Pods/Realm/include/core/realm/timestamp.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/timestamp.hpp rename to DiplomProject/Pods/Realm/include/core/realm/timestamp.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/unicode.hpp b/DiplomProject/Pods/Realm/include/core/realm/unicode.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/unicode.hpp rename to DiplomProject/Pods/Realm/include/core/realm/unicode.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/aes_cryptor.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/aes_cryptor.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/aes_cryptor.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/aes_cryptor.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/allocation_metrics.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/allocation_metrics.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/allocation_metrics.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/allocation_metrics.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/allocator.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/allocator.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/allocator.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/allocator.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/any.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/any.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/any.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/any.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/assert.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/assert.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/assert.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/assert.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/backtrace.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/backtrace.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/backtrace.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/backtrace.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/base64.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/base64.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/base64.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/base64.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/basic_system_errors.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/basic_system_errors.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/basic_system_errors.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/basic_system_errors.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/bind_ptr.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/bind_ptr.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/bind_ptr.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/bind_ptr.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/buffer.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/buffer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/buffer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/buffer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/buffer_stream.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/buffer_stream.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/buffer_stream.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/buffer_stream.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/call_with_tuple.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/call_with_tuple.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/call_with_tuple.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/call_with_tuple.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/cf_ptr.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/cf_ptr.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/cf_ptr.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/cf_ptr.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/cf_str.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/cf_str.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/cf_str.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/cf_str.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/circular_buffer.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/circular_buffer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/circular_buffer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/circular_buffer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/config.h b/DiplomProject/Pods/Realm/include/core/realm/util/config.h similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/config.h rename to DiplomProject/Pods/Realm/include/core/realm/util/config.h diff --git a/Lesson12/Pods/Realm/include/core/realm/util/demangle.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/demangle.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/demangle.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/demangle.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/duplicating_logger.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/duplicating_logger.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/duplicating_logger.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/duplicating_logger.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/enum.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/enum.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/enum.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/enum.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/errno.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/errno.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/errno.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/errno.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/features.h b/DiplomProject/Pods/Realm/include/core/realm/util/features.h similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/features.h rename to DiplomProject/Pods/Realm/include/core/realm/util/features.h diff --git a/Lesson12/Pods/Realm/include/core/realm/util/fifo_helper.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/fifo_helper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/fifo_helper.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/fifo_helper.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/file.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/file.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/file.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/file.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/file_mapper.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/file_mapper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/file_mapper.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/file_mapper.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/flat_map.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/flat_map.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/flat_map.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/flat_map.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/get_file_size.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/get_file_size.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/get_file_size.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/get_file_size.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/hex_dump.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/hex_dump.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/hex_dump.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/hex_dump.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/http.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/http.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/http.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/http.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/inspect.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/inspect.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/inspect.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/inspect.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/json_parser.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/json_parser.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/json_parser.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/json_parser.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/load_file.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/load_file.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/load_file.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/load_file.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/logger.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/logger.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/logger.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/logger.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/memory_stream.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/memory_stream.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/memory_stream.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/memory_stream.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/deque.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/deque.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/deque.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/deque.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/map.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/map.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/map.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/map.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/set.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/set.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/set.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/set.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/string.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/string.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/string.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/string.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/metered/vector.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/metered/vector.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/metered/vector.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/metered/vector.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/misc_errors.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/misc_errors.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/misc_errors.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/misc_errors.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/miscellaneous.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/miscellaneous.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/miscellaneous.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/miscellaneous.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/network.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/network.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/network.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/network.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/network_ssl.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/network_ssl.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/network_ssl.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/network_ssl.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/optional.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/optional.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/optional.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/optional.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/overload.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/overload.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/overload.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/overload.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/parent_dir.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/parent_dir.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/parent_dir.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/parent_dir.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/platform_info.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/platform_info.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/platform_info.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/platform_info.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/priority_queue.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/priority_queue.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/priority_queue.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/priority_queue.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/quote.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/quote.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/quote.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/quote.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/random.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/random.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/random.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/random.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/resource_limits.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/resource_limits.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/resource_limits.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/resource_limits.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/safe_int_ops.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/safe_int_ops.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/safe_int_ops.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/safe_int_ops.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/scope_exit.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/scope_exit.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/scope_exit.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/scope_exit.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/serializer.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/serializer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/serializer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/serializer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/shared_ptr.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/shared_ptr.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/shared_ptr.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/shared_ptr.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/signal_blocker.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/signal_blocker.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/signal_blocker.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/signal_blocker.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/string_buffer.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/string_buffer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/string_buffer.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/string_buffer.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/string_view.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/string_view.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/string_view.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/string_view.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/substitute.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/substitute.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/substitute.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/substitute.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/system_process.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/system_process.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/system_process.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/system_process.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/terminate.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/terminate.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/terminate.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/terminate.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/thread.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/thread.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/thread.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/thread.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/time.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/time.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/time.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/time.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/timestamp_logger.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/timestamp_logger.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/timestamp_logger.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/timestamp_logger.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/to_string.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/to_string.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/to_string.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/to_string.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/type_list.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/type_list.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/type_list.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/type_list.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/type_traits.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/type_traits.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/type_traits.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/type_traits.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/uri.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/uri.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/uri.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/uri.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/utf8.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/utf8.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/utf8.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/utf8.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/value_reset_guard.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/value_reset_guard.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/value_reset_guard.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/value_reset_guard.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/util/websocket.hpp b/DiplomProject/Pods/Realm/include/core/realm/util/websocket.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/util/websocket.hpp rename to DiplomProject/Pods/Realm/include/core/realm/util/websocket.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/utilities.hpp b/DiplomProject/Pods/Realm/include/core/realm/utilities.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/utilities.hpp rename to DiplomProject/Pods/Realm/include/core/realm/utilities.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/version.hpp b/DiplomProject/Pods/Realm/include/core/realm/version.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/version.hpp rename to DiplomProject/Pods/Realm/include/core/realm/version.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/version_id.hpp b/DiplomProject/Pods/Realm/include/core/realm/version_id.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/version_id.hpp rename to DiplomProject/Pods/Realm/include/core/realm/version_id.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/version_numbers.hpp b/DiplomProject/Pods/Realm/include/core/realm/version_numbers.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/version_numbers.hpp rename to DiplomProject/Pods/Realm/include/core/realm/version_numbers.hpp diff --git a/Lesson12/Pods/Realm/include/core/realm/views.hpp b/DiplomProject/Pods/Realm/include/core/realm/views.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/core/realm/views.hpp rename to DiplomProject/Pods/Realm/include/core/realm/views.hpp diff --git a/Lesson12/Pods/Realm/include/execution_context_id.hpp b/DiplomProject/Pods/Realm/include/execution_context_id.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/execution_context_id.hpp rename to DiplomProject/Pods/Realm/include/execution_context_id.hpp diff --git a/Lesson12/Pods/Realm/include/feature_checks.hpp b/DiplomProject/Pods/Realm/include/feature_checks.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/feature_checks.hpp rename to DiplomProject/Pods/Realm/include/feature_checks.hpp diff --git a/Lesson12/Pods/Realm/include/impl/apple/external_commit_helper.hpp b/DiplomProject/Pods/Realm/include/impl/apple/external_commit_helper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/apple/external_commit_helper.hpp rename to DiplomProject/Pods/Realm/include/impl/apple/external_commit_helper.hpp diff --git a/Lesson12/Pods/Realm/include/impl/apple/keychain_helper.hpp b/DiplomProject/Pods/Realm/include/impl/apple/keychain_helper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/apple/keychain_helper.hpp rename to DiplomProject/Pods/Realm/include/impl/apple/keychain_helper.hpp diff --git a/Lesson12/Pods/Realm/include/impl/collection_change_builder.hpp b/DiplomProject/Pods/Realm/include/impl/collection_change_builder.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/collection_change_builder.hpp rename to DiplomProject/Pods/Realm/include/impl/collection_change_builder.hpp diff --git a/Lesson12/Pods/Realm/include/impl/collection_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/collection_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/collection_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/collection_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/impl/external_commit_helper.hpp b/DiplomProject/Pods/Realm/include/impl/external_commit_helper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/external_commit_helper.hpp rename to DiplomProject/Pods/Realm/include/impl/external_commit_helper.hpp diff --git a/Lesson12/Pods/Realm/include/impl/list_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/list_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/list_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/list_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/impl/notification_wrapper.hpp b/DiplomProject/Pods/Realm/include/impl/notification_wrapper.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/notification_wrapper.hpp rename to DiplomProject/Pods/Realm/include/impl/notification_wrapper.hpp diff --git a/Lesson12/Pods/Realm/include/impl/object_accessor_impl.hpp b/DiplomProject/Pods/Realm/include/impl/object_accessor_impl.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/object_accessor_impl.hpp rename to DiplomProject/Pods/Realm/include/impl/object_accessor_impl.hpp diff --git a/Lesson12/Pods/Realm/include/impl/object_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/object_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/object_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/object_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/impl/primitive_list_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/primitive_list_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/primitive_list_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/primitive_list_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/impl/realm_coordinator.hpp b/DiplomProject/Pods/Realm/include/impl/realm_coordinator.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/realm_coordinator.hpp rename to DiplomProject/Pods/Realm/include/impl/realm_coordinator.hpp diff --git a/Lesson12/Pods/Realm/include/impl/results_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/results_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/results_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/results_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/impl/transact_log_handler.hpp b/DiplomProject/Pods/Realm/include/impl/transact_log_handler.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/transact_log_handler.hpp rename to DiplomProject/Pods/Realm/include/impl/transact_log_handler.hpp diff --git a/Lesson12/Pods/Realm/include/impl/weak_realm_notifier.hpp b/DiplomProject/Pods/Realm/include/impl/weak_realm_notifier.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/impl/weak_realm_notifier.hpp rename to DiplomProject/Pods/Realm/include/impl/weak_realm_notifier.hpp diff --git a/Lesson12/Pods/Realm/include/index_set.hpp b/DiplomProject/Pods/Realm/include/index_set.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/index_set.hpp rename to DiplomProject/Pods/Realm/include/index_set.hpp diff --git a/Lesson12/Pods/Realm/include/keypath_helpers.hpp b/DiplomProject/Pods/Realm/include/keypath_helpers.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/keypath_helpers.hpp rename to DiplomProject/Pods/Realm/include/keypath_helpers.hpp diff --git a/Lesson12/Pods/Realm/include/list.hpp b/DiplomProject/Pods/Realm/include/list.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/list.hpp rename to DiplomProject/Pods/Realm/include/list.hpp diff --git a/Lesson12/Pods/Realm/include/object.hpp b/DiplomProject/Pods/Realm/include/object.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/object.hpp rename to DiplomProject/Pods/Realm/include/object.hpp diff --git a/Lesson12/Pods/Realm/include/object_accessor.hpp b/DiplomProject/Pods/Realm/include/object_accessor.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/object_accessor.hpp rename to DiplomProject/Pods/Realm/include/object_accessor.hpp diff --git a/Lesson12/Pods/Realm/include/object_schema.hpp b/DiplomProject/Pods/Realm/include/object_schema.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/object_schema.hpp rename to DiplomProject/Pods/Realm/include/object_schema.hpp diff --git a/Lesson12/Pods/Realm/include/object_store.hpp b/DiplomProject/Pods/Realm/include/object_store.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/object_store.hpp rename to DiplomProject/Pods/Realm/include/object_store.hpp diff --git a/Lesson12/Pods/Realm/include/property.hpp b/DiplomProject/Pods/Realm/include/property.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/property.hpp rename to DiplomProject/Pods/Realm/include/property.hpp diff --git a/Lesson12/Pods/Realm/include/results.hpp b/DiplomProject/Pods/Realm/include/results.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/results.hpp rename to DiplomProject/Pods/Realm/include/results.hpp diff --git a/Lesson12/Pods/Realm/include/schema.hpp b/DiplomProject/Pods/Realm/include/schema.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/schema.hpp rename to DiplomProject/Pods/Realm/include/schema.hpp diff --git a/Lesson12/Pods/Realm/include/shared_realm.hpp b/DiplomProject/Pods/Realm/include/shared_realm.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/shared_realm.hpp rename to DiplomProject/Pods/Realm/include/shared_realm.hpp diff --git a/Lesson12/Pods/Realm/include/sync/async_open_task.hpp b/DiplomProject/Pods/Realm/include/sync/async_open_task.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/async_open_task.hpp rename to DiplomProject/Pods/Realm/include/sync/async_open_task.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/apple/network_reachability_observer.hpp b/DiplomProject/Pods/Realm/include/sync/impl/apple/network_reachability_observer.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/apple/network_reachability_observer.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/apple/network_reachability_observer.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/apple/system_configuration.hpp b/DiplomProject/Pods/Realm/include/sync/impl/apple/system_configuration.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/apple/system_configuration.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/apple/system_configuration.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/network_reachability.hpp b/DiplomProject/Pods/Realm/include/sync/impl/network_reachability.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/network_reachability.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/network_reachability.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/sync_client.hpp b/DiplomProject/Pods/Realm/include/sync/impl/sync_client.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/sync_client.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/sync_client.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/sync_file.hpp b/DiplomProject/Pods/Realm/include/sync/impl/sync_file.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/sync_file.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/sync_file.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/sync_metadata.hpp b/DiplomProject/Pods/Realm/include/sync/impl/sync_metadata.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/sync_metadata.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/sync_metadata.hpp diff --git a/Lesson12/Pods/Realm/include/sync/impl/work_queue.hpp b/DiplomProject/Pods/Realm/include/sync/impl/work_queue.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/impl/work_queue.hpp rename to DiplomProject/Pods/Realm/include/sync/impl/work_queue.hpp diff --git a/Lesson12/Pods/Realm/include/sync/partial_sync.hpp b/DiplomProject/Pods/Realm/include/sync/partial_sync.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/partial_sync.hpp rename to DiplomProject/Pods/Realm/include/sync/partial_sync.hpp diff --git a/Lesson12/Pods/Realm/include/sync/subscription_state.hpp b/DiplomProject/Pods/Realm/include/sync/subscription_state.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/subscription_state.hpp rename to DiplomProject/Pods/Realm/include/sync/subscription_state.hpp diff --git a/Lesson12/Pods/Realm/include/sync/sync_config.hpp b/DiplomProject/Pods/Realm/include/sync/sync_config.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/sync_config.hpp rename to DiplomProject/Pods/Realm/include/sync/sync_config.hpp diff --git a/Lesson12/Pods/Realm/include/sync/sync_manager.hpp b/DiplomProject/Pods/Realm/include/sync/sync_manager.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/sync_manager.hpp rename to DiplomProject/Pods/Realm/include/sync/sync_manager.hpp diff --git a/Lesson12/Pods/Realm/include/sync/sync_permission.hpp b/DiplomProject/Pods/Realm/include/sync/sync_permission.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/sync_permission.hpp rename to DiplomProject/Pods/Realm/include/sync/sync_permission.hpp diff --git a/Lesson12/Pods/Realm/include/sync/sync_session.hpp b/DiplomProject/Pods/Realm/include/sync/sync_session.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/sync_session.hpp rename to DiplomProject/Pods/Realm/include/sync/sync_session.hpp diff --git a/Lesson12/Pods/Realm/include/sync/sync_user.hpp b/DiplomProject/Pods/Realm/include/sync/sync_user.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/sync/sync_user.hpp rename to DiplomProject/Pods/Realm/include/sync/sync_user.hpp diff --git a/Lesson12/Pods/Realm/include/thread_safe_reference.hpp b/DiplomProject/Pods/Realm/include/thread_safe_reference.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/thread_safe_reference.hpp rename to DiplomProject/Pods/Realm/include/thread_safe_reference.hpp diff --git a/Lesson12/Pods/Realm/include/util/aligned_union.hpp b/DiplomProject/Pods/Realm/include/util/aligned_union.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/aligned_union.hpp rename to DiplomProject/Pods/Realm/include/util/aligned_union.hpp diff --git a/Lesson12/Pods/Realm/include/util/apple/event_loop_signal.hpp b/DiplomProject/Pods/Realm/include/util/apple/event_loop_signal.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/apple/event_loop_signal.hpp rename to DiplomProject/Pods/Realm/include/util/apple/event_loop_signal.hpp diff --git a/Lesson12/Pods/Realm/include/util/atomic_shared_ptr.hpp b/DiplomProject/Pods/Realm/include/util/atomic_shared_ptr.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/atomic_shared_ptr.hpp rename to DiplomProject/Pods/Realm/include/util/atomic_shared_ptr.hpp diff --git a/Lesson12/Pods/Realm/include/util/event_loop_dispatcher.hpp b/DiplomProject/Pods/Realm/include/util/event_loop_dispatcher.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/event_loop_dispatcher.hpp rename to DiplomProject/Pods/Realm/include/util/event_loop_dispatcher.hpp diff --git a/Lesson12/Pods/Realm/include/util/event_loop_signal.hpp b/DiplomProject/Pods/Realm/include/util/event_loop_signal.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/event_loop_signal.hpp rename to DiplomProject/Pods/Realm/include/util/event_loop_signal.hpp diff --git a/Lesson12/Pods/Realm/include/util/tagged_bool.hpp b/DiplomProject/Pods/Realm/include/util/tagged_bool.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/tagged_bool.hpp rename to DiplomProject/Pods/Realm/include/util/tagged_bool.hpp diff --git a/Lesson12/Pods/Realm/include/util/uuid.hpp b/DiplomProject/Pods/Realm/include/util/uuid.hpp similarity index 100% rename from Lesson12/Pods/Realm/include/util/uuid.hpp rename to DiplomProject/Pods/Realm/include/util/uuid.hpp diff --git a/Lesson12/Pods/RealmSwift/LICENSE b/DiplomProject/Pods/RealmSwift/LICENSE similarity index 100% rename from Lesson12/Pods/RealmSwift/LICENSE rename to DiplomProject/Pods/RealmSwift/LICENSE diff --git a/Lesson12/Pods/RealmSwift/README.md b/DiplomProject/Pods/RealmSwift/README.md similarity index 100% rename from Lesson12/Pods/RealmSwift/README.md rename to DiplomProject/Pods/RealmSwift/README.md diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Aliases.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Aliases.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Aliases.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Aliases.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Error.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Error.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Error.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Error.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/LinkingObjects.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/LinkingObjects.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/LinkingObjects.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/LinkingObjects.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/List.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/List.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/List.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/List.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Migration.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Migration.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Migration.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Migration.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Object.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Object.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Object.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Object.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/ObjectSchema.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/ObjectSchema.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/ObjectSchema.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/ObjectSchema.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/ObjectiveCSupport+Sync.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/ObjectiveCSupport+Sync.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/ObjectiveCSupport+Sync.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/ObjectiveCSupport+Sync.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/ObjectiveCSupport.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/ObjectiveCSupport.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/ObjectiveCSupport.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/ObjectiveCSupport.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Optional.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Optional.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Optional.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Optional.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Property.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Property.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Property.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Property.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Realm.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Realm.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Realm.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Realm.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/RealmCollection.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/RealmCollection.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/RealmCollection.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/RealmCollection.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/RealmConfiguration.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/RealmConfiguration.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/RealmConfiguration.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/RealmConfiguration.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Results.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Results.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Results.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Results.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Schema.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Schema.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Schema.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Schema.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/SortDescriptor.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/SortDescriptor.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/SortDescriptor.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/SortDescriptor.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/SwiftVersion.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/SwiftVersion.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/SwiftVersion.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/SwiftVersion.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Sync.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Sync.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Sync.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Sync.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/ThreadSafeReference.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/ThreadSafeReference.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/ThreadSafeReference.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/ThreadSafeReference.swift diff --git a/Lesson12/Pods/RealmSwift/RealmSwift/Util.swift b/DiplomProject/Pods/RealmSwift/RealmSwift/Util.swift similarity index 100% rename from Lesson12/Pods/RealmSwift/RealmSwift/Util.swift rename to DiplomProject/Pods/RealmSwift/RealmSwift/Util.swift diff --git a/Lesson12/Pods/RealmSwift/build.sh b/DiplomProject/Pods/RealmSwift/build.sh similarity index 100% rename from Lesson12/Pods/RealmSwift/build.sh rename to DiplomProject/Pods/RealmSwift/build.sh diff --git a/Lesson14/Pods/RxCocoa/LICENSE.md b/DiplomProject/Pods/RxCocoa/LICENSE.md similarity index 100% rename from Lesson14/Pods/RxCocoa/LICENSE.md rename to DiplomProject/Pods/RxCocoa/LICENSE.md diff --git a/Lesson14/Pods/RxCocoa/Platform/DataStructures/Bag.swift b/DiplomProject/Pods/RxCocoa/Platform/DataStructures/Bag.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/DataStructures/Bag.swift rename to DiplomProject/Pods/RxCocoa/Platform/DataStructures/Bag.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift b/DiplomProject/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift rename to DiplomProject/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift b/DiplomProject/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift rename to DiplomProject/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/DataStructures/Queue.swift b/DiplomProject/Pods/RxCocoa/Platform/DataStructures/Queue.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/DataStructures/Queue.swift rename to DiplomProject/Pods/RxCocoa/Platform/DataStructures/Queue.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift b/DiplomProject/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift rename to DiplomProject/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/Platform.Darwin.swift b/DiplomProject/Pods/RxCocoa/Platform/Platform.Darwin.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/Platform.Darwin.swift rename to DiplomProject/Pods/RxCocoa/Platform/Platform.Darwin.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/Platform.Linux.swift b/DiplomProject/Pods/RxCocoa/Platform/Platform.Linux.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/Platform.Linux.swift rename to DiplomProject/Pods/RxCocoa/Platform/Platform.Linux.swift diff --git a/Lesson14/Pods/RxCocoa/Platform/RecursiveLock.swift b/DiplomProject/Pods/RxCocoa/Platform/RecursiveLock.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/Platform/RecursiveLock.swift rename to DiplomProject/Pods/RxCocoa/Platform/RecursiveLock.swift diff --git a/Lesson14/Pods/RxCocoa/README.md b/DiplomProject/Pods/RxCocoa/README.md similarity index 100% rename from Lesson14/Pods/RxCocoa/README.md rename to DiplomProject/Pods/RxCocoa/README.md diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/Binder.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/Binder.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/Binder.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/Binder.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/KeyPathBinder.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/KeyPathBinder.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/KeyPathBinder.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/KeyPathBinder.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/NSLayoutConstraint+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/NSLayoutConstraint+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/NSLayoutConstraint+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/NSLayoutConstraint+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Common/TextInput.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Common/TextInput.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Common/TextInput.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Common/TextInput.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Deprecated.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Deprecated.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Deprecated.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Deprecated.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RX.m b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RX.m similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RX.m rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RX.m diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h b/DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/RxCocoa.h b/DiplomProject/Pods/RxCocoa/RxCocoa/RxCocoa.h similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/RxCocoa.h rename to DiplomProject/Pods/RxCocoa/RxCocoa/RxCocoa.h diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/RxCocoa.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/RxCocoa.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/RxCocoa.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/RxCocoa.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWebViewDelegateProxy.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWebViewDelegateProxy.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWebViewDelegateProxy.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWebViewDelegateProxy.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIAlertAction+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIAlertAction+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIAlertAction+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIAlertAction+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UILabel+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UILabel+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UILabel+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UILabel+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UINavigationItem+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UINavigationItem+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UINavigationItem+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UINavigationItem+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIPageControl+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIPageControl+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIPageControl+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIPageControl+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIProgressView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIProgressView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIProgressView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIProgressView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBarItem+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBarItem+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITabBarItem+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITabBarItem+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIViewController+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIViewController+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIViewController+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIViewController+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIWebView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIWebView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/iOS/UIWebView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/iOS/UIWebView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSImageView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSImageView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSImageView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSImageView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift diff --git a/Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift b/DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift similarity index 100% rename from Lesson14/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift rename to DiplomProject/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift diff --git a/Lesson14/Pods/RxRelay/LICENSE.md b/DiplomProject/Pods/RxRelay/LICENSE.md similarity index 100% rename from Lesson14/Pods/RxRelay/LICENSE.md rename to DiplomProject/Pods/RxRelay/LICENSE.md diff --git a/Lesson14/Pods/RxRelay/README.md b/DiplomProject/Pods/RxRelay/README.md similarity index 100% rename from Lesson14/Pods/RxRelay/README.md rename to DiplomProject/Pods/RxRelay/README.md diff --git a/Lesson14/Pods/RxRelay/RxRelay/BehaviorRelay.swift b/DiplomProject/Pods/RxRelay/RxRelay/BehaviorRelay.swift similarity index 100% rename from Lesson14/Pods/RxRelay/RxRelay/BehaviorRelay.swift rename to DiplomProject/Pods/RxRelay/RxRelay/BehaviorRelay.swift diff --git a/Lesson14/Pods/RxRelay/RxRelay/Observable+Bind.swift b/DiplomProject/Pods/RxRelay/RxRelay/Observable+Bind.swift similarity index 100% rename from Lesson14/Pods/RxRelay/RxRelay/Observable+Bind.swift rename to DiplomProject/Pods/RxRelay/RxRelay/Observable+Bind.swift diff --git a/Lesson14/Pods/RxRelay/RxRelay/PublishRelay.swift b/DiplomProject/Pods/RxRelay/RxRelay/PublishRelay.swift similarity index 100% rename from Lesson14/Pods/RxRelay/RxRelay/PublishRelay.swift rename to DiplomProject/Pods/RxRelay/RxRelay/PublishRelay.swift diff --git a/Lesson14/Pods/RxRelay/RxRelay/Utils.swift b/DiplomProject/Pods/RxRelay/RxRelay/Utils.swift similarity index 100% rename from Lesson14/Pods/RxRelay/RxRelay/Utils.swift rename to DiplomProject/Pods/RxRelay/RxRelay/Utils.swift diff --git a/Lesson14/Pods/RxSwift/LICENSE.md b/DiplomProject/Pods/RxSwift/LICENSE.md similarity index 100% rename from Lesson14/Pods/RxSwift/LICENSE.md rename to DiplomProject/Pods/RxSwift/LICENSE.md diff --git a/Lesson14/Pods/RxSwift/Platform/AtomicInt.swift b/DiplomProject/Pods/RxSwift/Platform/AtomicInt.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/AtomicInt.swift rename to DiplomProject/Pods/RxSwift/Platform/AtomicInt.swift diff --git a/Lesson14/Pods/RxSwift/Platform/DataStructures/Bag.swift b/DiplomProject/Pods/RxSwift/Platform/DataStructures/Bag.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/DataStructures/Bag.swift rename to DiplomProject/Pods/RxSwift/Platform/DataStructures/Bag.swift diff --git a/Lesson14/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/DiplomProject/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift rename to DiplomProject/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift diff --git a/Lesson14/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/DiplomProject/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift rename to DiplomProject/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift diff --git a/Lesson14/Pods/RxSwift/Platform/DataStructures/Queue.swift b/DiplomProject/Pods/RxSwift/Platform/DataStructures/Queue.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/DataStructures/Queue.swift rename to DiplomProject/Pods/RxSwift/Platform/DataStructures/Queue.swift diff --git a/Lesson14/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/DiplomProject/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift rename to DiplomProject/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift diff --git a/Lesson14/Pods/RxSwift/Platform/Platform.Darwin.swift b/DiplomProject/Pods/RxSwift/Platform/Platform.Darwin.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/Platform.Darwin.swift rename to DiplomProject/Pods/RxSwift/Platform/Platform.Darwin.swift diff --git a/Lesson14/Pods/RxSwift/Platform/Platform.Linux.swift b/DiplomProject/Pods/RxSwift/Platform/Platform.Linux.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/Platform.Linux.swift rename to DiplomProject/Pods/RxSwift/Platform/Platform.Linux.swift diff --git a/Lesson14/Pods/RxSwift/Platform/RecursiveLock.swift b/DiplomProject/Pods/RxSwift/Platform/RecursiveLock.swift similarity index 100% rename from Lesson14/Pods/RxSwift/Platform/RecursiveLock.swift rename to DiplomProject/Pods/RxSwift/Platform/RecursiveLock.swift diff --git a/Lesson14/Pods/RxSwift/README.md b/DiplomProject/Pods/RxSwift/README.md similarity index 100% rename from Lesson14/Pods/RxSwift/README.md rename to DiplomProject/Pods/RxSwift/README.md diff --git a/Lesson14/Pods/RxSwift/RxSwift/AnyObserver.swift b/DiplomProject/Pods/RxSwift/RxSwift/AnyObserver.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/AnyObserver.swift rename to DiplomProject/Pods/RxSwift/RxSwift/AnyObserver.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Cancelable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Cancelable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Cancelable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Cancelable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/Lock.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/Lock.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/Lock.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/DiplomProject/Pods/RxSwift/RxSwift/ConnectableObservableType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ConnectableObservableType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ConnectableObservableType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Date+Dispatch.swift b/DiplomProject/Pods/RxSwift/RxSwift/Date+Dispatch.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Date+Dispatch.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Date+Dispatch.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Deprecated.swift b/DiplomProject/Pods/RxSwift/RxSwift/Deprecated.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Deprecated.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Deprecated.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/Disposables.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/Disposables.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/Disposables.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Errors.swift b/DiplomProject/Pods/RxSwift/RxSwift/Errors.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Errors.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Errors.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Event.swift b/DiplomProject/Pods/RxSwift/RxSwift/Event.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Event.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Event.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/DiplomProject/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift b/DiplomProject/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/GroupedObservable.swift b/DiplomProject/Pods/RxSwift/RxSwift/GroupedObservable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/GroupedObservable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/GroupedObservable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/DiplomProject/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/DiplomProject/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/DiplomProject/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ObservableType.swift b/DiplomProject/Pods/RxSwift/RxSwift/ObservableType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ObservableType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ObservableType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/AddRef.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/AddRef.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/AddRef.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Amb.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Amb.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Amb.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Amb.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/AsSingle.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/AsSingle.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/AsSingle.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Buffer.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Buffer.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Buffer.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Catch.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Catch.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Catch.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Catch.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/CompactMap.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/CompactMap.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/CompactMap.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/CompactMap.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Concat.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Concat.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Concat.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Concat.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Create.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Create.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Create.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Create.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Debounce.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Debounce.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Debounce.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Debug.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Debug.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Debug.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Debug.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Deferred.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Deferred.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Deferred.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Delay.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Delay.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Delay.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Delay.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Do.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Do.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Do.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Do.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/ElementAt.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/ElementAt.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/ElementAt.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Empty.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Empty.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Empty.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Empty.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Enumerated.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Enumerated.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Enumerated.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Error.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Error.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Error.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Error.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Filter.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Filter.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Filter.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Filter.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/First.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/First.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/First.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/First.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Generate.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Generate.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Generate.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Generate.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/GroupBy.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/GroupBy.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/GroupBy.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Just.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Just.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Just.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Just.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Map.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Map.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Map.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Map.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Materialize.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Materialize.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Materialize.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Merge.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Merge.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Merge.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Merge.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Multicast.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Multicast.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Multicast.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Never.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Never.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Never.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Never.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Optional.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Optional.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Optional.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Optional.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Producer.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Producer.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Producer.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Producer.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Range.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Range.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Range.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Range.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Reduce.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Reduce.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Reduce.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Repeat.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Repeat.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Repeat.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Sample.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Sample.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Sample.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Sample.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Scan.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Scan.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Scan.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Scan.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Sequence.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Sequence.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Sequence.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Sink.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Sink.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Sink.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Sink.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Skip.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Skip.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Skip.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Skip.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/StartWith.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/StartWith.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/StartWith.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Switch.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Switch.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Switch.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Switch.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Take.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Take.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Take.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Take.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeLast.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/TakeLast.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeLast.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Throttle.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Throttle.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Throttle.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Timeout.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Timeout.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Timeout.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Timer.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Timer.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Timer.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Timer.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/ToArray.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/ToArray.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/ToArray.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Using.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Using.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Using.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Using.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Window.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Window.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Window.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Window.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observables/Zip.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observables/Zip.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observables/Zip.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/ObserverType.swift b/DiplomProject/Pods/RxSwift/RxSwift/ObserverType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/ObserverType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/ObserverType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/DiplomProject/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Reactive.swift b/DiplomProject/Pods/RxSwift/RxSwift/Reactive.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Reactive.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Reactive.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Rx.swift b/DiplomProject/Pods/RxSwift/RxSwift/Rx.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Rx.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Rx.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/RxMutableBox.swift b/DiplomProject/Pods/RxSwift/RxSwift/RxMutableBox.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/RxMutableBox.swift rename to DiplomProject/Pods/RxSwift/RxSwift/RxMutableBox.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/SchedulerType.swift b/DiplomProject/Pods/RxSwift/RxSwift/SchedulerType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/SchedulerType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/SchedulerType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/DiplomProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift b/DiplomProject/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift b/DiplomProject/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift b/DiplomProject/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift b/DiplomProject/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift b/DiplomProject/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift b/DiplomProject/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift rename to DiplomProject/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/Completable.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/Completable.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/Completable.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/Completable.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/Maybe.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/Maybe.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift diff --git a/Lesson14/Pods/RxSwift/RxSwift/Traits/Single.swift b/DiplomProject/Pods/RxSwift/RxSwift/Traits/Single.swift similarity index 100% rename from Lesson14/Pods/RxSwift/RxSwift/Traits/Single.swift rename to DiplomProject/Pods/RxSwift/RxSwift/Traits/Single.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/LICENSE b/DiplomProject/Pods/SnapKit/LICENSE similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/LICENSE rename to DiplomProject/Pods/SnapKit/LICENSE diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/README.md b/DiplomProject/Pods/SnapKit/README.md similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/README.md rename to DiplomProject/Pods/SnapKit/README.md diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/Constraint.swift b/DiplomProject/Pods/SnapKit/Source/Constraint.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/Constraint.swift rename to DiplomProject/Pods/SnapKit/Source/Constraint.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintAttributes.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintAttributes.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintAttributes.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintAttributes.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintConfig.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintConfig.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintConfig.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintConfig.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintConstantTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintConstantTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintConstantTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintConstantTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDSL.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintDSL.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDSL.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintDSL.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDescription.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintDescription.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDescription.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintDescription.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintInsetTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintInsetTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintInsetTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintInsetTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintInsets.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintInsets.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintInsets.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintInsets.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintItem.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintItem.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintItem.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintItem.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuide.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuide.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuide.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuide.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutSupport.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintLayoutSupport.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutSupport.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintLayoutSupport.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMaker.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMaker.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMaker.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMaker.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerEditable.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMakerEditable.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerEditable.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMakerEditable.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerExtendable.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMakerExtendable.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerExtendable.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMakerExtendable.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerRelatable.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMakerRelatable.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMakerRelatable.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMakerRelatable.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintOffsetTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintOffsetTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintOffsetTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintOffsetTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintPriority.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintPriority.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintPriority.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintPriority.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintPriorityTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintPriorityTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintPriorityTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintPriorityTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintRelatableTarget.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintRelatableTarget.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintRelatableTarget.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintRelatableTarget.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintRelation.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintRelation.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintRelation.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintRelation.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintView+Extensions.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintView+Extensions.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintView+Extensions.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintView+Extensions.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintView.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintView.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintView.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintView.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintViewDSL.swift b/DiplomProject/Pods/SnapKit/Source/ConstraintViewDSL.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/ConstraintViewDSL.swift rename to DiplomProject/Pods/SnapKit/Source/ConstraintViewDSL.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/Debugging.swift b/DiplomProject/Pods/SnapKit/Source/Debugging.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/Debugging.swift rename to DiplomProject/Pods/SnapKit/Source/Debugging.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/LayoutConstraint.swift b/DiplomProject/Pods/SnapKit/Source/LayoutConstraint.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/LayoutConstraint.swift rename to DiplomProject/Pods/SnapKit/Source/LayoutConstraint.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/LayoutConstraintItem.swift b/DiplomProject/Pods/SnapKit/Source/LayoutConstraintItem.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/LayoutConstraintItem.swift rename to DiplomProject/Pods/SnapKit/Source/LayoutConstraintItem.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/Typealiases.swift b/DiplomProject/Pods/SnapKit/Source/Typealiases.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/Typealiases.swift rename to DiplomProject/Pods/SnapKit/Source/Typealiases.swift diff --git a/Lesson10/Lesson10Task1/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift b/DiplomProject/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift similarity index 100% rename from Lesson10/Lesson10Task1/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift rename to DiplomProject/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-Info.plist b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-Info.plist similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-Info.plist rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-Info.plist diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-dummy.m b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-dummy.m similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-dummy.m rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-dummy.m diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-prefix.pch b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-prefix.pch similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-prefix.pch rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-prefix.pch diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-umbrella.h b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-umbrella.h similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage-umbrella.h rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage-umbrella.h diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage.modulemap b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage.modulemap similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage.modulemap rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage.modulemap diff --git a/Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage.xcconfig b/DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage.xcconfig similarity index 100% rename from Lesson12/Pods/Target Support Files/DTModelStorage/DTModelStorage.xcconfig rename to DiplomProject/Pods/Target Support Files/DTModelStorage/DTModelStorage.xcconfig diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-dummy.m b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-dummy.m similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-dummy.m rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-dummy.m diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.modulemap b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.modulemap similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.modulemap rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.modulemap diff --git a/Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.xcconfig b/DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.xcconfig similarity index 100% rename from Lesson12/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.xcconfig rename to DiplomProject/Pods/Target Support Files/DTTableViewManager/DTTableViewManager.xcconfig diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-Info.plist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-Info.plist similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-Info.plist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-Info.plist diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-acknowledgements.markdown b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-acknowledgements.markdown similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-acknowledgements.markdown rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-acknowledgements.markdown diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-acknowledgements.plist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-acknowledgements.plist similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-acknowledgements.plist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-acknowledgements.plist diff --git a/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-dummy.m b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-dummy.m new file mode 100644 index 0000000..717ade2 --- /dev/null +++ b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_DiplomProject : NSObject +@end +@implementation PodsDummy_Pods_DiplomProject +@end diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Debug-input-files.xcfilelist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Debug-input-files.xcfilelist similarity index 83% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Debug-input-files.xcfilelist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Debug-input-files.xcfilelist index 394b78b..ca651b2 100644 --- a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Debug-input-files.xcfilelist +++ b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Debug-input-files.xcfilelist @@ -1,4 +1,4 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks.sh +${PODS_ROOT}/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks.sh ${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework ${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework ${BUILT_PRODUCTS_DIR}/Realm/Realm.framework diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Debug-output-files.xcfilelist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Debug-output-files.xcfilelist similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Debug-output-files.xcfilelist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Debug-output-files.xcfilelist diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Release-input-files.xcfilelist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Release-input-files.xcfilelist similarity index 83% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Release-input-files.xcfilelist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Release-input-files.xcfilelist index 394b78b..ca651b2 100644 --- a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Release-input-files.xcfilelist +++ b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Release-input-files.xcfilelist @@ -1,4 +1,4 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks.sh +${PODS_ROOT}/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks.sh ${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework ${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework ${BUILT_PRODUCTS_DIR}/Realm/Realm.framework diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Release-output-files.xcfilelist b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Release-output-files.xcfilelist similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-Release-output-files.xcfilelist rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks-Release-output-files.xcfilelist diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks.sh b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks.sh similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks.sh rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-frameworks.sh diff --git a/Lesson14/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-umbrella.h similarity index 62% rename from Lesson14/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-umbrella.h index 8e1ead1..8ecd310 100644 --- a/Lesson14/Pods/Target Support Files/DTTableViewManager/DTTableViewManager-umbrella.h +++ b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject-umbrella.h @@ -11,6 +11,6 @@ #endif -FOUNDATION_EXPORT double DTTableViewManagerVersionNumber; -FOUNDATION_EXPORT const unsigned char DTTableViewManagerVersionString[]; +FOUNDATION_EXPORT double Pods_DiplomProjectVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_DiplomProjectVersionString[]; diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14.debug.xcconfig b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.debug.xcconfig similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14.debug.xcconfig rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.debug.xcconfig diff --git a/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.modulemap b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.modulemap new file mode 100644 index 0000000..65936f9 --- /dev/null +++ b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.modulemap @@ -0,0 +1,6 @@ +framework module Pods_DiplomProject { + umbrella header "Pods-DiplomProject-umbrella.h" + + export * + module * { export * } +} diff --git a/Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14.release.xcconfig b/DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.release.xcconfig similarity index 100% rename from Lesson14/Pods/Target Support Files/Pods-Lesson14/Pods-Lesson14.release.xcconfig rename to DiplomProject/Pods/Target Support Files/Pods-DiplomProject/Pods-DiplomProject.release.xcconfig diff --git a/Lesson12/Pods/Target Support Files/Realm/Realm-Info.plist b/DiplomProject/Pods/Target Support Files/Realm/Realm-Info.plist similarity index 100% rename from Lesson12/Pods/Target Support Files/Realm/Realm-Info.plist rename to DiplomProject/Pods/Target Support Files/Realm/Realm-Info.plist diff --git a/Lesson12/Pods/Target Support Files/Realm/Realm-dummy.m b/DiplomProject/Pods/Target Support Files/Realm/Realm-dummy.m similarity index 100% rename from Lesson12/Pods/Target Support Files/Realm/Realm-dummy.m rename to DiplomProject/Pods/Target Support Files/Realm/Realm-dummy.m diff --git a/Lesson12/Pods/Target Support Files/Realm/Realm-prefix.pch b/DiplomProject/Pods/Target Support Files/Realm/Realm-prefix.pch similarity index 100% rename from Lesson12/Pods/Target Support Files/Realm/Realm-prefix.pch rename to DiplomProject/Pods/Target Support Files/Realm/Realm-prefix.pch diff --git a/Lesson12/Pods/Target Support Files/Realm/Realm.modulemap b/DiplomProject/Pods/Target Support Files/Realm/Realm.modulemap similarity index 100% rename from Lesson12/Pods/Target Support Files/Realm/Realm.modulemap rename to DiplomProject/Pods/Target Support Files/Realm/Realm.modulemap diff --git a/Lesson12/Pods/Target Support Files/Realm/Realm.xcconfig b/DiplomProject/Pods/Target Support Files/Realm/Realm.xcconfig similarity index 100% rename from Lesson12/Pods/Target Support Files/Realm/Realm.xcconfig rename to DiplomProject/Pods/Target Support Files/Realm/Realm.xcconfig diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-Info.plist b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-Info.plist similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-Info.plist rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-Info.plist diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-dummy.m b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-dummy.m similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-dummy.m rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-dummy.m diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-prefix.pch b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-prefix.pch similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-prefix.pch rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-prefix.pch diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-umbrella.h b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-umbrella.h similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift-umbrella.h rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift-umbrella.h diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift.modulemap b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift.modulemap similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift.modulemap rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift.modulemap diff --git a/Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift.xcconfig b/DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift.xcconfig similarity index 100% rename from Lesson12/Pods/Target Support Files/RealmSwift/RealmSwift.xcconfig rename to DiplomProject/Pods/Target Support Files/RealmSwift/RealmSwift.xcconfig diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-Info.plist diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-dummy.m diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-prefix.pch diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa-umbrella.h diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa.modulemap diff --git a/Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa.xcconfig b/DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa.xcconfig similarity index 100% rename from Lesson14/Pods/Target Support Files/RxCocoa/RxCocoa.xcconfig rename to DiplomProject/Pods/Target Support Files/RxCocoa/RxCocoa.xcconfig diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay-Info.plist b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-Info.plist similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay-Info.plist rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-Info.plist diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay-dummy.m b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-dummy.m similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay-dummy.m rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-dummy.m diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-prefix.pch diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay-umbrella.h diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay.modulemap b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay.modulemap similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay.modulemap rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay.modulemap diff --git a/Lesson14/Pods/Target Support Files/RxRelay/RxRelay.xcconfig b/DiplomProject/Pods/Target Support Files/RxRelay/RxRelay.xcconfig similarity index 100% rename from Lesson14/Pods/Target Support Files/RxRelay/RxRelay.xcconfig rename to DiplomProject/Pods/Target Support Files/RxRelay/RxRelay.xcconfig diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift-Info.plist b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-Info.plist similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift-Info.plist rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-Info.plist diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift-dummy.m b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-dummy.m similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift-dummy.m rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-dummy.m diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift.modulemap b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift.modulemap similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift.modulemap rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift.modulemap diff --git a/Lesson14/Pods/Target Support Files/RxSwift/RxSwift.xcconfig b/DiplomProject/Pods/Target Support Files/RxSwift/RxSwift.xcconfig similarity index 100% rename from Lesson14/Pods/Target Support Files/RxSwift/RxSwift.xcconfig rename to DiplomProject/Pods/Target Support Files/RxSwift/RxSwift.xcconfig diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-Info.plist b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-Info.plist similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-Info.plist rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-Info.plist diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-dummy.m b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-dummy.m similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-dummy.m rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-dummy.m diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit.modulemap b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit.modulemap similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit.modulemap rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit.modulemap diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit.xcconfig b/DiplomProject/Pods/Target Support Files/SnapKit/SnapKit.xcconfig similarity index 100% rename from Lesson10/Lesson10Task1/Pods/Target Support Files/SnapKit/SnapKit.xcconfig rename to DiplomProject/Pods/Target Support Files/SnapKit/SnapKit.xcconfig diff --git a/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.pbxproj b/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.pbxproj deleted file mode 100644 index 936686f..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.pbxproj +++ /dev/null @@ -1,457 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 331D9D1523E191AF0006BB10 /* UIView+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331D9D1423E191AF0006BB10 /* UIView+Extension.swift */; }; - 333CA50923DADEB900A34EAC /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA50823DADEB900A34EAC /* AppDelegate.swift */; }; - 333CA50B23DADEB900A34EAC /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA50A23DADEB900A34EAC /* SceneDelegate.swift */; }; - 333CA50D23DADEB900A34EAC /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA50C23DADEB900A34EAC /* ViewController.swift */; }; - 333CA51023DADEB900A34EAC /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 333CA50E23DADEB900A34EAC /* Main.storyboard */; }; - 333CA51223DADEC000A34EAC /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 333CA51123DADEC000A34EAC /* Assets.xcassets */; }; - 333CA51523DADEC000A34EAC /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 333CA51323DADEC000A34EAC /* LaunchScreen.storyboard */; }; - 333CA51E23DAE04B00A34EAC /* ShopCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA51D23DAE04B00A34EAC /* ShopCollectionViewCell.swift */; }; - 333CA52023DAE53B00A34EAC /* CollectionViewViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA51F23DAE53B00A34EAC /* CollectionViewViewController.swift */; }; - 333CA52323DAE74500A34EAC /* ProductShopModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA52223DAE74500A34EAC /* ProductShopModel.swift */; }; - 333CA52523DB138800A34EAC /* TableViewViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA52423DB138800A34EAC /* TableViewViewController.swift */; }; - 333CA52723DB13CB00A34EAC /* MenuTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA52623DB13CB00A34EAC /* MenuTableViewCell.swift */; }; - 333CA52923DB17E900A34EAC /* MenuItemModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 333CA52823DB17E900A34EAC /* MenuItemModel.swift */; }; - 61FF38F1C43820C2F36A354C /* Pods_Lesson10Task1.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBE8985367A41AC3CAF88BD4 /* Pods_Lesson10Task1.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 327130BED23121DDD75688DF /* Pods-Lesson10Task1.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson10Task1.debug.xcconfig"; path = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.debug.xcconfig"; sourceTree = ""; }; - 331D9D1423E191AF0006BB10 /* UIView+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIView+Extension.swift"; sourceTree = ""; }; - 333CA50523DADEB900A34EAC /* Lesson10Task1.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lesson10Task1.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 333CA50823DADEB900A34EAC /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 333CA50A23DADEB900A34EAC /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 333CA50C23DADEB900A34EAC /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; - 333CA50F23DADEB900A34EAC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 333CA51123DADEC000A34EAC /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 333CA51423DADEC000A34EAC /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 333CA51623DADEC000A34EAC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 333CA51D23DAE04B00A34EAC /* ShopCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShopCollectionViewCell.swift; sourceTree = ""; }; - 333CA51F23DAE53B00A34EAC /* CollectionViewViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionViewViewController.swift; sourceTree = ""; }; - 333CA52223DAE74500A34EAC /* ProductShopModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProductShopModel.swift; sourceTree = ""; }; - 333CA52423DB138800A34EAC /* TableViewViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableViewViewController.swift; sourceTree = ""; }; - 333CA52623DB13CB00A34EAC /* MenuTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuTableViewCell.swift; sourceTree = ""; }; - 333CA52823DB17E900A34EAC /* MenuItemModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuItemModel.swift; sourceTree = ""; }; - 6C91D9C6A09377221DE1EA47 /* Pods-Lesson10Task1.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson10Task1.release.xcconfig"; path = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.release.xcconfig"; sourceTree = ""; }; - BBE8985367A41AC3CAF88BD4 /* Pods_Lesson10Task1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Lesson10Task1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 333CA50223DADEB900A34EAC /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 61FF38F1C43820C2F36A354C /* Pods_Lesson10Task1.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 333CA4FC23DADEB900A34EAC = { - isa = PBXGroup; - children = ( - 333CA50723DADEB900A34EAC /* Lesson10Task1 */, - 333CA50623DADEB900A34EAC /* Products */, - 63926E283F263904A9E56F67 /* Pods */, - 96E128718E4E0A0AB8743FB0 /* Frameworks */, - ); - sourceTree = ""; - }; - 333CA50623DADEB900A34EAC /* Products */ = { - isa = PBXGroup; - children = ( - 333CA50523DADEB900A34EAC /* Lesson10Task1.app */, - ); - name = Products; - sourceTree = ""; - }; - 333CA50723DADEB900A34EAC /* Lesson10Task1 */ = { - isa = PBXGroup; - children = ( - 333CA52123DAE72F00A34EAC /* Model */, - 333CA51C23DAE02000A34EAC /* Support */, - 333CA50823DADEB900A34EAC /* AppDelegate.swift */, - 333CA50A23DADEB900A34EAC /* SceneDelegate.swift */, - 333CA50C23DADEB900A34EAC /* ViewController.swift */, - 333CA50E23DADEB900A34EAC /* Main.storyboard */, - 333CA51123DADEC000A34EAC /* Assets.xcassets */, - 333CA51323DADEC000A34EAC /* LaunchScreen.storyboard */, - 333CA51623DADEC000A34EAC /* Info.plist */, - 333CA51F23DAE53B00A34EAC /* CollectionViewViewController.swift */, - 333CA52423DB138800A34EAC /* TableViewViewController.swift */, - 331D9D1423E191AF0006BB10 /* UIView+Extension.swift */, - ); - path = Lesson10Task1; - sourceTree = ""; - }; - 333CA51C23DAE02000A34EAC /* Support */ = { - isa = PBXGroup; - children = ( - 333CA51D23DAE04B00A34EAC /* ShopCollectionViewCell.swift */, - 333CA52623DB13CB00A34EAC /* MenuTableViewCell.swift */, - ); - path = Support; - sourceTree = ""; - }; - 333CA52123DAE72F00A34EAC /* Model */ = { - isa = PBXGroup; - children = ( - 333CA52223DAE74500A34EAC /* ProductShopModel.swift */, - 333CA52823DB17E900A34EAC /* MenuItemModel.swift */, - ); - path = Model; - sourceTree = ""; - }; - 63926E283F263904A9E56F67 /* Pods */ = { - isa = PBXGroup; - children = ( - 327130BED23121DDD75688DF /* Pods-Lesson10Task1.debug.xcconfig */, - 6C91D9C6A09377221DE1EA47 /* Pods-Lesson10Task1.release.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; - 96E128718E4E0A0AB8743FB0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - BBE8985367A41AC3CAF88BD4 /* Pods_Lesson10Task1.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 333CA50423DADEB900A34EAC /* Lesson10Task1 */ = { - isa = PBXNativeTarget; - buildConfigurationList = 333CA51923DADEC000A34EAC /* Build configuration list for PBXNativeTarget "Lesson10Task1" */; - buildPhases = ( - 5710AE42426BEF25134AFE78 /* [CP] Check Pods Manifest.lock */, - 333CA50123DADEB900A34EAC /* Sources */, - 333CA50223DADEB900A34EAC /* Frameworks */, - 333CA50323DADEB900A34EAC /* Resources */, - B7E9C12E20B4BD23DFC01F0E /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Lesson10Task1; - productName = Lesson10Task1; - productReference = 333CA50523DADEB900A34EAC /* Lesson10Task1.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 333CA4FD23DADEB900A34EAC /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1110; - LastUpgradeCheck = 1110; - ORGANIZATIONNAME = "Михаил Беленко"; - TargetAttributes = { - 333CA50423DADEB900A34EAC = { - CreatedOnToolsVersion = 11.1; - }; - }; - }; - buildConfigurationList = 333CA50023DADEB900A34EAC /* Build configuration list for PBXProject "Lesson10Task1" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 333CA4FC23DADEB900A34EAC; - productRefGroup = 333CA50623DADEB900A34EAC /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 333CA50423DADEB900A34EAC /* Lesson10Task1 */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 333CA50323DADEB900A34EAC /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 333CA51523DADEC000A34EAC /* LaunchScreen.storyboard in Resources */, - 333CA51223DADEC000A34EAC /* Assets.xcassets in Resources */, - 333CA51023DADEB900A34EAC /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 5710AE42426BEF25134AFE78 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Lesson10Task1-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - B7E9C12E20B4BD23DFC01F0E /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 333CA50123DADEB900A34EAC /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 333CA51E23DAE04B00A34EAC /* ShopCollectionViewCell.swift in Sources */, - 333CA52323DAE74500A34EAC /* ProductShopModel.swift in Sources */, - 333CA52923DB17E900A34EAC /* MenuItemModel.swift in Sources */, - 333CA52723DB13CB00A34EAC /* MenuTableViewCell.swift in Sources */, - 333CA50D23DADEB900A34EAC /* ViewController.swift in Sources */, - 333CA52023DAE53B00A34EAC /* CollectionViewViewController.swift in Sources */, - 333CA50923DADEB900A34EAC /* AppDelegate.swift in Sources */, - 333CA50B23DADEB900A34EAC /* SceneDelegate.swift in Sources */, - 331D9D1523E191AF0006BB10 /* UIView+Extension.swift in Sources */, - 333CA52523DB138800A34EAC /* TableViewViewController.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 333CA50E23DADEB900A34EAC /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 333CA50F23DADEB900A34EAC /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 333CA51323DADEC000A34EAC /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 333CA51423DADEC000A34EAC /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 333CA51723DADEC000A34EAC /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 333CA51823DADEC000A34EAC /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 333CA51A23DADEC000A34EAC /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 327130BED23121DDD75688DF /* Pods-Lesson10Task1.debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson10Task1/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson10Task1; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Debug; - }; - 333CA51B23DADEC000A34EAC /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 6C91D9C6A09377221DE1EA47 /* Pods-Lesson10Task1.release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson10Task1/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson10Task1; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 333CA50023DADEB900A34EAC /* Build configuration list for PBXProject "Lesson10Task1" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 333CA51723DADEC000A34EAC /* Debug */, - 333CA51823DADEC000A34EAC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 333CA51923DADEC000A34EAC /* Build configuration list for PBXNativeTarget "Lesson10Task1" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 333CA51A23DADEC000A34EAC /* Debug */, - 333CA51B23DADEC000A34EAC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 333CA4FD23DADEB900A34EAC /* Project object */; -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index bc0c575..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson10/Lesson10Task1/Lesson10Task1.xcworkspace/contents.xcworkspacedata b/Lesson10/Lesson10Task1/Lesson10Task1.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 3da5e0b..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/AppDelegate.swift b/Lesson10/Lesson10Task1/Lesson10Task1/AppDelegate.swift deleted file mode 100644 index 607534b..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/AppDelegate.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// AppDelegate.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { - - - - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - return true - } - - // MARK: UISceneSession Lifecycle - - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) - } - - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. - } - - -} - diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/Contents.json deleted file mode 100644 index 102971f..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon1.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/icon1.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/icon1.png deleted file mode 100644 index 773db87..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon1.imageset/icon1.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/Contents.json deleted file mode 100644 index 5e0ed30..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon10.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/icon10.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/icon10.png deleted file mode 100644 index 13b4088..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon10.imageset/icon10.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/Contents.json deleted file mode 100644 index 0003e35..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon11.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/icon11.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/icon11.png deleted file mode 100644 index 329c379..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon11.imageset/icon11.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/Contents.json deleted file mode 100644 index d6e8573..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon12.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/icon12.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/icon12.png deleted file mode 100644 index 3e34afd..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon12.imageset/icon12.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/Contents.json deleted file mode 100644 index 130bb70..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon13.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/icon13.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/icon13.png deleted file mode 100644 index 68a2cb1..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon13.imageset/icon13.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/Contents.json deleted file mode 100644 index 2a4dc12..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon14.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/icon14.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/icon14.png deleted file mode 100644 index 3ee04a8..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon14.imageset/icon14.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/Contents.json deleted file mode 100644 index 00eaedc..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon15.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/icon15.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/icon15.png deleted file mode 100644 index 5c055e6..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon15.imageset/icon15.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/Contents.json deleted file mode 100644 index 6929c77..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon16.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/icon16.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/icon16.png deleted file mode 100644 index 4c18c73..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon16.imageset/icon16.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/Contents.json deleted file mode 100644 index 5d48cc1..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon17.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/icon17.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/icon17.png deleted file mode 100644 index 2b90474..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon17.imageset/icon17.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/Contents.json deleted file mode 100644 index d718bd2..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon18.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/icon18.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/icon18.png deleted file mode 100644 index 0f95fab..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon18.imageset/icon18.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/Contents.json deleted file mode 100644 index f42d707..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon19.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/icon19.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/icon19.png deleted file mode 100644 index 5c99ffe..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon19.imageset/icon19.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/Contents.json deleted file mode 100644 index 17c812b..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon2.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/icon2.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/icon2.png deleted file mode 100644 index b373acf..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon2.imageset/icon2.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/Contents.json deleted file mode 100644 index da136e4..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon20.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/icon20.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/icon20.png deleted file mode 100644 index 7753c21..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon20.imageset/icon20.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/Contents.json deleted file mode 100644 index aedfdba..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon21.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/icon21.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/icon21.png deleted file mode 100644 index eb5fb81..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon21.imageset/icon21.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/Contents.json deleted file mode 100644 index 2927533..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon22.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/icon22.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/icon22.png deleted file mode 100644 index d190b8c..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon22.imageset/icon22.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/Contents.json deleted file mode 100644 index bc7d425..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon23.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/icon23.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/icon23.png deleted file mode 100644 index 84cf013..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon23.imageset/icon23.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/Contents.json deleted file mode 100644 index 105e582..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon24.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/icon24.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/icon24.png deleted file mode 100644 index 47f3cd2..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon24.imageset/icon24.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/Contents.json deleted file mode 100644 index 8b2b230..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon25.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/icon25.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/icon25.png deleted file mode 100644 index 12f6f8e..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon25.imageset/icon25.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/Contents.json deleted file mode 100644 index aaaafab..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon26.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/icon26.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/icon26.png deleted file mode 100644 index 8e20550..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon26.imageset/icon26.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/Contents.json deleted file mode 100644 index aacb1e4..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon27.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/icon27.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/icon27.png deleted file mode 100644 index 7032ceb..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon27.imageset/icon27.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/Contents.json deleted file mode 100644 index 0df5161..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon28.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/icon28.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/icon28.png deleted file mode 100644 index 76c275e..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon28.imageset/icon28.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/Contents.json deleted file mode 100644 index f941915..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon29.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/icon29.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/icon29.png deleted file mode 100644 index 1b876d2..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon29.imageset/icon29.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/Contents.json deleted file mode 100644 index 8806f8a..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon3.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/icon3.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/icon3.png deleted file mode 100644 index 67cf720..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon3.imageset/icon3.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/Contents.json deleted file mode 100644 index 0c69f4b..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon30.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/icon30.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/icon30.png deleted file mode 100644 index 7d9d9f4..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon30.imageset/icon30.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/Contents.json deleted file mode 100644 index 34f1734..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon31.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/icon31.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/icon31.png deleted file mode 100644 index d4aafd4..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon31.imageset/icon31.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/Contents.json deleted file mode 100644 index 1db2002..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon32.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/icon32.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/icon32.png deleted file mode 100644 index 33fc520..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon32.imageset/icon32.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/Contents.json deleted file mode 100644 index 82ac739..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon33.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/icon33.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/icon33.png deleted file mode 100644 index 008fb44..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon33.imageset/icon33.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/Contents.json deleted file mode 100644 index 1ad12d5..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon34.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/icon34.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/icon34.png deleted file mode 100644 index 9a5cd4b..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon34.imageset/icon34.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/Contents.json deleted file mode 100644 index dd24450..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon35.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/icon35.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/icon35.png deleted file mode 100644 index 3c68662..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon35.imageset/icon35.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/Contents.json deleted file mode 100644 index 4604ebe..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon36.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/icon36.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/icon36.png deleted file mode 100644 index 96c9be1..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon36.imageset/icon36.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/Contents.json deleted file mode 100644 index 4d0fc54..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon37.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/icon37.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/icon37.png deleted file mode 100644 index a8f13b2..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon37.imageset/icon37.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/Contents.json deleted file mode 100644 index a859d0a..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon38.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/icon38.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/icon38.png deleted file mode 100644 index b295a48..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon38.imageset/icon38.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/Contents.json deleted file mode 100644 index 50b3cef..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon39.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/icon39.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/icon39.png deleted file mode 100644 index a877afd..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon39.imageset/icon39.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/Contents.json deleted file mode 100644 index 3a53efc..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon4.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/icon4.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/icon4.png deleted file mode 100644 index f5f0e7d..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon4.imageset/icon4.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/Contents.json deleted file mode 100644 index 90a3bd4..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon40.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/icon40.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/icon40.png deleted file mode 100644 index daedb7b..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon40.imageset/icon40.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/Contents.json deleted file mode 100644 index 3d630c6..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon41.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/icon41.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/icon41.png deleted file mode 100644 index 6d2380d..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon41.imageset/icon41.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/Contents.json deleted file mode 100644 index 4267fb7..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon42.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/icon42.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/icon42.png deleted file mode 100644 index a441318..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon42.imageset/icon42.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/Contents.json deleted file mode 100644 index 7b112de..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon5.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/icon5.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/icon5.png deleted file mode 100644 index f78f9ac..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon5.imageset/icon5.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/Contents.json deleted file mode 100644 index 335b7a3..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon6.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/icon6.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/icon6.png deleted file mode 100644 index 52bbf9b..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon6.imageset/icon6.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/Contents.json deleted file mode 100644 index c09cb9e..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon7.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/icon7.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/icon7.png deleted file mode 100644 index 8997c43..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon7.imageset/icon7.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/Contents.json deleted file mode 100644 index 7c9fc06..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon8.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/icon8.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/icon8.png deleted file mode 100644 index f1f4d7e..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon8.imageset/icon8.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/Contents.json deleted file mode 100644 index 393b86c..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "icon9.png" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/icon9.png b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/icon9.png deleted file mode 100644 index 6067ea0..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/icons/icon9.imageset/icon9.png and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/Contents.json deleted file mode 100644 index d3e7515..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes1.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/clothes1.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/clothes1.jpg deleted file mode 100644 index d972fed..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes1.imageset/clothes1.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/Contents.json deleted file mode 100644 index 1925329..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes2.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/clothes2.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/clothes2.jpg deleted file mode 100644 index eb06102..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes2.imageset/clothes2.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/Contents.json deleted file mode 100644 index 39e9f4e..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes3.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/clothes3.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/clothes3.jpg deleted file mode 100644 index eadfe56..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes3.imageset/clothes3.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/Contents.json deleted file mode 100644 index 4d06923..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes4.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/clothes4.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/clothes4.jpg deleted file mode 100644 index d7f9c58..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes4.imageset/clothes4.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/Contents.json deleted file mode 100644 index 08371de..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes5.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/clothes5.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/clothes5.jpg deleted file mode 100644 index 091face..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes5.imageset/clothes5.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/Contents.json b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/Contents.json deleted file mode 100644 index 4fbc001..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/Contents.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "clothes6.jpg" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - }, - "properties" : { - "preserves-vector-representation" : true - } -} \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/clothes6.jpg b/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/clothes6.jpg deleted file mode 100644 index 93ab6c7..0000000 Binary files a/Lesson10/Lesson10Task1/Lesson10Task1/Assets.xcassets/images/clothes6.imageset/clothes6.jpg and /dev/null differ diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Base.lproj/Main.storyboard b/Lesson10/Lesson10Task1/Lesson10Task1/Base.lproj/Main.storyboard deleted file mode 100644 index b07165a..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Base.lproj/Main.storyboard +++ /dev/null @@ -1,429 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/CollectionViewViewController.swift b/Lesson10/Lesson10Task1/Lesson10Task1/CollectionViewViewController.swift deleted file mode 100644 index 11eee03..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/CollectionViewViewController.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// CollectionViewViewController.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class CollectionViewViewController: UIViewController { - - var product: [ProductShopModel] = [] - - @IBOutlet weak var collectionView: UICollectionView! - - override func viewDidLoad() { - super.viewDidLoad() - - product = getMockedData() - } - - func getMockedData() -> [ProductShopModel] { - return [ - ProductShopModel(name: "Жакет женский", - oldPrice: 4999, - sale: 40, - productImage: UIImage(imageLiteralResourceName: "clothes1")), - ProductShopModel(name: "Кофта женская", - oldPrice: 3599, - sale: 35, - productImage: UIImage(imageLiteralResourceName: "clothes2")), - ProductShopModel(name: "Рубашка мужская", - oldPrice: 6999, - sale: 60, - productImage: UIImage(imageLiteralResourceName: "clothes3")), - ProductShopModel(name: "Куртка мужская", - oldPrice: 13999, - sale: 50, - productImage: UIImage(imageLiteralResourceName: "clothes4")), - ProductShopModel(name: "Платье женское", - oldPrice: 8999, - sale: 75, - productImage: UIImage(imageLiteralResourceName: "clothes5")), - ProductShopModel(name: "Свитшот мужской", - oldPrice: 4999, - sale: 30, - productImage: UIImage(imageLiteralResourceName: "clothes6")) - ] - } - - func throughText(text: String) -> NSAttributedString { - let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text) - attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) - return attributeString - } -} - -extension CollectionViewViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - let width = view.bounds.width / 2 - 26 - return CGSize(width: width, height: collectionView.bounds.height / 2 - 10) - } - - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - product.count - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShopCell", for: indexPath) as! ShopCollectionViewCell - - var currentProduct = product[indexPath.row] - cell.productImageView.image = currentProduct.productImage - cell.oldPriceLabel.attributedText = throughText(text: "\(currentProduct.oldPrice) руб.") - cell.saleLabel.text = "-\(currentProduct.sale)%" - cell.currentPriceLabel.text = "\(currentProduct.currentPrice) руб." - cell.nameProductLabel.text = currentProduct.name - - return cell - } - - -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Model/MenuItemModel.swift b/Lesson10/Lesson10Task1/Lesson10Task1/Model/MenuItemModel.swift deleted file mode 100644 index 8df3a2b..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Model/MenuItemModel.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// MenuItemModel.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -struct MenuItemModel { - let icon: UIImage - let name: String -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Model/ProductShopModel.swift b/Lesson10/Lesson10Task1/Lesson10Task1/Model/ProductShopModel.swift deleted file mode 100644 index a3c4741..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Model/ProductShopModel.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// ProductShopModel.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -struct ProductShopModel { - let name: String - let oldPrice: Int - let sale: Int - let productImage: UIImage - - lazy var currentPrice: Int = { - return roundUp((Double(oldPrice) * (Double(sale) / 100)), toNearest: 500) - 1 - }() - - init(name: String, - oldPrice: Int, - sale: Int, - productImage: UIImage) { - self.name = name - self.oldPrice = oldPrice - self.sale = sale - self.productImage = productImage - } - - func roundUp(_ value: Double, toNearest: Double) -> Int { - return Int(ceil(value / toNearest) * toNearest) - } -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/SceneDelegate.swift b/Lesson10/Lesson10Task1/Lesson10Task1/SceneDelegate.swift deleted file mode 100644 index cfe649c..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/SceneDelegate.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// SceneDelegate.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - - var window: UIWindow? - - - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). - guard let _ = (scene as? UIWindowScene) else { return } - } - - func sceneDidDisconnect(_ scene: UIScene) { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). - } - - func sceneDidBecomeActive(_ scene: UIScene) { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. - } - - func sceneWillResignActive(_ scene: UIScene) { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). - } - - func sceneWillEnterForeground(_ scene: UIScene) { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. - } - - func sceneDidEnterBackground(_ scene: UIScene) { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. - } - - -} - diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Support/MenuTableViewCell.swift b/Lesson10/Lesson10Task1/Lesson10Task1/Support/MenuTableViewCell.swift deleted file mode 100644 index 0d7330f..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Support/MenuTableViewCell.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// MenuTableViewCell.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class MenuTableViewCell: UITableViewCell { - - @IBOutlet weak var menuItemIcon: UIImageView! - @IBOutlet weak var menuItemName: UILabel! - - override func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - override func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/Support/ShopCollectionViewCell.swift b/Lesson10/Lesson10Task1/Lesson10Task1/Support/ShopCollectionViewCell.swift deleted file mode 100644 index 4f10d94..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/Support/ShopCollectionViewCell.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// ShopCollectionViewCell.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class ShopCollectionViewCell: UICollectionViewCell { - - @IBOutlet weak var productImageView: UIImageView! - @IBOutlet weak var oldPriceLabel: UILabel! - @IBOutlet weak var currentPriceLabel: UILabel! - @IBOutlet weak var nameProductLabel: UILabel! - @IBOutlet weak var saleLabel: UILabel! -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/TableViewViewController.swift b/Lesson10/Lesson10Task1/Lesson10Task1/TableViewViewController.swift deleted file mode 100644 index 31cbae5..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/TableViewViewController.swift +++ /dev/null @@ -1,83 +0,0 @@ -// -// TableViewViewController.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class TableViewViewController: UIViewController { - - @IBOutlet weak var tableView: UITableView! - - var menuItems: [[MenuItemModel]] = [] - - func getMockedData() -> [[MenuItemModel]] { - var firstSection: [MenuItemModel] = [] - var secondSection: [MenuItemModel] = [] - var thirdSection: [MenuItemModel] = [] - var fourthSection: [MenuItemModel] = [] - for index in 1...42 { - let name = "Настройка №\(index)" - if index % 7 == 0 { - firstSection.append(MenuItemModel(icon: UIImage(imageLiteralResourceName: "icon\(index)"), name: name)) - continue - } - if index % 3 == 0 { - secondSection.append(MenuItemModel(icon: UIImage(imageLiteralResourceName: "icon\(index)"), name: name)) - continue - } - if index % 2 == 0 { - fourthSection.append(MenuItemModel(icon: UIImage(imageLiteralResourceName: "icon\(index)"), name: name)) - continue - } - thirdSection.append(MenuItemModel(icon: UIImage(imageLiteralResourceName: "icon\(index)"), name: name)) - } - return [firstSection, secondSection, thirdSection, fourthSection] - } - - override func viewDidLoad() { - super.viewDidLoad() - - menuItems = getMockedData() - view.backgroundColor = .lightGray - } -} - -extension TableViewViewController: UITableViewDataSource, UITableViewDelegate { - - func numberOfSections(in tableView: UITableView) -> Int { - return menuItems.count - } - - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return menuItems[section].count - } - - func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { - if section != 0 { - let header = UIView(frame: CGRect(x: 0, - y: 0, - width: view.bounds.width, - height: 16)) - header.backgroundColor = .gray - return header - } - return UIView() - } - - func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "MenuItemCell") as! MenuTableViewCell - - cell.menuItemIcon.image = menuItems[indexPath.section][indexPath.row].icon - cell.menuItemName.text = menuItems[indexPath.section][indexPath.row].name - - return cell - } - - func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - tableView.deselectRow(at: indexPath, animated: true) - } -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/UIView+Extension.swift b/Lesson10/Lesson10Task1/Lesson10Task1/UIView+Extension.swift deleted file mode 100644 index 4ceb820..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/UIView+Extension.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// UIView+Extension.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 29.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -extension UIView { - - @IBInspectable var cornerRadius: CGFloat { - get { - return layer.cornerRadius - } - set { - layer.cornerRadius = newValue - layer.masksToBounds = newValue > 0 - } - } - - @IBInspectable var borderWidth: CGFloat { - get { - return layer.borderWidth - } - set { - layer.borderWidth = newValue - } - } - - @IBInspectable var borderColor: UIColor? { - get { - return UIColor(cgColor: layer.borderColor!) - } - set { - layer.borderColor = newValue?.cgColor - } - } -} diff --git a/Lesson10/Lesson10Task1/Lesson10Task1/ViewController.swift b/Lesson10/Lesson10Task1/Lesson10Task1/ViewController.swift deleted file mode 100644 index 4a01512..0000000 --- a/Lesson10/Lesson10Task1/Lesson10Task1/ViewController.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// ViewController.swift -// Lesson10Task1 -// -// Created by Михаил Беленко on 24.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class ViewController: UIViewController { - - @IBOutlet weak var segmentedControl: UISegmentedControl! - - override func viewDidLoad() { - super.viewDidLoad() - - setChildViewController(controller: storyboard!.instantiateViewController(identifier: "CollectionViewViewController")) - } - - private func setChildViewController(controller: UIViewController) { - addChild(controller) - controller.view.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(controller.view) - - NSLayoutConstraint.activate([ - controller.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), - controller.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), - controller.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), - controller.view.bottomAnchor.constraint(equalTo: segmentedControl.topAnchor, constant: -8) - ]) - - controller.didMove(toParent: self) - } - - @IBAction func changeSegmantedControl(_ sender: Any) { - switch segmentedControl.selectedSegmentIndex { - case 0: - setChildViewController(controller: storyboard!.instantiateViewController(identifier: "CollectionViewViewController")) - case 1: - setChildViewController(controller: storyboard!.instantiateViewController(identifier: "TableViewViewController")) - case 2: - setChildViewController(controller: storyboard!.instantiateViewController(identifier: "ScrollViewViewController")) - default: - fatalError("imposible") - } - } -} - diff --git a/Lesson10/Lesson10Task1/Podfile b/Lesson10/Lesson10Task1/Podfile deleted file mode 100644 index 956778b..0000000 --- a/Lesson10/Lesson10Task1/Podfile +++ /dev/null @@ -1,11 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'Lesson10Task1' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - # Pods for Lesson10Task1 - pod 'SnapKit', '~> 5.0.0' - -end diff --git a/Lesson10/Lesson10Task1/Podfile.lock b/Lesson10/Lesson10Task1/Podfile.lock deleted file mode 100644 index de404aa..0000000 --- a/Lesson10/Lesson10Task1/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - SnapKit (5.0.1) - -DEPENDENCIES: - - SnapKit (~> 5.0.0) - -SPEC REPOS: - trunk: - - SnapKit - -SPEC CHECKSUMS: - SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb - -PODFILE CHECKSUM: 6110f26eeedaedf32f89e392c0db25bc3fb87938 - -COCOAPODS: 1.8.4 diff --git a/Lesson10/Lesson10Task1/Pods/Manifest.lock b/Lesson10/Lesson10Task1/Pods/Manifest.lock deleted file mode 100644 index de404aa..0000000 --- a/Lesson10/Lesson10Task1/Pods/Manifest.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - SnapKit (5.0.1) - -DEPENDENCIES: - - SnapKit (~> 5.0.0) - -SPEC REPOS: - trunk: - - SnapKit - -SPEC CHECKSUMS: - SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb - -PODFILE CHECKSUM: 6110f26eeedaedf32f89e392c0db25bc3fb87938 - -COCOAPODS: 1.8.4 diff --git a/Lesson10/Lesson10Task1/Pods/Pods.xcodeproj/project.pbxproj b/Lesson10/Lesson10Task1/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 7ed3423..0000000 --- a/Lesson10/Lesson10Task1/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,746 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 50; - objects = { - -/* Begin PBXBuildFile section */ - 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = E56D17419B45F7AEA8E9FD4713B0D394 /* ConstraintLayoutSupportDSL.swift */; }; - 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = F738E14AC76C938181436DD3CAF2C114 /* LayoutConstraint.swift */; }; - 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */; }; - 132A0BAE04761AC4A0C22ABA49694DEC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */; }; - 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2048BAD969893AF74BE692ED91CDAF1A /* Typealiases.swift */; }; - 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90363F632F42F81DAFA242A8F46218E7 /* ConstraintLayoutGuide+Extensions.swift */; }; - 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCAC4BBC219F813FDC65BFB63E07DCFA /* ConstraintInsets.swift */; }; - 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CFFD5DFB83283597B0DC408E2144099 /* ConstraintPriority.swift */; }; - 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F5E9E5E8037CC20D5EF42A328034DC /* ConstraintAttributes.swift */; }; - 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07E06B9BA934C46F84976ABC2D7141ED /* ConstraintInsetTarget.swift */; }; - 37A8F007A30CE988DE540DDA9628907C /* Pods-Lesson10Task1-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CE7AE990D0898F2E8613811BBC06ED9 /* Pods-Lesson10Task1-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB0B9A61896874A4153DA213B5FDBA23 /* Constraint.swift */; }; - 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62904996FDA9DE5467B70321F8C07955 /* ConstraintView+Extensions.swift */; }; - 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 754536E6E725F807D5C3BAAD54EACF2D /* SnapKit-dummy.m */; }; - 5157F021CBD326D601625A02739821A1 /* Pods-Lesson10Task1-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 56FA693D8AD037A8FA81B0BFB0520FE0 /* Pods-Lesson10Task1-dummy.m */; }; - 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2813DAD1A398260A46420E012A4EC917 /* ConstraintMaker.swift */; }; - 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 941EB7E88E4E7360C4C459DFAF3CDDDA /* ConstraintLayoutSupport.swift */; }; - 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61EC6EE15D4D67183E93DEDF18A40981 /* ConstraintConstantTarget.swift */; }; - 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D418A1EF57CADF7AC73AE2E19D3475E1 /* ConstraintMakerExtendable.swift */; }; - 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAD407D076C59AEB6AFE4508E4B95808 /* ConstraintRelatableTarget.swift */; }; - 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F2E193C13A3A14CB612EB51F05A543B /* UILayoutSupport+Extensions.swift */; }; - 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB481C58427FA3F4E097F6E133F8118B /* ConstraintDirectionalInsetTarget.swift */; }; - 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDDD718AFA0616F5C00341E1E3B64D5E /* ConstraintMakerRelatable.swift */; }; - 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42D9B891112E7E8DC9504C3CC09FB484 /* ConstraintLayoutGuideDSL.swift */; }; - 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95615519C42793A3F9BFD614096E493A /* ConstraintMakerEditable.swift */; }; - 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FFFB67EF8E7135A063A1163E2BE514E /* ConstraintDSL.swift */; }; - 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C4D286E4BD20698B5C694EA69111A47 /* ConstraintOffsetTarget.swift */; }; - 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FF26E13590AB8190A1F5DEC7E7BECCA /* ConstraintItem.swift */; }; - 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AA803CC2969C21BC90D73347E1980B1 /* ConstraintConfig.swift */; }; - A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = 101A54E43B6DFAA6BC849E4547B7C282 /* ConstraintLayoutGuide.swift */; }; - A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D17D99D978CF81C2FE6BC01137C7E9F /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = E86CFD34EFB62B5D4FA9AB14C2F3654F /* ConstraintDirectionalInsets.swift */; }; - B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90D94FD5F9D1E70514063D05CF6ABC99 /* ConstraintDescription.swift */; }; - B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA08B21F65760AB725806CF81513EDD6 /* Debugging.swift */; }; - BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1ACF77247BB1059203369EEA2F03D76 /* ConstraintView.swift */; }; - C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFA26282AD0058A9D2C5E948FB218029 /* ConstraintMakerFinalizable.swift */; }; - CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09EEF551863CDDE4C5DFB0B0C1BD9835 /* ConstraintRelation.swift */; }; - D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC5B4F88C96976B456904499E9530A03 /* ConstraintMultiplierTarget.swift */; }; - E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46A818CD9D52DAB63058A6279B32B948 /* ConstraintPriorityTarget.swift */; }; - E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CA0A5F80FD7D1C11B44362F2840A71F /* LayoutConstraintItem.swift */; }; - EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51C387F75F998F3D11ACA67B32F28A89 /* ConstraintViewDSL.swift */; }; - EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B39E09B644150C5F99180FDFDFD440D0 /* ConstraintMakerPriortizable.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 89F74AD46F63C597D484866B7D45E396 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; - remoteInfo = SnapKit; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 07E06B9BA934C46F84976ABC2D7141ED /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; - 09EEF551863CDDE4C5DFB0B0C1BD9835 /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Source/ConstraintRelation.swift; sourceTree = ""; }; - 0FFFB67EF8E7135A063A1163E2BE514E /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Source/ConstraintDSL.swift; sourceTree = ""; }; - 101A54E43B6DFAA6BC849E4547B7C282 /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Source/ConstraintLayoutGuide.swift; sourceTree = ""; }; - 2048BAD969893AF74BE692ED91CDAF1A /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Source/Typealiases.swift; sourceTree = ""; }; - 2813DAD1A398260A46420E012A4EC917 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; - 2CE7AE990D0898F2E8613811BBC06ED9 /* Pods-Lesson10Task1-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Lesson10Task1-umbrella.h"; sourceTree = ""; }; - 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 3C4D286E4BD20698B5C694EA69111A47 /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Source/ConstraintOffsetTarget.swift; sourceTree = ""; }; - 3CFFD5DFB83283597B0DC408E2144099 /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Source/ConstraintPriority.swift; sourceTree = ""; }; - 3F2E193C13A3A14CB612EB51F05A543B /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Source/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; - 42D9B891112E7E8DC9504C3CC09FB484 /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Source/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; - 46A818CD9D52DAB63058A6279B32B948 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; - 4EA58997FF74CFB289C04181D0B5C261 /* Pods-Lesson10Task1-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Lesson10Task1-acknowledgements.markdown"; sourceTree = ""; }; - 51C387F75F998F3D11ACA67B32F28A89 /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Source/ConstraintViewDSL.swift; sourceTree = ""; }; - 56FA693D8AD037A8FA81B0BFB0520FE0 /* Pods-Lesson10Task1-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Lesson10Task1-dummy.m"; sourceTree = ""; }; - 5971695E6F467F210FBA5D8DDBF3D5DD /* Pods-Lesson10Task1-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Lesson10Task1-frameworks.sh"; sourceTree = ""; }; - 61EC6EE15D4D67183E93DEDF18A40981 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Source/ConstraintConstantTarget.swift; sourceTree = ""; }; - 62904996FDA9DE5467B70321F8C07955 /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Source/ConstraintView+Extensions.swift"; sourceTree = ""; }; - 6AA803CC2969C21BC90D73347E1980B1 /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Source/ConstraintConfig.swift; sourceTree = ""; }; - 74B8ABA4F93FA9E68362C7C76006D5C9 /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; - 754536E6E725F807D5C3BAAD54EACF2D /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; - 7D17D99D978CF81C2FE6BC01137C7E9F /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; - 7E511DC742D2D9571D1AE768505A7F95 /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; - 7FF26E13590AB8190A1F5DEC7E7BECCA /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Source/ConstraintItem.swift; sourceTree = ""; }; - 8CA0A5F80FD7D1C11B44362F2840A71F /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Source/LayoutConstraintItem.swift; sourceTree = ""; }; - 90363F632F42F81DAFA242A8F46218E7 /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Source/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; - 90D94FD5F9D1E70514063D05CF6ABC99 /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Source/ConstraintDescription.swift; sourceTree = ""; }; - 90F5E9E5E8037CC20D5EF42A328034DC /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; - 941EB7E88E4E7360C4C459DFAF3CDDDA /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Source/ConstraintLayoutSupport.swift; sourceTree = ""; }; - 9485341768A2EED5F312B913A963A8B2 /* Pods-Lesson10Task1.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson10Task1.debug.xcconfig"; sourceTree = ""; }; - 95615519C42793A3F9BFD614096E493A /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Source/ConstraintMakerEditable.swift; sourceTree = ""; }; - 979486118B3E90C08386079D57962701 /* SnapKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit.framework; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9A8860C52E1C4160B71696E3B6A361D3 /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - A6FBA9B1482818C5E83D091723D59C92 /* Pods-Lesson10Task1.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson10Task1.release.xcconfig"; sourceTree = ""; }; - A7C030BDF220D7B78052E74729E94DBA /* Pods_Lesson10Task1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Lesson10Task1.framework; path = "Pods-Lesson10Task1.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - A9DC1416BB8D683DA0609A8D9C1D1D8F /* SnapKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.xcconfig; sourceTree = ""; }; - AA08B21F65760AB725806CF81513EDD6 /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.swift; sourceTree = ""; }; - AAD407D076C59AEB6AFE4508E4B95808 /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Source/ConstraintRelatableTarget.swift; sourceTree = ""; }; - B39E09B644150C5F99180FDFDFD440D0 /* ConstraintMakerPriortizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPriortizable.swift; path = Source/ConstraintMakerPriortizable.swift; sourceTree = ""; }; - BB0B9A61896874A4153DA213B5FDBA23 /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Source/Constraint.swift; sourceTree = ""; }; - BB481C58427FA3F4E097F6E133F8118B /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Source/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; - CA8286E787457F6C7F7FFB83131EE0EF /* Pods-Lesson10Task1-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson10Task1-acknowledgements.plist"; sourceTree = ""; }; - D0C38630844976AB3C9490A7C3E78A9E /* Pods-Lesson10Task1-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson10Task1-Info.plist"; sourceTree = ""; }; - D418A1EF57CADF7AC73AE2E19D3475E1 /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Source/ConstraintMakerExtendable.swift; sourceTree = ""; }; - DCAC4BBC219F813FDC65BFB63E07DCFA /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Source/ConstraintInsets.swift; sourceTree = ""; }; - E1ACF77247BB1059203369EEA2F03D76 /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Source/ConstraintView.swift; sourceTree = ""; }; - E56D17419B45F7AEA8E9FD4713B0D394 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Source/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; - E86CFD34EFB62B5D4FA9AB14C2F3654F /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Source/ConstraintDirectionalInsets.swift; sourceTree = ""; }; - EC42204F6A6F37B8A700CBDC221C714A /* Pods-Lesson10Task1.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Lesson10Task1.modulemap"; sourceTree = ""; }; - EC5B4F88C96976B456904499E9530A03 /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Source/ConstraintMultiplierTarget.swift; sourceTree = ""; }; - EDDD718AFA0616F5C00341E1E3B64D5E /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Source/ConstraintMakerRelatable.swift; sourceTree = ""; }; - F738E14AC76C938181436DD3CAF2C114 /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; - FFA26282AD0058A9D2C5E948FB218029 /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Source/ConstraintMakerFinalizable.swift; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C94706C2EE607510176ABC49DB55C23A /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 132A0BAE04761AC4A0C22ABA49694DEC /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 14D487C84B91C6E3C6AAF35FEBE9B1DF /* SnapKit */ = { - isa = PBXGroup; - children = ( - BB0B9A61896874A4153DA213B5FDBA23 /* Constraint.swift */, - 90F5E9E5E8037CC20D5EF42A328034DC /* ConstraintAttributes.swift */, - 6AA803CC2969C21BC90D73347E1980B1 /* ConstraintConfig.swift */, - 61EC6EE15D4D67183E93DEDF18A40981 /* ConstraintConstantTarget.swift */, - 90D94FD5F9D1E70514063D05CF6ABC99 /* ConstraintDescription.swift */, - E86CFD34EFB62B5D4FA9AB14C2F3654F /* ConstraintDirectionalInsets.swift */, - BB481C58427FA3F4E097F6E133F8118B /* ConstraintDirectionalInsetTarget.swift */, - 0FFFB67EF8E7135A063A1163E2BE514E /* ConstraintDSL.swift */, - DCAC4BBC219F813FDC65BFB63E07DCFA /* ConstraintInsets.swift */, - 07E06B9BA934C46F84976ABC2D7141ED /* ConstraintInsetTarget.swift */, - 7FF26E13590AB8190A1F5DEC7E7BECCA /* ConstraintItem.swift */, - 101A54E43B6DFAA6BC849E4547B7C282 /* ConstraintLayoutGuide.swift */, - 90363F632F42F81DAFA242A8F46218E7 /* ConstraintLayoutGuide+Extensions.swift */, - 42D9B891112E7E8DC9504C3CC09FB484 /* ConstraintLayoutGuideDSL.swift */, - 941EB7E88E4E7360C4C459DFAF3CDDDA /* ConstraintLayoutSupport.swift */, - E56D17419B45F7AEA8E9FD4713B0D394 /* ConstraintLayoutSupportDSL.swift */, - 2813DAD1A398260A46420E012A4EC917 /* ConstraintMaker.swift */, - 95615519C42793A3F9BFD614096E493A /* ConstraintMakerEditable.swift */, - D418A1EF57CADF7AC73AE2E19D3475E1 /* ConstraintMakerExtendable.swift */, - FFA26282AD0058A9D2C5E948FB218029 /* ConstraintMakerFinalizable.swift */, - B39E09B644150C5F99180FDFDFD440D0 /* ConstraintMakerPriortizable.swift */, - EDDD718AFA0616F5C00341E1E3B64D5E /* ConstraintMakerRelatable.swift */, - EC5B4F88C96976B456904499E9530A03 /* ConstraintMultiplierTarget.swift */, - 3C4D286E4BD20698B5C694EA69111A47 /* ConstraintOffsetTarget.swift */, - 3CFFD5DFB83283597B0DC408E2144099 /* ConstraintPriority.swift */, - 46A818CD9D52DAB63058A6279B32B948 /* ConstraintPriorityTarget.swift */, - AAD407D076C59AEB6AFE4508E4B95808 /* ConstraintRelatableTarget.swift */, - 09EEF551863CDDE4C5DFB0B0C1BD9835 /* ConstraintRelation.swift */, - E1ACF77247BB1059203369EEA2F03D76 /* ConstraintView.swift */, - 62904996FDA9DE5467B70321F8C07955 /* ConstraintView+Extensions.swift */, - 51C387F75F998F3D11ACA67B32F28A89 /* ConstraintViewDSL.swift */, - AA08B21F65760AB725806CF81513EDD6 /* Debugging.swift */, - F738E14AC76C938181436DD3CAF2C114 /* LayoutConstraint.swift */, - 8CA0A5F80FD7D1C11B44362F2840A71F /* LayoutConstraintItem.swift */, - 2048BAD969893AF74BE692ED91CDAF1A /* Typealiases.swift */, - 3F2E193C13A3A14CB612EB51F05A543B /* UILayoutSupport+Extensions.swift */, - 71BFF8DEE087891C80100BB29880775D /* Support Files */, - ); - name = SnapKit; - path = SnapKit; - sourceTree = ""; - }; - 31696D0773F955AF2D39C1ADCA8ABC9B /* Products */ = { - isa = PBXGroup; - children = ( - A7C030BDF220D7B78052E74729E94DBA /* Pods_Lesson10Task1.framework */, - 979486118B3E90C08386079D57962701 /* SnapKit.framework */, - ); - name = Products; - sourceTree = ""; - }; - 71BFF8DEE087891C80100BB29880775D /* Support Files */ = { - isa = PBXGroup; - children = ( - 7E511DC742D2D9571D1AE768505A7F95 /* SnapKit.modulemap */, - A9DC1416BB8D683DA0609A8D9C1D1D8F /* SnapKit.xcconfig */, - 754536E6E725F807D5C3BAAD54EACF2D /* SnapKit-dummy.m */, - 74B8ABA4F93FA9E68362C7C76006D5C9 /* SnapKit-Info.plist */, - 9A8860C52E1C4160B71696E3B6A361D3 /* SnapKit-prefix.pch */, - 7D17D99D978CF81C2FE6BC01137C7E9F /* SnapKit-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/SnapKit"; - sourceTree = ""; - }; - BA22F08D059965C9A09F78196176CEDB /* Pods */ = { - isa = PBXGroup; - children = ( - 14D487C84B91C6E3C6AAF35FEBE9B1DF /* SnapKit */, - ); - name = Pods; - sourceTree = ""; - }; - C0834CEBB1379A84116EF29F93051C60 /* iOS */ = { - isa = PBXGroup; - children = ( - 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */, - ); - name = iOS; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */, - BA22F08D059965C9A09F78196176CEDB /* Pods */, - 31696D0773F955AF2D39C1ADCA8ABC9B /* Products */, - FAC7563CE407AF6D21E0D3C4D7B3A146 /* Targets Support Files */, - ); - sourceTree = ""; - }; - D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */ = { - isa = PBXGroup; - children = ( - C0834CEBB1379A84116EF29F93051C60 /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - F6C6AAEED9EF4209F64D72945F7F00B6 /* Pods-Lesson10Task1 */ = { - isa = PBXGroup; - children = ( - EC42204F6A6F37B8A700CBDC221C714A /* Pods-Lesson10Task1.modulemap */, - 4EA58997FF74CFB289C04181D0B5C261 /* Pods-Lesson10Task1-acknowledgements.markdown */, - CA8286E787457F6C7F7FFB83131EE0EF /* Pods-Lesson10Task1-acknowledgements.plist */, - 56FA693D8AD037A8FA81B0BFB0520FE0 /* Pods-Lesson10Task1-dummy.m */, - 5971695E6F467F210FBA5D8DDBF3D5DD /* Pods-Lesson10Task1-frameworks.sh */, - D0C38630844976AB3C9490A7C3E78A9E /* Pods-Lesson10Task1-Info.plist */, - 2CE7AE990D0898F2E8613811BBC06ED9 /* Pods-Lesson10Task1-umbrella.h */, - 9485341768A2EED5F312B913A963A8B2 /* Pods-Lesson10Task1.debug.xcconfig */, - A6FBA9B1482818C5E83D091723D59C92 /* Pods-Lesson10Task1.release.xcconfig */, - ); - name = "Pods-Lesson10Task1"; - path = "Target Support Files/Pods-Lesson10Task1"; - sourceTree = ""; - }; - FAC7563CE407AF6D21E0D3C4D7B3A146 /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - F6C6AAEED9EF4209F64D72945F7F00B6 /* Pods-Lesson10Task1 */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 25926EBB740623D7269D71B6C34AB535 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 37A8F007A30CE988DE540DDA9628907C /* Pods-Lesson10Task1-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { - isa = PBXNativeTarget; - buildConfigurationList = 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */; - buildPhases = ( - 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */, - 89222AF845A30312C284F407BA48B98F /* Sources */, - 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */, - 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = SnapKit; - productName = SnapKit; - productReference = 979486118B3E90C08386079D57962701 /* SnapKit.framework */; - productType = "com.apple.product-type.framework"; - }; - 5E8D80B8C3EEEF972188050C0F076616 /* Pods-Lesson10Task1 */ = { - isa = PBXNativeTarget; - buildConfigurationList = E21F0FE5407084E4B1C9EB85DB8D93B5 /* Build configuration list for PBXNativeTarget "Pods-Lesson10Task1" */; - buildPhases = ( - 25926EBB740623D7269D71B6C34AB535 /* Headers */, - 7BC6450AB12C156486AA6E8F73D2A9EC /* Sources */, - C94706C2EE607510176ABC49DB55C23A /* Frameworks */, - 23DE8FEA37A35FA77DCFD1AE01FF555C /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - D714B18E65BBB94997F18D41BDC58D02 /* PBXTargetDependency */, - ); - name = "Pods-Lesson10Task1"; - productName = "Pods-Lesson10Task1"; - productReference = A7C030BDF220D7B78052E74729E94DBA /* Pods_Lesson10Task1.framework */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1100; - LastUpgradeCheck = 1100; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 31696D0773F955AF2D39C1ADCA8ABC9B /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 5E8D80B8C3EEEF972188050C0F076616 /* Pods-Lesson10Task1 */, - 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 23DE8FEA37A35FA77DCFD1AE01FF555C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 7BC6450AB12C156486AA6E8F73D2A9EC /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 5157F021CBD326D601625A02739821A1 /* Pods-Lesson10Task1-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 89222AF845A30312C284F407BA48B98F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */, - 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */, - 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */, - 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */, - B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */, - AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */, - 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */, - 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */, - 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */, - 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */, - 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */, - 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */, - A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */, - 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */, - 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */, - 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */, - 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */, - 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */, - 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */, - C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */, - EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */, - 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */, - D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */, - 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */, - 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */, - E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */, - 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */, - CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */, - 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */, - BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */, - EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */, - B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */, - 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */, - E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */, - 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */, - 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */, - 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - D714B18E65BBB94997F18D41BDC58D02 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = SnapKit; - target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; - targetProxy = 89F74AD46F63C597D484866B7D45E396 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 020BEC27E3AD6D7C84D288C148A58E74 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A9DC1416BB8D683DA0609A8D9C1D1D8F /* SnapKit.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; - PRODUCT_MODULE_NAME = SnapKit; - PRODUCT_NAME = SnapKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 2E3C8A300772E0028147E4BAF0D5078A /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A9DC1416BB8D683DA0609A8D9C1D1D8F /* SnapKit.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; - PRODUCT_MODULE_NAME = SnapKit; - PRODUCT_NAME = SnapKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 338F35E12CAB61A095B6BFB26E6E8B7C /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A6FBA9B1482818C5E83D091723D59C92 /* Pods-Lesson10Task1.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 510B057D2E9F059C50D52DA5D90F3ACF /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - 804E13245C9FBBE6A340C555CA8B2B4C /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - F580EDBE7B25BC4FB14052410C42D4A9 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9485341768A2EED5F312B913A963A8B2 /* Pods-Lesson10Task1.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 804E13245C9FBBE6A340C555CA8B2B4C /* Debug */, - 510B057D2E9F059C50D52DA5D90F3ACF /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 2E3C8A300772E0028147E4BAF0D5078A /* Debug */, - 020BEC27E3AD6D7C84D288C148A58E74 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - E21F0FE5407084E4B1C9EB85DB8D93B5 /* Build configuration list for PBXNativeTarget "Pods-Lesson10Task1" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F580EDBE7B25BC4FB14052410C42D4A9 /* Debug */, - 338F35E12CAB61A095B6BFB26E6E8B7C /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.markdown b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.markdown deleted file mode 100644 index 25f8f66..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.markdown +++ /dev/null @@ -1,26 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## SnapKit - -Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Generated by CocoaPods - https://cocoapods.org diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.plist b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.plist deleted file mode 100644 index 8474d45..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-acknowledgements.plist +++ /dev/null @@ -1,58 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - License - MIT - Title - SnapKit - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-dummy.m b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-dummy.m deleted file mode 100644 index c48beb1..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_Lesson10Task1 : NSObject -@end -@implementation PodsDummy_Pods_Lesson10Task1 -@end diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-input-files.xcfilelist b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-input-files.xcfilelist deleted file mode 100644 index 5b9c79f..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-input-files.xcfilelist +++ /dev/null @@ -1,2 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh -${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-output-files.xcfilelist b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-output-files.xcfilelist deleted file mode 100644 index b156f80..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Debug-output-files.xcfilelist +++ /dev/null @@ -1 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-input-files.xcfilelist b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-input-files.xcfilelist deleted file mode 100644 index 5b9c79f..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-input-files.xcfilelist +++ /dev/null @@ -1,2 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh -${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-output-files.xcfilelist b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-output-files.xcfilelist deleted file mode 100644 index b156f80..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks-Release-output-files.xcfilelist +++ /dev/null @@ -1 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework \ No newline at end of file diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh deleted file mode 100755 index b253b3b..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-frameworks.sh +++ /dev/null @@ -1,171 +0,0 @@ -#!/bin/sh -set -e -set -u -set -o pipefail - -function on_error { - echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" -} -trap 'on_error $LINENO' ERR - -if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then - # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy - # frameworks to, so exit 0 (signalling the script phase was successful). - exit 0 -fi - -echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" -mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - -COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" -SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" - -# Used as a return value for each invocation of `strip_invalid_archs` function. -STRIP_BINARY_RETVAL=0 - -# This protects against multiple targets copying the same framework dependency at the same time. The solution -# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html -RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") - -# Copies and strips a vendored framework -install_framework() -{ - if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then - local source="${BUILT_PRODUCTS_DIR}/$1" - elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then - local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" - elif [ -r "$1" ]; then - local source="$1" - fi - - local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - - if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink "${source}")" - fi - - # Use filter instead of exclude so missing patterns don't throw errors. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" - - local basename - basename="$(basename -s .framework "$1")" - binary="${destination}/${basename}.framework/${basename}" - - if ! [ -r "$binary" ]; then - binary="${destination}/${basename}" - elif [ -L "${binary}" ]; then - echo "Destination binary is symlinked..." - dirname="$(dirname "${binary}")" - binary="${dirname}/$(readlink "${binary}")" - fi - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then - strip_invalid_archs "$binary" - fi - - # Resign the code if required by the build settings to avoid unstable apps - code_sign_if_enabled "${destination}/$(basename "$1")" - - # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. - if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then - local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) - for lib in $swift_runtime_libs; do - echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" - rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" - code_sign_if_enabled "${destination}/${lib}" - done - fi -} - -# Copies and strips a vendored dSYM -install_dsym() { - local source="$1" - if [ -r "$source" ]; then - # Copy the dSYM into a the targets temp dir. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" - - local basename - basename="$(basename -s .framework.dSYM "$source")" - binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then - strip_invalid_archs "$binary" - fi - - if [[ $STRIP_BINARY_RETVAL == 1 ]]; then - # Move the stripped file into its final destination. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" - else - # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. - touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" - fi - fi -} - -# Copies the bcsymbolmap files of a vendored framework -install_bcsymbolmap() { - local bcsymbolmap_path="$1" - local destination="${BUILT_PRODUCTS_DIR}" - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" -} - -# Signs a framework with the provided identity -code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identity - echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" - - if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - code_sign_cmd="$code_sign_cmd &" - fi - echo "$code_sign_cmd" - eval "$code_sign_cmd" - fi -} - -# Strip invalid architectures -strip_invalid_archs() { - binary="$1" - # Get architectures for current target binary - binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" - # Intersect them with the architectures we are building for - intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" - # If there are no archs supported by this binary then warn the user - if [[ -z "$intersected_archs" ]]; then - echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." - STRIP_BINARY_RETVAL=0 - return - fi - stripped="" - for arch in $binary_archs; do - if ! [[ "${ARCHS}" == *"$arch"* ]]; then - # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" - stripped="$stripped $arch" - fi - done - if [[ "$stripped" ]]; then - echo "Stripped $binary of architectures:$stripped" - fi - STRIP_BINARY_RETVAL=1 -} - - -if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" -fi -if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" -fi -if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - wait -fi diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-umbrella.h b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-umbrella.h deleted file mode 100644 index 4645a59..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_Lesson10Task1VersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_Lesson10Task1VersionString[]; - diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.debug.xcconfig b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.debug.xcconfig deleted file mode 100644 index d5c8ea8..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "SnapKit" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.modulemap b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.modulemap deleted file mode 100644 index d1aec19..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_Lesson10Task1 { - umbrella header "Pods-Lesson10Task1-umbrella.h" - - export * - module * { export * } -} diff --git a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.release.xcconfig b/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.release.xcconfig deleted file mode 100644 index d5c8ea8..0000000 --- a/Lesson10/Lesson10Task1/Pods/Target Support Files/Pods-Lesson10Task1/Pods-Lesson10Task1.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "SnapKit" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Lesson11/Lesson11.xcodeproj/project.pbxproj b/Lesson11/Lesson11.xcodeproj/project.pbxproj deleted file mode 100644 index 0821b49..0000000 --- a/Lesson11/Lesson11.xcodeproj/project.pbxproj +++ /dev/null @@ -1,371 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 50; - objects = { - -/* Begin PBXBuildFile section */ - 33ACCD9E23E2C995006D9067 /* CustomSegmentControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33ACCD9D23E2C995006D9067 /* CustomSegmentControl.swift */; }; - 33D550D823E1A98900C3B724 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D550D723E1A98900C3B724 /* AppDelegate.swift */; }; - 33D550DC23E1A98900C3B724 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D550DB23E1A98900C3B724 /* ViewController.swift */; }; - 33D550DF23E1A98900C3B724 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33D550DD23E1A98900C3B724 /* Main.storyboard */; }; - 33D550E123E1A99000C3B724 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33D550E023E1A99000C3B724 /* Assets.xcassets */; }; - 33D550E423E1A99000C3B724 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33D550E223E1A99000C3B724 /* LaunchScreen.storyboard */; }; - 33D550ED23E1A9C500C3B724 /* CustomButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D550EC23E1A9C500C3B724 /* CustomButton.swift */; }; - 33D550F023E1AD6D00C3B724 /* ClockView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D550EF23E1AD6D00C3B724 /* ClockView.swift */; }; - 33D550F223E1AD8400C3B724 /* ClockView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33D550F123E1AD8400C3B724 /* ClockView.xib */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 33ACCD9D23E2C995006D9067 /* CustomSegmentControl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomSegmentControl.swift; sourceTree = ""; }; - 33D550D423E1A98900C3B724 /* Lesson11.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lesson11.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 33D550D723E1A98900C3B724 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33D550DB23E1A98900C3B724 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; - 33D550DE23E1A98900C3B724 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 33D550E023E1A99000C3B724 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 33D550E323E1A99000C3B724 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 33D550E523E1A99000C3B724 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 33D550EC23E1A9C500C3B724 /* CustomButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomButton.swift; sourceTree = ""; }; - 33D550EF23E1AD6D00C3B724 /* ClockView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClockView.swift; sourceTree = ""; }; - 33D550F123E1AD8400C3B724 /* ClockView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ClockView.xib; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 33D550D123E1A98900C3B724 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 33D550CB23E1A98900C3B724 = { - isa = PBXGroup; - children = ( - 33D550D623E1A98900C3B724 /* Lesson11 */, - 33D550D523E1A98900C3B724 /* Products */, - ); - sourceTree = ""; - }; - 33D550D523E1A98900C3B724 /* Products */ = { - isa = PBXGroup; - children = ( - 33D550D423E1A98900C3B724 /* Lesson11.app */, - ); - name = Products; - sourceTree = ""; - }; - 33D550D623E1A98900C3B724 /* Lesson11 */ = { - isa = PBXGroup; - children = ( - 33D550EB23E1A9A000C3B724 /* CustomView */, - 33D550D723E1A98900C3B724 /* AppDelegate.swift */, - 33D550DB23E1A98900C3B724 /* ViewController.swift */, - 33D550DD23E1A98900C3B724 /* Main.storyboard */, - 33D550E023E1A99000C3B724 /* Assets.xcassets */, - 33D550E223E1A99000C3B724 /* LaunchScreen.storyboard */, - 33D550E523E1A99000C3B724 /* Info.plist */, - ); - path = Lesson11; - sourceTree = ""; - }; - 33D550EB23E1A9A000C3B724 /* CustomView */ = { - isa = PBXGroup; - children = ( - 33D550EE23E1AD5200C3B724 /* ClockView */, - 33D550EC23E1A9C500C3B724 /* CustomButton.swift */, - 33ACCD9D23E2C995006D9067 /* CustomSegmentControl.swift */, - ); - path = CustomView; - sourceTree = ""; - }; - 33D550EE23E1AD5200C3B724 /* ClockView */ = { - isa = PBXGroup; - children = ( - 33D550EF23E1AD6D00C3B724 /* ClockView.swift */, - 33D550F123E1AD8400C3B724 /* ClockView.xib */, - ); - path = ClockView; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 33D550D323E1A98900C3B724 /* Lesson11 */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33D550E823E1A99000C3B724 /* Build configuration list for PBXNativeTarget "Lesson11" */; - buildPhases = ( - 33D550D023E1A98900C3B724 /* Sources */, - 33D550D123E1A98900C3B724 /* Frameworks */, - 33D550D223E1A98900C3B724 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Lesson11; - productName = Lesson11; - productReference = 33D550D423E1A98900C3B724 /* Lesson11.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33D550CC23E1A98900C3B724 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1110; - LastUpgradeCheck = 1110; - ORGANIZATIONNAME = "Михаил Беленко"; - TargetAttributes = { - 33D550D323E1A98900C3B724 = { - CreatedOnToolsVersion = 11.1; - }; - }; - }; - buildConfigurationList = 33D550CF23E1A98900C3B724 /* Build configuration list for PBXProject "Lesson11" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33D550CB23E1A98900C3B724; - productRefGroup = 33D550D523E1A98900C3B724 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33D550D323E1A98900C3B724 /* Lesson11 */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 33D550D223E1A98900C3B724 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33D550E423E1A99000C3B724 /* LaunchScreen.storyboard in Resources */, - 33D550F223E1AD8400C3B724 /* ClockView.xib in Resources */, - 33D550E123E1A99000C3B724 /* Assets.xcassets in Resources */, - 33D550DF23E1A98900C3B724 /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 33D550D023E1A98900C3B724 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33D550ED23E1A9C500C3B724 /* CustomButton.swift in Sources */, - 33D550F023E1AD6D00C3B724 /* ClockView.swift in Sources */, - 33D550DC23E1A98900C3B724 /* ViewController.swift in Sources */, - 33D550D823E1A98900C3B724 /* AppDelegate.swift in Sources */, - 33ACCD9E23E2C995006D9067 /* CustomSegmentControl.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 33D550DD23E1A98900C3B724 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 33D550DE23E1A98900C3B724 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 33D550E223E1A99000C3B724 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 33D550E323E1A99000C3B724 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 33D550E623E1A99000C3B724 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33D550E723E1A99000C3B724 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.1; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 33D550E923E1A99000C3B724 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson11/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson11; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 33D550EA23E1A99000C3B724 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson11/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson11; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 33D550CF23E1A98900C3B724 /* Build configuration list for PBXProject "Lesson11" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33D550E623E1A99000C3B724 /* Debug */, - 33D550E723E1A99000C3B724 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33D550E823E1A99000C3B724 /* Build configuration list for PBXNativeTarget "Lesson11" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33D550E923E1A99000C3B724 /* Debug */, - 33D550EA23E1A99000C3B724 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 33D550CC23E1A98900C3B724 /* Project object */; -} diff --git a/Lesson11/Lesson11.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson11/Lesson11.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson11/Lesson11.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson11/Lesson11/AppDelegate.swift b/Lesson11/Lesson11/AppDelegate.swift deleted file mode 100644 index eee7b5e..0000000 --- a/Lesson11/Lesson11/AppDelegate.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// AppDelegate.swift -// Lesson11 -// -// Created by Михаил Беленко on 29.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { - - var window: UIWindow? - - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - - return true - } -} - diff --git a/Lesson11/Lesson11/Assets.xcassets/Contents.json b/Lesson11/Lesson11/Assets.xcassets/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson11/Lesson11/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson11/Lesson11/Base.lproj/LaunchScreen.storyboard b/Lesson11/Lesson11/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 865e932..0000000 --- a/Lesson11/Lesson11/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson11/Lesson11/Base.lproj/Main.storyboard b/Lesson11/Lesson11/Base.lproj/Main.storyboard deleted file mode 100644 index ca33883..0000000 --- a/Lesson11/Lesson11/Base.lproj/Main.storyboard +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson11/Lesson11/CustomView/ClockView/ClockView.swift b/Lesson11/Lesson11/CustomView/ClockView/ClockView.swift deleted file mode 100644 index 79a5ab9..0000000 --- a/Lesson11/Lesson11/CustomView/ClockView/ClockView.swift +++ /dev/null @@ -1,150 +0,0 @@ -// -// ClockView.swift -// Lesson11 -// -// Created by Михаил Беленко on 29.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -@IBDesignable -class ClockView: UIView { - - private var isSetuped = false - - @IBInspectable var clockBackgroundColor: UIColor = .gray { - didSet { - backgroundColor = clockBackgroundColor - } - } - - var markerSize: CGFloat = 4 - var markerLength: CGFloat = 12 - var markerColor: UIColor = .blue - - @IBInspectable var hourLineSize: CGFloat = 8 { - didSet { - hourLine.frame = CGRect(origin: hourLine.frame.origin, size: CGSize(width: hourLineSize, height: hourLine.frame.size.height)) - } - } - @IBInspectable var hourLineColor: UIColor = .yellow { - didSet { - hourLine.backgroundColor = hourLineColor - } - } - - @IBInspectable var minuteLineSize: CGFloat = 7 { - didSet { - minuteLine.frame = CGRect(origin: minuteLine.frame.origin, size: CGSize(width: minuteLineSize, height: minuteLine.frame.size.height)) - } - } - @IBInspectable var minuteLineColor: UIColor = .red { - didSet { - minuteLine.backgroundColor = minuteLineColor - } - } - - @IBInspectable var secondLineSize: CGFloat = 6 { - didSet { - secondLine.frame = CGRect(origin: secondLine.frame.origin, size: CGSize(width: secondLineSize, height: secondLine.frame.size.height)) - } - } - @IBInspectable var secondLineColor: UIColor = .green { - didSet { - secondLine.backgroundColor = secondLineColor - } - } - - @IBInspectable var hours: CGFloat = 3 { - didSet { - updateHours() - } - } - @IBInspectable var minutes: CGFloat = 45 { - didSet { - updateMinutes() - } - } - @IBInspectable var seconds: CGFloat = 30 { - didSet { - updateSeconds() - } - } - - private let topMarker = UIView() - private let leftMarker = UIView() - private let rightMarker = UIView() - private let bottomMarker = UIView() - - private let hourLine = UIView() - private let minuteLine = UIView() - private let secondLine = UIView() - - override func layoutSubviews() { - super.layoutSubviews() - - backgroundColor = clockBackgroundColor - - let width = frame.size.width - let height = frame.size.height - - hourLine.layer.anchorPoint = CGPoint(x: 0.5, y: 1) - minuteLine.layer.anchorPoint = CGPoint(x: 0.5, y: 1) - secondLine.layer.anchorPoint = CGPoint(x: 0.5, y: 1) - - hourLine.frame = CGRect(x: width / 2 - hourLineSize / 2, y: height / 2 - height / 6, width: hourLineSize, height: height / 6) - minuteLine.frame = CGRect(x: width / 2 - minuteLineSize / 2, y: height / 2 - height / 4, width: minuteLineSize, height: height / 4) - secondLine.frame = CGRect(x: width / 2 - secondLineSize / 2, y: height / 2 - height / 3, width: secondLineSize, height: height / 3) - updateTime() - - topMarker.frame = CGRect(x: width / 2 - markerSize / 2, y: 0, width: markerSize, height: markerLength) - leftMarker.frame = CGRect(x: 0, y: height / 2 - markerSize / 2, width: markerLength, height: markerSize) - rightMarker.frame = CGRect(x: width - markerLength, y: height / 2 - markerSize / 2, width: markerLength, height: markerSize) - bottomMarker.frame = CGRect(x: width / 2 - markerSize / 2, y: height - markerLength, width: markerSize, height: markerLength) - - for v in [topMarker, leftMarker, rightMarker, bottomMarker] { - v.backgroundColor = markerColor - } - - hourLine.backgroundColor = hourLineColor - minuteLine.backgroundColor = minuteLineColor - secondLine.backgroundColor = secondLineColor - - layer.cornerRadius = width / 2 - - if isSetuped { return } - isSetuped = false - - for v in [topMarker, leftMarker, rightMarker, bottomMarker, secondLine, minuteLine, hourLine] { - addSubview(v) - } - } - - private func updateTime() { - updateHours() - updateMinutes() - updateSeconds() - } - - private func updateHours() { - let angle = CGFloat.pi * 2 * (hours / CGFloat(12)) - hourLine.transform = CGAffineTransform(rotationAngle: angle) - } - - private func updateMinutes() { - let angle = CGFloat.pi * 2 * (minutes / CGFloat(60)) - minuteLine.transform = CGAffineTransform(rotationAngle: angle) - } - - private func updateSeconds() { - let angle = CGFloat.pi * 2 * (seconds / CGFloat(60)) - secondLine.transform = CGAffineTransform(rotationAngle: angle) - } - - static func loadFromNIB() -> ClockView { - let nib = UINib(nibName: "ClockView", bundle: nil) - return nib.instantiate(withOwner: self, options: nil).first as! ClockView - } - -} diff --git a/Lesson11/Lesson11/CustomView/ClockView/ClockView.xib b/Lesson11/Lesson11/CustomView/ClockView/ClockView.xib deleted file mode 100644 index f9a8daa..0000000 --- a/Lesson11/Lesson11/CustomView/ClockView/ClockView.xib +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson11/Lesson11/CustomView/CustomButton.swift b/Lesson11/Lesson11/CustomView/CustomButton.swift deleted file mode 100644 index 8435c80..0000000 --- a/Lesson11/Lesson11/CustomView/CustomButton.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// CustomButton.swift -// Lesson11 -// -// Created by Михаил Беленко on 29.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -@IBDesignable -class CustomButton: UIButton { - - @IBInspectable var cornerRadius: CGFloat = 10.0 { - didSet { - layer.cornerRadius = cornerRadius - } - } - - @IBInspectable var borderWidth: CGFloat = 2 { - didSet { - layer.borderWidth = borderWidth - } - } - - @IBInspectable var borderColor: UIColor = .black { - didSet { - layer.borderColor = borderColor.cgColor - } - } - - @IBInspectable var width: CGFloat = 100 { - didSet { - frame = CGRect(origin: frame.origin, size: CGSize(width: width, height: frame.height)) - } - } -} diff --git a/Lesson11/Lesson11/CustomView/CustomSegmentControl.swift b/Lesson11/Lesson11/CustomView/CustomSegmentControl.swift deleted file mode 100644 index 3fb98ae..0000000 --- a/Lesson11/Lesson11/CustomView/CustomSegmentControl.swift +++ /dev/null @@ -1,82 +0,0 @@ -// -// CustomSegmentControl.swift -// Lesson11 -// -// Created by Михаил Беленко on 30.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -protocol CustomSegmentControlDelegate { - - func getSelectedItem() -> UIView -} - -@IBDesignable -class CustomSegmentControl: UISegmentedControl, CustomSegmentControlDelegate { - - private var isSetuped = false - - @IBInspectable var firstSegmentText: String? { - didSet { - setTitle(firstSegmentText, forSegmentAt: 0) - } - } - - @IBInspectable var secondSegmentText: String? { - didSet { - setTitle(secondSegmentText, forSegmentAt: 1) - } - } - - @IBInspectable var firstSegmentBackgroundColor: UIColor? - - @IBInspectable var secondSegmentBackgroundColor: UIColor? - - @IBInspectable var borderColor: UIColor? { - didSet { - layer.borderColor = borderColor?.cgColor - } - } - - @IBInspectable var borderWidth: CGFloat = 0 { - didSet { - layer.borderWidth = borderWidth - } - } - - override func layoutSubviews() { - super.layoutSubviews() - - if isSetuped { return } - isSetuped = true - - changeSelectedItem(sender: self) - addTarget(self, action: #selector(changeSelectedItem), for: .valueChanged) - } - - @objc - private func changeSelectedItem(sender: UISegmentedControl) - { - if #available(iOS 13.0, *) { - switch selectedSegmentIndex { - case 0: - selectedSegmentTintColor = firstSegmentBackgroundColor - case 1: - selectedSegmentTintColor = secondSegmentBackgroundColor - default: - fatalError("Not first or second item") - } - } - else { - let color = selectedSegmentIndex == 0 ? firstSegmentBackgroundColor : secondSegmentBackgroundColor - let subViewOfSegment: UIView = subviews[selectedSegmentIndex] as UIView - subViewOfSegment.tintColor = color - } - } - - func getSelectedItem() -> UIView { - return subviews[selectedSegmentIndex] as UIView - } -} diff --git a/Lesson11/Lesson11/Info.plist b/Lesson11/Lesson11/Info.plist deleted file mode 100644 index af8868b..0000000 --- a/Lesson11/Lesson11/Info.plist +++ /dev/null @@ -1,45 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Lesson11/Lesson11/ViewController.swift b/Lesson11/Lesson11/ViewController.swift deleted file mode 100644 index 9744612..0000000 --- a/Lesson11/Lesson11/ViewController.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// ViewController.swift -// Lesson11 -// -// Created by Михаил Беленко on 29.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class ViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - // Do any additional setup after loading the view. - } - - -} - diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2001.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2001.png" deleted file mode 100644 index ad65ca9..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2001.png" and /dev/null differ diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2002.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2002.png" deleted file mode 100644 index d72d996..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2002.png" and /dev/null differ diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2003.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2003.png" deleted file mode 100644 index 2d54fae..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2003.png" and /dev/null differ diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2004.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2004.png" deleted file mode 100644 index e8d5ec9..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2004.png" and /dev/null differ diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2005.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2005.png" deleted file mode 100644 index ddbb0de..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2005.png" and /dev/null differ diff --git "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2006.png" "b/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2006.png" deleted file mode 100644 index 47e7d26..0000000 Binary files "a/Lesson11/\320\237\321\200\320\270\320\274\320\265\321\200\321\213 \320\276\321\210\320\270\320\261\320\276\320\272 2 \320\273\320\260\320\261\320\276\321\200\320\260\321\202\320\276\321\200\320\275\320\276\320\271/\320\237\321\200\320\270\320\274\320\265\321\2006.png" and /dev/null differ diff --git a/Lesson12/Cartfile b/Lesson12/Cartfile deleted file mode 100644 index 1503d6d..0000000 --- a/Lesson12/Cartfile +++ /dev/null @@ -1 +0,0 @@ -github "Alamofire/Alamofire" "5.0.0-rc.3" diff --git a/Lesson12/Cartfile.resolved b/Lesson12/Cartfile.resolved deleted file mode 100644 index 1503d6d..0000000 --- a/Lesson12/Cartfile.resolved +++ /dev/null @@ -1 +0,0 @@ -github "Alamofire/Alamofire" "5.0.0-rc.3" diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.github/ISSUE_TEMPLATE.md b/Lesson12/Carthage/Checkouts/Alamofire/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index e7576da..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,33 +0,0 @@ -> ℹ Please fill out this template when filing an issue. -> All lines beginning with an ℹ symbol instruct you with what info we expect. You can delete those lines once you've filled in the info. -> -> Per our [*CONTRIBUTING guidelines](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md), we use GitHub for -> bugs and feature requests, not general support. Other issues should be opened on Stack Overflow with the tag `alamofire`. -> -> Please remove this line and everything above it before submitting. - -* [ ] I've read, understood, and done my best to follow the [*CONTRIBUTING guidelines](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). - -## What did you do? - -ℹ Please replace this with what you did. - -## What did you expect to happen? - -ℹ Please replace this with what you expected to happen. - -## What happened instead? - -ℹ Please replace this with of what happened instead. - -## Alamofire Environment - -**Alamofire version:** -**Xcode version:** -**Swift version:** -**Platform(s) running Alamofire:** -**macOS version running Xcode:** - -## Demo Project - -ℹ Please link to or upload a project we can download that reproduces the issue. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.github/PULL_REQUEST_TEMPLATE.md b/Lesson12/Carthage/Checkouts/Alamofire/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 6e04c37..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,13 +0,0 @@ -### Issue Link :link: - - -### Goals :soccer: - - - -### Implementation Details :construction: - - - -### Testing Details :mag: - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.github/workflows/ci.yml b/Lesson12/Carthage/Checkouts/Alamofire/.github/workflows/ci.yml deleted file mode 100644 index 090db26..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.github/workflows/ci.yml +++ /dev/null @@ -1,67 +0,0 @@ -name: "Alamofire CI" - -on: - push: - branches: - - master - - hotfix - pull_request: - branches: - - master - - hotfix - -jobs: - macOS: - name: Test macOS - runs-on: macOS-latest - env: - DEVELOPER_DIR: /Applications/Xcode_11.1.app/Contents/Developer - steps: - - uses: actions/checkout@v1 - - name: macOS - run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project "Alamofire.xcodeproj" -scheme "Alamofire macOS" -destination "platform=macOS" clean test | xcpretty - iOS: - name: Test iOS - runs-on: macOS-latest - env: - DEVELOPER_DIR: /Applications/Xcode_11.1.app/Contents/Developer - strategy: - matrix: - destination: ["OS=13.1,name=iPhone 11 Pro"] #, "OS=12.4,name=iPhone XS", "OS=11.4,name=iPhone X", "OS=10.3.1,name=iPhone SE"] - steps: - - uses: actions/checkout@v1 - - name: iOS - ${{ matrix.destination }} - run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project "Alamofire.xcodeproj" -scheme "Alamofire iOS" -destination "${{ matrix.destination }}" clean test | xcpretty - tvOS: - name: Test tvOS - runs-on: macOS-latest - env: - DEVELOPER_DIR: /Applications/Xcode_11.1.app/Contents/Developer - strategy: - matrix: - destination: ["OS=13.0,name=Apple TV 4K"] #, "OS=11.4,name=Apple TV 4K", "OS=10.2,name=Apple TV 1080p"] - steps: - - uses: actions/checkout@v1 - - name: tvOS - ${{ matrix.destination }} - run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project "Alamofire.xcodeproj" -scheme "Alamofire tvOS" -destination "${{ matrix.destination }}" clean test | xcpretty - watchOS: - name: Build watchOS - runs-on: macOS-latest - env: - DEVELOPER_DIR: /Applications/Xcode_11.1.app/Contents/Developer - strategy: - matrix: - destination: ["OS=6.0,name=Apple Watch Series 5 - 44mm"] #, "OS=4.2,name=Apple Watch Series 3 - 42mm", "OS=3.2,name=Apple Watch Series 2 - 42mm"] - steps: - - uses: actions/checkout@v1 - - name: watchOS - ${{ matrix.destination }} - run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project "Alamofire.xcodeproj" -scheme "Alamofire watchOS" -destination "${{ matrix.destination }}" clean build | xcpretty - spm: - name: Test SPM Integration - runs-on: macOS-latest - needs: [macOS] - steps: - - uses: actions/checkout@v1 - - name: SPM Build - run: swift build - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.gitignore b/Lesson12/Carthage/Checkouts/Alamofire/.gitignore deleted file mode 100644 index 222e8ec..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# Mac OS X -.DS_Store - -# Xcode - -## Build generated -build/ -DerivedData - -## Various settings -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint - -## Obj-C/Swift specific -*.hmap -*.ipa - -## Playgrounds -timeline.xctimeline -playground.xcworkspace - -# Swift Package Manager -.build/ - -# Carthage -Carthage/Build diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.jazzy.yaml b/Lesson12/Carthage/Checkouts/Alamofire/.jazzy.yaml deleted file mode 100644 index 1fa4beb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.jazzy.yaml +++ /dev/null @@ -1,8 +0,0 @@ -author: Alamofire Software Foundation -author_url: http://alamofire.org/ -github_url: https://github.com/Alamofire/Alamofire -root_url: https://alamofire.github.io/Alamofire/ -module: Alamofire -output: docs -theme: fullwidth -xcodebuild_arguments: [-workspace, 'Alamofire.xcworkspace', -scheme, 'Alamofire iOS'] diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.ruby-gemset b/Lesson12/Carthage/Checkouts/Alamofire/.ruby-gemset deleted file mode 100644 index bbc11e1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.ruby-gemset +++ /dev/null @@ -1 +0,0 @@ -Alamofire diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.ruby-version b/Lesson12/Carthage/Checkouts/Alamofire/.ruby-version deleted file mode 100644 index ec1cf33..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -2.6.3 diff --git a/Lesson12/Carthage/Checkouts/Alamofire/.swiftformat b/Lesson12/Carthage/Checkouts/Alamofire/.swiftformat deleted file mode 100644 index 79290cf..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/.swiftformat +++ /dev/null @@ -1,25 +0,0 @@ -# file options - ---symlinks ignore ---swiftversion 5 - -# rules ---disable andOperator - -# format options - ---closingparen same-line ---commas inline ---comments indent ---decimalgrouping 3,5 ---exponentcase lowercase ---exponentgrouping disabled ---fractiongrouping disabled ---ifdef outdent ---importgrouping testable-top ---operatorfunc no-space ---ranges no-space ---selfrequired validate ---stripunusedargs closure-only ---wraparguments after-first ---wrapcollections after-first \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.podspec b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.podspec deleted file mode 100644 index e06cf1b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.podspec +++ /dev/null @@ -1,21 +0,0 @@ -Pod::Spec.new do |s| - s.name = 'Alamofire' - s.version = '5.0.0-rc.3' - s.license = 'MIT' - s.summary = 'Elegant HTTP Networking in Swift' - s.homepage = 'https://github.com/Alamofire/Alamofire' - s.authors = { 'Alamofire Software Foundation' => 'info@alamofire.org' } - s.source = { :git => 'https://github.com/Alamofire/Alamofire.git', :tag => s.version } - s.documentation_url = 'https://alamofire.github.io/Alamofire/' - - s.ios.deployment_target = '10.0' - s.osx.deployment_target = '10.12' - s.tvos.deployment_target = '10.0' - s.watchos.deployment_target = '3.0' - - s.swift_versions = ['5.0', '5.1'] - - s.source_files = 'Source/*.swift' - - s.frameworks = 'CFNetwork' -end diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.pbxproj b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.pbxproj deleted file mode 100644 index c31d86c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.pbxproj +++ /dev/null @@ -1,2003 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 3107EA3520A11AE100445260 /* AuthenticationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */; }; - 3107EA3620A11AE100445260 /* AuthenticationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */; }; - 3107EA3720A11AE200445260 /* AuthenticationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */; }; - 3107EA3820A11F9600445260 /* ResponseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */; }; - 3107EA3920A11F9600445260 /* ResponseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */; }; - 3107EA3A20A11F9700445260 /* ResponseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */; }; - 3107EA3F20A1267C00445260 /* SessionDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C9DCE771CB1BCE2003E6463 /* SessionDelegateTests.swift */; }; - 3107EA4020A1267C00445260 /* SessionDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C9DCE771CB1BCE2003E6463 /* SessionDelegateTests.swift */; }; - 3107EA4120A1267D00445260 /* SessionDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C9DCE771CB1BCE2003E6463 /* SessionDelegateTests.swift */; }; - 3111CE8420A7636E008315E2 /* SessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D1C6F419D52968002E74FE /* SessionTests.swift */; }; - 3111CE8520A7636F008315E2 /* SessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D1C6F419D52968002E74FE /* SessionTests.swift */; }; - 3111CE8620A76370008315E2 /* SessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D1C6F419D52968002E74FE /* SessionTests.swift */; }; - 3111CE8820A77843008315E2 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3111CE8720A77843008315E2 /* EventMonitor.swift */; }; - 3111CE8920A77944008315E2 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3111CE8720A77843008315E2 /* EventMonitor.swift */; }; - 3111CE8A20A77945008315E2 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3111CE8720A77843008315E2 /* EventMonitor.swift */; }; - 3111CE8B20A77945008315E2 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3111CE8720A77843008315E2 /* EventMonitor.swift */; }; - 3111CE8C20A7EBE6008315E2 /* MultipartFormDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */; }; - 3111CE8D20A7EBE7008315E2 /* MultipartFormDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */; }; - 3111CE8E20A7EBE7008315E2 /* MultipartFormDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */; }; - 3111CE8F20A7EC26008315E2 /* NetworkReachabilityManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00571C66A8B900D1F709 /* NetworkReachabilityManagerTests.swift */; }; - 3111CE9020A7EC27008315E2 /* NetworkReachabilityManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00571C66A8B900D1F709 /* NetworkReachabilityManagerTests.swift */; }; - 3111CE9120A7EC27008315E2 /* NetworkReachabilityManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00571C66A8B900D1F709 /* NetworkReachabilityManagerTests.swift */; }; - 3111CE9220A7EC30008315E2 /* ResponseSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */; }; - 3111CE9320A7EC31008315E2 /* ResponseSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */; }; - 3111CE9420A7EC32008315E2 /* ResponseSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */; }; - 3111CE9520A7EC39008315E2 /* ServerTrustEvaluatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C33A1421B52089C00873DFF /* ServerTrustEvaluatorTests.swift */; }; - 3111CE9620A7EC3A008315E2 /* ServerTrustEvaluatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C33A1421B52089C00873DFF /* ServerTrustEvaluatorTests.swift */; }; - 3111CE9720A7EC3A008315E2 /* ServerTrustEvaluatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C33A1421B52089C00873DFF /* ServerTrustEvaluatorTests.swift */; }; - 3111CE9B20A7EC57008315E2 /* URLProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CCFA7991B2BE71600B6F460 /* URLProtocolTests.swift */; }; - 3111CE9C20A7EC58008315E2 /* URLProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CCFA7991B2BE71600B6F460 /* URLProtocolTests.swift */; }; - 3111CE9D20A7EC58008315E2 /* URLProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CCFA7991B2BE71600B6F460 /* URLProtocolTests.swift */; }; - 3113D46B21878227001CCD21 /* HTTPHeadersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3113D46A21878227001CCD21 /* HTTPHeadersTests.swift */; }; - 3113D46C21878227001CCD21 /* HTTPHeadersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3113D46A21878227001CCD21 /* HTTPHeadersTests.swift */; }; - 3113D46D21878227001CCD21 /* HTTPHeadersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3113D46A21878227001CCD21 /* HTTPHeadersTests.swift */; }; - 311A89BF23185BBF003BB714 /* CachedResponseHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFD6B132201338E00FFB5E3 /* CachedResponseHandlerTests.swift */; }; - 311A89C023185BBF003BB714 /* CachedResponseHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFD6B132201338E00FFB5E3 /* CachedResponseHandlerTests.swift */; }; - 311A89C123185BC0003BB714 /* CachedResponseHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFD6B132201338E00FFB5E3 /* CachedResponseHandlerTests.swift */; }; - 311B199020B0D3B40036823B /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 311B198F20B0D3B40036823B /* MultipartUpload.swift */; }; - 311B199120B0E3470036823B /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 311B198F20B0D3B40036823B /* MultipartUpload.swift */; }; - 311B199220B0E3480036823B /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 311B198F20B0D3B40036823B /* MultipartUpload.swift */; }; - 311B199320B0E3480036823B /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 311B198F20B0D3B40036823B /* MultipartUpload.swift */; }; - 311B199420B0ED980036823B /* UploadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5F19A9674D0040E7D1 /* UploadTests.swift */; }; - 311B199520B0ED980036823B /* UploadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5F19A9674D0040E7D1 /* UploadTests.swift */; }; - 311B199620B0ED990036823B /* UploadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5F19A9674D0040E7D1 /* UploadTests.swift */; }; - 31501E882196962A005829F2 /* ParameterEncoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31501E872196962A005829F2 /* ParameterEncoderTests.swift */; }; - 31501E892196962A005829F2 /* ParameterEncoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31501E872196962A005829F2 /* ParameterEncoderTests.swift */; }; - 31501E8A2196962A005829F2 /* ParameterEncoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31501E872196962A005829F2 /* ParameterEncoderTests.swift */; }; - 31727418218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; }; - 31727419218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; }; - 3172741A218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; }; - 3172741B218BAEC90039FFCC /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727417218BAEC90039FFCC /* HTTPMethod.swift */; }; - 3172741D218BB1790039FFCC /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3172741C218BB1790039FFCC /* ParameterEncoder.swift */; }; - 3172741E218BB1790039FFCC /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3172741C218BB1790039FFCC /* ParameterEncoder.swift */; }; - 3172741F218BB1790039FFCC /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3172741C218BB1790039FFCC /* ParameterEncoder.swift */; }; - 31727420218BB1790039FFCC /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3172741C218BB1790039FFCC /* ParameterEncoder.swift */; }; - 31727422218BB9A50039FFCC /* HTTPBin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727421218BB9A50039FFCC /* HTTPBin.swift */; }; - 31727423218BB9A50039FFCC /* HTTPBin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727421218BB9A50039FFCC /* HTTPBin.swift */; }; - 31727424218BB9A50039FFCC /* HTTPBin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31727421218BB9A50039FFCC /* HTTPBin.swift */; }; - 317A6A7620B2207F00A9FEC5 /* DownloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */; }; - 317A6A7720B2208000A9FEC5 /* DownloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */; }; - 317A6A7820B2208000A9FEC5 /* DownloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */; }; - 3191B5751F5F53A6003960A8 /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3191B5741F5F53A6003960A8 /* Protector.swift */; }; - 3191B5761F5F53A6003960A8 /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3191B5741F5F53A6003960A8 /* Protector.swift */; }; - 3191B5771F5F53A6003960A8 /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3191B5741F5F53A6003960A8 /* Protector.swift */; }; - 3191B5781F5F53A6003960A8 /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3191B5741F5F53A6003960A8 /* Protector.swift */; }; - 31991794209CDA7F00103A19 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991790209CDA7F00103A19 /* Request.swift */; }; - 31991795209CDA7F00103A19 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991790209CDA7F00103A19 /* Request.swift */; }; - 31991796209CDA7F00103A19 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991790209CDA7F00103A19 /* Request.swift */; }; - 31991797209CDA7F00103A19 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991790209CDA7F00103A19 /* Request.swift */; }; - 31991798209CDA7F00103A19 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991791209CDA7F00103A19 /* Response.swift */; }; - 31991799209CDA7F00103A19 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991791209CDA7F00103A19 /* Response.swift */; }; - 3199179A209CDA7F00103A19 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991791209CDA7F00103A19 /* Response.swift */; }; - 3199179B209CDA7F00103A19 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991791209CDA7F00103A19 /* Response.swift */; }; - 3199179C209CDA7F00103A19 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991792209CDA7F00103A19 /* Session.swift */; }; - 3199179D209CDA7F00103A19 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991792209CDA7F00103A19 /* Session.swift */; }; - 3199179E209CDA7F00103A19 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991792209CDA7F00103A19 /* Session.swift */; }; - 3199179F209CDA7F00103A19 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991792209CDA7F00103A19 /* Session.swift */; }; - 319917A0209CDA7F00103A19 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991793209CDA7F00103A19 /* SessionDelegate.swift */; }; - 319917A1209CDA7F00103A19 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991793209CDA7F00103A19 /* SessionDelegate.swift */; }; - 319917A2209CDA7F00103A19 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991793209CDA7F00103A19 /* SessionDelegate.swift */; }; - 319917A3209CDA7F00103A19 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31991793209CDA7F00103A19 /* SessionDelegate.swift */; }; - 319917A5209CDAC400103A19 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A4209CDAC400103A19 /* RequestTaskMap.swift */; }; - 319917A6209CDAC400103A19 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A4209CDAC400103A19 /* RequestTaskMap.swift */; }; - 319917A7209CDAC400103A19 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A4209CDAC400103A19 /* RequestTaskMap.swift */; }; - 319917A8209CDAC400103A19 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A4209CDAC400103A19 /* RequestTaskMap.swift */; }; - 319917AA209CDCB000103A19 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A9209CDCB000103A19 /* HTTPHeaders.swift */; }; - 319917AB209CDCB000103A19 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A9209CDCB000103A19 /* HTTPHeaders.swift */; }; - 319917AC209CDCB000103A19 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A9209CDCB000103A19 /* HTTPHeaders.swift */; }; - 319917AD209CDCB000103A19 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917A9209CDCB000103A19 /* HTTPHeaders.swift */; }; - 319917B9209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */; }; - 319917BA209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */; }; - 319917BB209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */; }; - 319917BC209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */; }; - 31C2B0EA20B271040089BA7C /* CacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C341BB91B1A865A00C1B34D /* CacheTests.swift */; }; - 31C2B0EB20B271050089BA7C /* CacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C341BB91B1A865A00C1B34D /* CacheTests.swift */; }; - 31C2B0EC20B271060089BA7C /* CacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C341BB91B1A865A00C1B34D /* CacheTests.swift */; }; - 31C2B0F020B271370089BA7C /* TLSEvaluationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */; }; - 31C2B0F120B271370089BA7C /* TLSEvaluationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */; }; - 31C2B0F220B271380089BA7C /* TLSEvaluationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */; }; - 31D83FCE20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */; }; - 31D83FCF20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */; }; - 31D83FD020D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */; }; - 31D83FD120D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */; }; - 31DADDFB224811ED0051390F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31DADDFA224811ED0051390F /* AlamofireExtended.swift */; }; - 31DADDFC224811ED0051390F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31DADDFA224811ED0051390F /* AlamofireExtended.swift */; }; - 31DADDFD224811ED0051390F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31DADDFA224811ED0051390F /* AlamofireExtended.swift */; }; - 31DADDFE224811ED0051390F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31DADDFA224811ED0051390F /* AlamofireExtended.swift */; }; - 31EBD9C120D1D89C00D1FF34 /* ValidationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */; }; - 31EBD9C220D1D89C00D1FF34 /* ValidationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */; }; - 31EBD9C320D1D89D00D1FF34 /* ValidationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */; }; - 31ED52E81D73891B00199085 /* AFError+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31ED52E61D73889D00199085 /* AFError+AlamofireTests.swift */; }; - 31ED52E91D73891C00199085 /* AFError+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31ED52E61D73889D00199085 /* AFError+AlamofireTests.swift */; }; - 31ED52EA1D73891C00199085 /* AFError+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31ED52E61D73889D00199085 /* AFError+AlamofireTests.swift */; }; - 31F5085D20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */; }; - 31F5085E20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */; }; - 31F5085F20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */; }; - 31F5086020B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */; }; - 31F9683C20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F9683B20BB70290009606F /* NSLoggingEventMonitor.swift */; }; - 31F9683D20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F9683B20BB70290009606F /* NSLoggingEventMonitor.swift */; }; - 31F9683E20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31F9683B20BB70290009606F /* NSLoggingEventMonitor.swift */; }; - 31FB2F8722C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */; }; - 31FB2F8822C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */; }; - 31FB2F8922C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */; }; - 31FB2F8A22C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */; }; - 4196936222FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */; }; - 4196936322FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */; }; - 4196936422FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */; }; - 4196936522FA1EAD001EA5D5 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */; }; - 4C0CB631220BC70300604EDC /* RequestInterceptorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB630220BC70300604EDC /* RequestInterceptorTests.swift */; }; - 4C0CB632220BC70300604EDC /* RequestInterceptorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB630220BC70300604EDC /* RequestInterceptorTests.swift */; }; - 4C0CB633220BC70300604EDC /* RequestInterceptorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB630220BC70300604EDC /* RequestInterceptorTests.swift */; }; - 4C0CB641220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */; }; - 4C0CB642220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */; }; - 4C0CB643220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */; }; - 4C0CB644220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */; }; - 4C0CB646220CA8A400604EDC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */; }; - 4C0CB647220CA8A400604EDC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */; }; - 4C0CB648220CA8A400604EDC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */; }; - 4C0CB649220CA8A400604EDC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */; }; - 4C0CB64B220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB64A220CA8D600604EDC /* RedirectHandlerTests.swift */; }; - 4C0CB64C220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB64A220CA8D600604EDC /* RedirectHandlerTests.swift */; }; - 4C0CB64D220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0CB64A220CA8D600604EDC /* RedirectHandlerTests.swift */; }; - 4C1DC8541B68908E00476DE3 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1DC8531B68908E00476DE3 /* AFError.swift */; }; - 4C1DC8551B68908E00476DE3 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1DC8531B68908E00476DE3 /* AFError.swift */; }; - 4C23EB431B327C5B0090E0BC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */; }; - 4C23EB441B327C5B0090E0BC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */; }; - 4C256A0621EEB69000AD5D87 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */; }; - 4C256A0721EEB69000AD5D87 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */; }; - 4C256A0821EEB69000AD5D87 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */; }; - 4C256A0921EEB69000AD5D87 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */; }; - 4C256A1A21F1449C00AD5D87 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */; }; - 4C256A1B21F1449C00AD5D87 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */; }; - 4C256A1C21F1449C00AD5D87 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */; }; - 4C256A1D21F1449C00AD5D87 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */; }; - 4C256A531B096C770065714F /* BaseTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A501B096C2C0065714F /* BaseTestCase.swift */; }; - 4C256A541B096C770065714F /* BaseTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A501B096C2C0065714F /* BaseTestCase.swift */; }; - 4C33A1391B5207DB00873DFF /* rainbow.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1231B5207DB00873DFF /* rainbow.jpg */; }; - 4C33A13A1B5207DB00873DFF /* rainbow.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1231B5207DB00873DFF /* rainbow.jpg */; }; - 4C33A13B1B5207DB00873DFF /* unicorn.png in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1241B5207DB00873DFF /* unicorn.png */; }; - 4C33A13C1B5207DB00873DFF /* unicorn.png in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1241B5207DB00873DFF /* unicorn.png */; }; - 4C3D00541C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */; }; - 4C3D00551C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */; }; - 4C3D00561C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */; }; - 4C43669B1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */; }; - 4C43669C1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */; }; - 4C43669D1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */; }; - 4C43669E1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */; }; - 4C4466EB21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */; }; - 4C4466EC21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */; }; - 4C4466ED21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */; }; - 4C4466EE21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */; }; - 4C743CF61C22772D00BCB23E /* certDER.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F831C1A72F8002DA1A9 /* certDER.cer */; }; - 4C743CF71C22772D00BCB23E /* certDER.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F841C1A72F8002DA1A9 /* certDER.crt */; }; - 4C743CF81C22772D00BCB23E /* certDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F851C1A72F8002DA1A9 /* certDER.der */; }; - 4C743CF91C22772D00BCB23E /* certPEM.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F861C1A72F8002DA1A9 /* certPEM.cer */; }; - 4C743CFA1C22772D00BCB23E /* certPEM.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F871C1A72F8002DA1A9 /* certPEM.crt */; }; - 4C743CFB1C22772D00BCB23E /* randomGibberish.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F891C1A72F8002DA1A9 /* randomGibberish.crt */; }; - 4C743CFC1C22772D00BCB23E /* keyDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F8A1C1A72F8002DA1A9 /* keyDER.der */; }; - 4C743CFD1C22772D00BCB23E /* alamofire-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3A1B535F220017E0BF /* alamofire-root-ca.cer */; }; - 4C743CFE1C22772D00BCB23E /* alamofire-signing-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3D1B535F2E0017E0BF /* alamofire-signing-ca1.cer */; }; - 4C743CFF1C22772D00BCB23E /* alamofire-signing-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3E1B535F2E0017E0BF /* alamofire-signing-ca2.cer */; }; - 4C743D001C22772D00BCB23E /* multiple-dns-names.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C441B535F400017E0BF /* multiple-dns-names.cer */; }; - 4C743D011C22772D00BCB23E /* signed-by-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C451B535F400017E0BF /* signed-by-ca1.cer */; }; - 4C743D021C22772D00BCB23E /* test.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C461B535F400017E0BF /* test.alamofire.org.cer */; }; - 4C743D031C22772D00BCB23E /* wildcard.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C431B535F400017E0BF /* wildcard.alamofire.org.cer */; }; - 4C743D041C22772D00BCB23E /* expired.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C4F1B535F540017E0BF /* expired.cer */; }; - 4C743D051C22772D00BCB23E /* missing-dns-name-and-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C501B535F540017E0BF /* missing-dns-name-and-uri.cer */; }; - 4C743D061C22772D00BCB23E /* signed-by-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C511B535F540017E0BF /* signed-by-ca2.cer */; }; - 4C743D071C22772D00BCB23E /* valid-dns-name.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C521B535F540017E0BF /* valid-dns-name.cer */; }; - 4C743D081C22772D00BCB23E /* valid-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C531B535F540017E0BF /* valid-uri.cer */; }; - 4C743D0C1C22772E00BCB23E /* certDER.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F831C1A72F8002DA1A9 /* certDER.cer */; }; - 4C743D0D1C22772E00BCB23E /* certDER.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F841C1A72F8002DA1A9 /* certDER.crt */; }; - 4C743D0E1C22772E00BCB23E /* certDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F851C1A72F8002DA1A9 /* certDER.der */; }; - 4C743D0F1C22772E00BCB23E /* certPEM.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F861C1A72F8002DA1A9 /* certPEM.cer */; }; - 4C743D101C22772E00BCB23E /* certPEM.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F871C1A72F8002DA1A9 /* certPEM.crt */; }; - 4C743D111C22772E00BCB23E /* randomGibberish.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F891C1A72F8002DA1A9 /* randomGibberish.crt */; }; - 4C743D121C22772E00BCB23E /* keyDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F8A1C1A72F8002DA1A9 /* keyDER.der */; }; - 4C743D131C22772E00BCB23E /* alamofire-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3A1B535F220017E0BF /* alamofire-root-ca.cer */; }; - 4C743D141C22772E00BCB23E /* alamofire-signing-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3D1B535F2E0017E0BF /* alamofire-signing-ca1.cer */; }; - 4C743D151C22772E00BCB23E /* alamofire-signing-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3E1B535F2E0017E0BF /* alamofire-signing-ca2.cer */; }; - 4C743D161C22772E00BCB23E /* multiple-dns-names.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C441B535F400017E0BF /* multiple-dns-names.cer */; }; - 4C743D171C22772E00BCB23E /* signed-by-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C451B535F400017E0BF /* signed-by-ca1.cer */; }; - 4C743D181C22772E00BCB23E /* test.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C461B535F400017E0BF /* test.alamofire.org.cer */; }; - 4C743D191C22772E00BCB23E /* wildcard.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C431B535F400017E0BF /* wildcard.alamofire.org.cer */; }; - 4C743D1A1C22772E00BCB23E /* expired.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C4F1B535F540017E0BF /* expired.cer */; }; - 4C743D1B1C22772E00BCB23E /* missing-dns-name-and-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C501B535F540017E0BF /* missing-dns-name-and-uri.cer */; }; - 4C743D1C1C22772E00BCB23E /* signed-by-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C511B535F540017E0BF /* signed-by-ca2.cer */; }; - 4C743D1D1C22772E00BCB23E /* valid-dns-name.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C521B535F540017E0BF /* valid-dns-name.cer */; }; - 4C743D1E1C22772E00BCB23E /* valid-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C531B535F540017E0BF /* valid-uri.cer */; }; - 4C743D221C22772F00BCB23E /* certDER.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F831C1A72F8002DA1A9 /* certDER.cer */; }; - 4C743D231C22772F00BCB23E /* certDER.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F841C1A72F8002DA1A9 /* certDER.crt */; }; - 4C743D241C22772F00BCB23E /* certDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F851C1A72F8002DA1A9 /* certDER.der */; }; - 4C743D251C22772F00BCB23E /* certPEM.cer in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F861C1A72F8002DA1A9 /* certPEM.cer */; }; - 4C743D261C22772F00BCB23E /* certPEM.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F871C1A72F8002DA1A9 /* certPEM.crt */; }; - 4C743D271C22772F00BCB23E /* randomGibberish.crt in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F891C1A72F8002DA1A9 /* randomGibberish.crt */; }; - 4C743D281C22772F00BCB23E /* keyDER.der in Resources */ = {isa = PBXBuildFile; fileRef = B39E2F8A1C1A72F8002DA1A9 /* keyDER.der */; }; - 4C743D291C22772F00BCB23E /* alamofire-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3A1B535F220017E0BF /* alamofire-root-ca.cer */; }; - 4C743D2A1C22772F00BCB23E /* alamofire-signing-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3D1B535F2E0017E0BF /* alamofire-signing-ca1.cer */; }; - 4C743D2B1C22772F00BCB23E /* alamofire-signing-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C3E1B535F2E0017E0BF /* alamofire-signing-ca2.cer */; }; - 4C743D2C1C22772F00BCB23E /* multiple-dns-names.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C441B535F400017E0BF /* multiple-dns-names.cer */; }; - 4C743D2D1C22772F00BCB23E /* signed-by-ca1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C451B535F400017E0BF /* signed-by-ca1.cer */; }; - 4C743D2E1C22772F00BCB23E /* test.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C461B535F400017E0BF /* test.alamofire.org.cer */; }; - 4C743D2F1C22772F00BCB23E /* wildcard.alamofire.org.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C431B535F400017E0BF /* wildcard.alamofire.org.cer */; }; - 4C743D301C22772F00BCB23E /* expired.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C4F1B535F540017E0BF /* expired.cer */; }; - 4C743D311C22772F00BCB23E /* missing-dns-name-and-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C501B535F540017E0BF /* missing-dns-name-and-uri.cer */; }; - 4C743D321C22772F00BCB23E /* signed-by-ca2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C511B535F540017E0BF /* signed-by-ca2.cer */; }; - 4C743D331C22772F00BCB23E /* valid-dns-name.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C521B535F540017E0BF /* valid-dns-name.cer */; }; - 4C743D341C22772F00BCB23E /* valid-uri.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4C812C531B535F540017E0BF /* valid-uri.cer */; }; - 4C7DD7EB224C627300249836 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C7DD7EA224C627300249836 /* Result+Alamofire.swift */; }; - 4C7DD7EC224C627300249836 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C7DD7EA224C627300249836 /* Result+Alamofire.swift */; }; - 4C7DD7ED224C627300249836 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C7DD7EA224C627300249836 /* Result+Alamofire.swift */; }; - 4C811F8D1B51856D00E0F59A /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */; }; - 4C811F8E1B51856D00E0F59A /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */; }; - 4CB928291C66BFBC00CE5F08 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CB928281C66BFBC00CE5F08 /* Notifications.swift */; }; - 4CB9282A1C66BFBC00CE5F08 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CB928281C66BFBC00CE5F08 /* Notifications.swift */; }; - 4CB9282B1C66BFBC00CE5F08 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CB928281C66BFBC00CE5F08 /* Notifications.swift */; }; - 4CB9282C1C66BFBC00CE5F08 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CB928281C66BFBC00CE5F08 /* Notifications.swift */; }; - 4CBD2180220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CBD217F220B48AE008F1C59 /* RetryPolicyTests.swift */; }; - 4CBD2181220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CBD217F220B48AE008F1C59 /* RetryPolicyTests.swift */; }; - 4CBD2182220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CBD217F220B48AE008F1C59 /* RetryPolicyTests.swift */; }; - 4CCB206C1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20681D4549E000C64D5B /* expired.badssl.com-leaf.cer */; }; - 4CCB206D1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20681D4549E000C64D5B /* expired.badssl.com-leaf.cer */; }; - 4CCB206E1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20681D4549E000C64D5B /* expired.badssl.com-leaf.cer */; }; - 4CCB206F1D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20691D4549E000C64D5B /* expired.badssl.com-root-ca.cer */; }; - 4CCB20701D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20691D4549E000C64D5B /* expired.badssl.com-root-ca.cer */; }; - 4CCB20711D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB20691D4549E000C64D5B /* expired.badssl.com-root-ca.cer */; }; - 4CCB20721D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206A1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer */; }; - 4CCB20731D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206A1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer */; }; - 4CCB20741D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206A1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer */; }; - 4CCB20751D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206B1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer */; }; - 4CCB20761D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206B1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer */; }; - 4CCB20771D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 4CCB206B1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer */; }; - 4CDE2C431AF89F0900BABAE5 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C421AF89F0900BABAE5 /* Validation.swift */; }; - 4CDE2C441AF89F0900BABAE5 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C421AF89F0900BABAE5 /* Validation.swift */; }; - 4CDE2C461AF89FF300BABAE5 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */; }; - 4CDE2C471AF89FF300BABAE5 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */; }; - 4CE2724F1AF88FB500F1D59A /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */; }; - 4CE272501AF88FB500F1D59A /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */; }; - 4CEC605A1B745C9100E684F4 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1DC8531B68908E00476DE3 /* AFError.swift */; }; - 4CEC605C1B745C9B00E684F4 /* Alamofire.h in Headers */ = {isa = PBXBuildFile; fileRef = F8111E3819A95C8B0040E7D1 /* Alamofire.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4CEE82AD1C6813CF00E9C9F0 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */; }; - 4CF626F91BA7CB3E0011A099 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4CF626EF1BA7CB3E0011A099 /* Alamofire.framework */; }; - 4CF627061BA7CBE30011A099 /* Alamofire.h in Headers */ = {isa = PBXBuildFile; fileRef = F8111E3819A95C8B0040E7D1 /* Alamofire.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4CF627071BA7CBF60011A099 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F897FF4019AA800700AB5182 /* Alamofire.swift */; }; - 4CF627081BA7CBF60011A099 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1DC8531B68908E00476DE3 /* AFError.swift */; }; - 4CF6270A1BA7CBF60011A099 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */; }; - 4CF6270E1BA7CBF60011A099 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */; }; - 4CF6270F1BA7CBF60011A099 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */; }; - 4CF627101BA7CBF60011A099 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */; }; - 4CF627131BA7CBF60011A099 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C421AF89F0900BABAE5 /* Validation.swift */; }; - 4CF627141BA7CC240011A099 /* BaseTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C256A501B096C2C0065714F /* BaseTestCase.swift */; }; - 4CF627171BA7CC240011A099 /* ParameterEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */; }; - 4CF627181BA7CC240011A099 /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5D19A9674D0040E7D1 /* RequestTests.swift */; }; - 4CF627341BA7CC300011A099 /* rainbow.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1231B5207DB00873DFF /* rainbow.jpg */; }; - 4CF627351BA7CC300011A099 /* unicorn.png in Resources */ = {isa = PBXBuildFile; fileRef = 4C33A1241B5207DB00873DFF /* unicorn.png */; }; - 4CFB02901D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFB028F1D7CF28F0056F249 /* FileManager+AlamofireTests.swift */; }; - 4CFB02911D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFB028F1D7CF28F0056F249 /* FileManager+AlamofireTests.swift */; }; - 4CFB02921D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CFB028F1D7CF28F0056F249 /* FileManager+AlamofireTests.swift */; }; - 4CFB02F51D7D2FA20056F249 /* empty_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EA1D7D2FA20056F249 /* empty_data.json */; }; - 4CFB02F61D7D2FA20056F249 /* empty_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EA1D7D2FA20056F249 /* empty_data.json */; }; - 4CFB02F71D7D2FA20056F249 /* empty_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EA1D7D2FA20056F249 /* empty_data.json */; }; - 4CFB02F81D7D2FA20056F249 /* invalid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EB1D7D2FA20056F249 /* invalid_data.json */; }; - 4CFB02F91D7D2FA20056F249 /* invalid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EB1D7D2FA20056F249 /* invalid_data.json */; }; - 4CFB02FA1D7D2FA20056F249 /* invalid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EB1D7D2FA20056F249 /* invalid_data.json */; }; - 4CFB02FB1D7D2FA20056F249 /* valid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EC1D7D2FA20056F249 /* valid_data.json */; }; - 4CFB02FC1D7D2FA20056F249 /* valid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EC1D7D2FA20056F249 /* valid_data.json */; }; - 4CFB02FD1D7D2FA20056F249 /* valid_data.json in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02EC1D7D2FA20056F249 /* valid_data.json */; }; - 4CFB03071D7D2FA20056F249 /* empty_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F21D7D2FA20056F249 /* empty_string.txt */; }; - 4CFB03081D7D2FA20056F249 /* empty_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F21D7D2FA20056F249 /* empty_string.txt */; }; - 4CFB03091D7D2FA20056F249 /* empty_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F21D7D2FA20056F249 /* empty_string.txt */; }; - 4CFB030A1D7D2FA20056F249 /* utf32_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F31D7D2FA20056F249 /* utf32_string.txt */; }; - 4CFB030B1D7D2FA20056F249 /* utf32_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F31D7D2FA20056F249 /* utf32_string.txt */; }; - 4CFB030C1D7D2FA20056F249 /* utf32_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F31D7D2FA20056F249 /* utf32_string.txt */; }; - 4CFB030D1D7D2FA20056F249 /* utf8_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F41D7D2FA20056F249 /* utf8_string.txt */; }; - 4CFB030E1D7D2FA20056F249 /* utf8_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F41D7D2FA20056F249 /* utf8_string.txt */; }; - 4CFB030F1D7D2FA20056F249 /* utf8_string.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB02F41D7D2FA20056F249 /* utf8_string.txt */; }; - 4DD67C241A5C58FB00ED2280 /* Alamofire.h in Headers */ = {isa = PBXBuildFile; fileRef = F8111E3819A95C8B0040E7D1 /* Alamofire.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4DD67C251A5C590000ED2280 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F897FF4019AA800700AB5182 /* Alamofire.swift */; }; - 8035DB621BAB492500466CB3 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8111E3319A95C8B0040E7D1 /* Alamofire.framework */; }; - E4202FD01B667AA100C997FB /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */; }; - E4202FD21B667AA100C997FB /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */; }; - E4202FD41B667AA100C997FB /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F897FF4019AA800700AB5182 /* Alamofire.swift */; }; - E4202FD51B667AA100C997FB /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */; }; - E4202FD61B667AA100C997FB /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */; }; - E4202FD81B667AA100C997FB /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CDE2C421AF89F0900BABAE5 /* Validation.swift */; }; - F8111E3919A95C8B0040E7D1 /* Alamofire.h in Headers */ = {isa = PBXBuildFile; fileRef = F8111E3819A95C8B0040E7D1 /* Alamofire.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F8111E6119A9674D0040E7D1 /* ParameterEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */; }; - F829C6B81A7A94F100A2CD59 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DD67C0B1A5C55C900ED2280 /* Alamofire.framework */; }; - F829C6BE1A7A950600A2CD59 /* ParameterEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */; }; - F829C6BF1A7A950600A2CD59 /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5D19A9674D0040E7D1 /* RequestTests.swift */; }; - F8858DDD19A96B4300F55F93 /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8111E5D19A9674D0040E7D1 /* RequestTests.swift */; }; - F897FF4119AA800700AB5182 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F897FF4019AA800700AB5182 /* Alamofire.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 4CF626FA1BA7CB3E0011A099 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = F8111E2A19A95C8B0040E7D1 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4CF626EE1BA7CB3E0011A099; - remoteInfo = "Alamofire tvOS"; - }; - F8111E6519A967880040E7D1 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = F8111E2A19A95C8B0040E7D1 /* Project object */; - proxyType = 1; - remoteGlobalIDString = F8111E3219A95C8B0040E7D1; - remoteInfo = Alamofire; - }; - F829C6B91A7A94F100A2CD59 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = F8111E2A19A95C8B0040E7D1 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4DD67C0A1A5C55C900ED2280; - remoteInfo = "Alamofire OSX"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 3111CE8720A77843008315E2 /* EventMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventMonitor.swift; sourceTree = ""; }; - 3113D46A21878227001CCD21 /* HTTPHeadersTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPHeadersTests.swift; sourceTree = ""; }; - 311B198F20B0D3B40036823B /* MultipartUpload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MultipartUpload.swift; sourceTree = ""; }; - 312D1E0B1FC2551400E51FF1 /* Usage.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = Usage.md; path = Documentation/Usage.md; sourceTree = ""; }; - 312D1E0C1FC2551400E51FF1 /* AdvancedUsage.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = AdvancedUsage.md; path = Documentation/AdvancedUsage.md; sourceTree = ""; }; - 31501E872196962A005829F2 /* ParameterEncoderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParameterEncoderTests.swift; sourceTree = ""; }; - 316250E41F00ABE900E207A6 /* ISSUE_TEMPLATE.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = ISSUE_TEMPLATE.md; path = .github/ISSUE_TEMPLATE.md; sourceTree = ""; }; - 316250E51F00ACD000E207A6 /* PULL_REQUEST_TEMPLATE.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = PULL_REQUEST_TEMPLATE.md; path = .github/PULL_REQUEST_TEMPLATE.md; sourceTree = ""; }; - 31727417218BAEC90039FFCC /* HTTPMethod.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPMethod.swift; sourceTree = ""; }; - 3172741C218BB1790039FFCC /* ParameterEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParameterEncoder.swift; sourceTree = ""; }; - 31727421218BB9A50039FFCC /* HTTPBin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPBin.swift; sourceTree = ""; }; - 3191B5741F5F53A6003960A8 /* Protector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Protector.swift; sourceTree = ""; }; - 31991790209CDA7F00103A19 /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; - 31991791209CDA7F00103A19 /* Response.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Response.swift; sourceTree = ""; }; - 31991792209CDA7F00103A19 /* Session.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; - 31991793209CDA7F00103A19 /* SessionDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionDelegate.swift; sourceTree = ""; }; - 319917A4209CDAC400103A19 /* RequestTaskMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTaskMap.swift; sourceTree = ""; }; - 319917A9209CDCB000103A19 /* HTTPHeaders.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPHeaders.swift; sourceTree = ""; }; - 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OperationQueue+Alamofire.swift"; sourceTree = ""; }; - 31B2CA9521AA25CD005B371A /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; - 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; - 31DADDFA224811ED0051390F /* AlamofireExtended.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlamofireExtended.swift; sourceTree = ""; }; - 31ED52E61D73889D00199085 /* AFError+AlamofireTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AFError+AlamofireTests.swift"; sourceTree = ""; }; - 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; - 31F9683B20BB70290009606F /* NSLoggingEventMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSLoggingEventMonitor.swift; sourceTree = ""; }; - 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLEncodedFormEncoder.swift; sourceTree = ""; }; - 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Result+Alamofire.swift"; sourceTree = ""; }; - 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseSerializationTests.swift; sourceTree = ""; }; - 4C0CB630220BC70300604EDC /* RequestInterceptorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestInterceptorTests.swift; sourceTree = ""; }; - 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "URLRequest+Alamofire.swift"; sourceTree = ""; }; - 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RedirectHandler.swift; sourceTree = ""; }; - 4C0CB64A220CA8D600604EDC /* RedirectHandlerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RedirectHandlerTests.swift; sourceTree = ""; }; - 4C1DC8531B68908E00476DE3 /* AFError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AFError.swift; sourceTree = ""; }; - 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MultipartFormData.swift; sourceTree = ""; }; - 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestInterceptor.swift; sourceTree = ""; }; - 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RetryPolicy.swift; sourceTree = ""; }; - 4C256A501B096C2C0065714F /* BaseTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseTestCase.swift; sourceTree = ""; }; - 4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MultipartFormDataTests.swift; sourceTree = ""; }; - 4C33A1231B5207DB00873DFF /* rainbow.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = rainbow.jpg; sourceTree = ""; }; - 4C33A1241B5207DB00873DFF /* unicorn.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = unicorn.png; sourceTree = ""; }; - 4C33A1421B52089C00873DFF /* ServerTrustEvaluatorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ServerTrustEvaluatorTests.swift; sourceTree = ""; }; - 4C341BB91B1A865A00C1B34D /* CacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CacheTests.swift; sourceTree = ""; }; - 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkReachabilityManager.swift; sourceTree = ""; }; - 4C3D00571C66A8B900D1F709 /* NetworkReachabilityManagerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkReachabilityManagerTests.swift; sourceTree = ""; }; - 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CachedResponseHandler.swift; sourceTree = ""; }; - 4C7DD7EA224C627300249836 /* Result+Alamofire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Result+Alamofire.swift"; sourceTree = ""; }; - 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ServerTrustEvaluation.swift; sourceTree = ""; }; - 4C812C3A1B535F220017E0BF /* alamofire-root-ca.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "alamofire-root-ca.cer"; path = "alamofire.org/alamofire-root-ca.cer"; sourceTree = ""; }; - 4C812C3D1B535F2E0017E0BF /* alamofire-signing-ca1.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "alamofire-signing-ca1.cer"; path = "alamofire.org/alamofire-signing-ca1.cer"; sourceTree = ""; }; - 4C812C3E1B535F2E0017E0BF /* alamofire-signing-ca2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "alamofire-signing-ca2.cer"; path = "alamofire.org/alamofire-signing-ca2.cer"; sourceTree = ""; }; - 4C812C431B535F400017E0BF /* wildcard.alamofire.org.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = wildcard.alamofire.org.cer; path = alamofire.org/wildcard.alamofire.org.cer; sourceTree = ""; }; - 4C812C441B535F400017E0BF /* multiple-dns-names.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "multiple-dns-names.cer"; path = "alamofire.org/multiple-dns-names.cer"; sourceTree = ""; }; - 4C812C451B535F400017E0BF /* signed-by-ca1.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "signed-by-ca1.cer"; path = "alamofire.org/signed-by-ca1.cer"; sourceTree = ""; }; - 4C812C461B535F400017E0BF /* test.alamofire.org.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = test.alamofire.org.cer; path = alamofire.org/test.alamofire.org.cer; sourceTree = ""; }; - 4C812C4F1B535F540017E0BF /* expired.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = expired.cer; path = alamofire.org/expired.cer; sourceTree = ""; }; - 4C812C501B535F540017E0BF /* missing-dns-name-and-uri.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "missing-dns-name-and-uri.cer"; path = "alamofire.org/missing-dns-name-and-uri.cer"; sourceTree = ""; }; - 4C812C511B535F540017E0BF /* signed-by-ca2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "signed-by-ca2.cer"; path = "alamofire.org/signed-by-ca2.cer"; sourceTree = ""; }; - 4C812C521B535F540017E0BF /* valid-dns-name.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "valid-dns-name.cer"; path = "alamofire.org/valid-dns-name.cer"; sourceTree = ""; }; - 4C812C531B535F540017E0BF /* valid-uri.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = "valid-uri.cer"; path = "alamofire.org/valid-uri.cer"; sourceTree = ""; }; - 4C9DCE771CB1BCE2003E6463 /* SessionDelegateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionDelegateTests.swift; sourceTree = ""; }; - 4C9E88371F5FB3B0000BEC61 /* Alamofire 2.0 Migration Guide.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = "Alamofire 2.0 Migration Guide.md"; path = "Documentation/Alamofire 2.0 Migration Guide.md"; sourceTree = ""; }; - 4C9E88381F5FB3B0000BEC61 /* Alamofire 3.0 Migration Guide.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = "Alamofire 3.0 Migration Guide.md"; path = "Documentation/Alamofire 3.0 Migration Guide.md"; sourceTree = ""; }; - 4C9E88391F5FB3B0000BEC61 /* Alamofire 4.0 Migration Guide.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = "Alamofire 4.0 Migration Guide.md"; path = "Documentation/Alamofire 4.0 Migration Guide.md"; sourceTree = ""; }; - 4CB928281C66BFBC00CE5F08 /* Notifications.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Notifications.swift; sourceTree = ""; }; - 4CBD217F220B48AE008F1C59 /* RetryPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RetryPolicyTests.swift; sourceTree = ""; }; - 4CCB20681D4549E000C64D5B /* expired.badssl.com-leaf.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "expired.badssl.com-leaf.cer"; sourceTree = ""; }; - 4CCB20691D4549E000C64D5B /* expired.badssl.com-root-ca.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "expired.badssl.com-root-ca.cer"; sourceTree = ""; }; - 4CCB206A1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "expired.badssl.com-intermediate-ca-1.cer"; sourceTree = ""; }; - 4CCB206B1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "expired.badssl.com-intermediate-ca-2.cer"; sourceTree = ""; }; - 4CCFA7991B2BE71600B6F460 /* URLProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLProtocolTests.swift; sourceTree = ""; }; - 4CDE2C421AF89F0900BABAE5 /* Validation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Validation.swift; sourceTree = ""; }; - 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseSerialization.swift; sourceTree = ""; }; - 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ParameterEncoding.swift; sourceTree = ""; }; - 4CE292311EF4A393008DA555 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; - 4CE292321EF4A393008DA555 /* CHANGELOG.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; - 4CE292331EF4A393008DA555 /* CONTRIBUTING.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = CONTRIBUTING.md; sourceTree = ""; }; - 4CE292391EF4B12B008DA555 /* Alamofire.podspec */ = {isa = PBXFileReference; lastKnownFileType = text; path = Alamofire.podspec; sourceTree = ""; }; - 4CF3B4281F5FC7900075BE59 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; - 4CF626EF1BA7CB3E0011A099 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 4CF626F81BA7CB3E0011A099 /* Alamofire tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Alamofire tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - 4CFB028F1D7CF28F0056F249 /* FileManager+AlamofireTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FileManager+AlamofireTests.swift"; sourceTree = ""; }; - 4CFB02EA1D7D2FA20056F249 /* empty_data.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = empty_data.json; sourceTree = ""; }; - 4CFB02EB1D7D2FA20056F249 /* invalid_data.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = invalid_data.json; sourceTree = ""; }; - 4CFB02EC1D7D2FA20056F249 /* valid_data.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = valid_data.json; sourceTree = ""; }; - 4CFB02F21D7D2FA20056F249 /* empty_string.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = empty_string.txt; sourceTree = ""; }; - 4CFB02F31D7D2FA20056F249 /* utf32_string.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = utf32_string.txt; sourceTree = ""; }; - 4CFB02F41D7D2FA20056F249 /* utf8_string.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = utf8_string.txt; sourceTree = ""; }; - 4CFD6B132201338E00FFB5E3 /* CachedResponseHandlerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CachedResponseHandlerTests.swift; sourceTree = ""; }; - 4DD67C0B1A5C55C900ED2280 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - B39E2F831C1A72F8002DA1A9 /* certDER.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = certDER.cer; path = selfSignedAndMalformedCerts/certDER.cer; sourceTree = ""; }; - B39E2F841C1A72F8002DA1A9 /* certDER.crt */ = {isa = PBXFileReference; lastKnownFileType = file; name = certDER.crt; path = selfSignedAndMalformedCerts/certDER.crt; sourceTree = ""; }; - B39E2F851C1A72F8002DA1A9 /* certDER.der */ = {isa = PBXFileReference; lastKnownFileType = file; name = certDER.der; path = selfSignedAndMalformedCerts/certDER.der; sourceTree = ""; }; - B39E2F861C1A72F8002DA1A9 /* certPEM.cer */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = certPEM.cer; path = selfSignedAndMalformedCerts/certPEM.cer; sourceTree = ""; }; - B39E2F871C1A72F8002DA1A9 /* certPEM.crt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = certPEM.crt; path = selfSignedAndMalformedCerts/certPEM.crt; sourceTree = ""; }; - B39E2F891C1A72F8002DA1A9 /* randomGibberish.crt */ = {isa = PBXFileReference; lastKnownFileType = file; name = randomGibberish.crt; path = selfSignedAndMalformedCerts/randomGibberish.crt; sourceTree = ""; }; - B39E2F8A1C1A72F8002DA1A9 /* keyDER.der */ = {isa = PBXFileReference; lastKnownFileType = file; name = keyDER.der; path = selfSignedAndMalformedCerts/keyDER.der; sourceTree = ""; }; - E4202FE01B667AA100C997FB /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F8111E3319A95C8B0040E7D1 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F8111E3719A95C8B0040E7D1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - F8111E3819A95C8B0040E7D1 /* Alamofire.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Alamofire.h; sourceTree = ""; }; - F8111E3E19A95C8B0040E7D1 /* Alamofire iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Alamofire iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - F8111E4119A95C8B0040E7D1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DownloadTests.swift; sourceTree = ""; }; - F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ParameterEncodingTests.swift; sourceTree = ""; }; - F8111E5D19A9674D0040E7D1 /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; - F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseTests.swift; sourceTree = ""; }; - F8111E5F19A9674D0040E7D1 /* UploadTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UploadTests.swift; sourceTree = ""; }; - F829C6B21A7A94F100A2CD59 /* Alamofire macOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Alamofire macOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; - F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TLSEvaluationTests.swift; sourceTree = ""; }; - F897FF4019AA800700AB5182 /* Alamofire.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Alamofire.swift; sourceTree = ""; }; - F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValidationTests.swift; sourceTree = ""; }; - F8D1C6F419D52968002E74FE /* SessionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionTests.swift; sourceTree = ""; }; - F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthenticationTests.swift; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4CF626EB1BA7CB3E0011A099 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4CF626F51BA7CB3E0011A099 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CF626F91BA7CB3E0011A099 /* Alamofire.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4DD67C071A5C55C900ED2280 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E4202FD91B667AA100C997FB /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E2F19A95C8B0040E7D1 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E3B19A95C8B0040E7D1 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 8035DB621BAB492500466CB3 /* Alamofire.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F829C6AF1A7A94F100A2CD59 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - F829C6B81A7A94F100A2CD59 /* Alamofire.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 4C256A4E1B09656A0065714F /* Core */ = { - isa = PBXGroup; - children = ( - F8E6024419CB46A800A3E7F1 /* AuthenticationTests.swift */, - F8111E5B19A9674D0040E7D1 /* DownloadTests.swift */, - 31501E872196962A005829F2 /* ParameterEncoderTests.swift */, - F8111E5C19A9674D0040E7D1 /* ParameterEncodingTests.swift */, - F8111E5D19A9674D0040E7D1 /* RequestTests.swift */, - F8111E5E19A9674D0040E7D1 /* ResponseTests.swift */, - 4C9DCE771CB1BCE2003E6463 /* SessionDelegateTests.swift */, - F8D1C6F419D52968002E74FE /* SessionTests.swift */, - F8111E5F19A9674D0040E7D1 /* UploadTests.swift */, - ); - name = Core; - sourceTree = ""; - }; - 4C256A4F1B09656E0065714F /* Features */ = { - isa = PBXGroup; - children = ( - 4CFD6B132201338E00FFB5E3 /* CachedResponseHandlerTests.swift */, - 4C341BB91B1A865A00C1B34D /* CacheTests.swift */, - 3113D46A21878227001CCD21 /* HTTPHeadersTests.swift */, - 4C3238E61B3604DB00FE04AE /* MultipartFormDataTests.swift */, - 4C3D00571C66A8B900D1F709 /* NetworkReachabilityManagerTests.swift */, - 4C0CB64A220CA8D600604EDC /* RedirectHandlerTests.swift */, - 4C0CB630220BC70300604EDC /* RequestInterceptorTests.swift */, - 4C0B58381B747A4400C0B99C /* ResponseSerializationTests.swift */, - 4CBD217F220B48AE008F1C59 /* RetryPolicyTests.swift */, - 4C33A1421B52089C00873DFF /* ServerTrustEvaluatorTests.swift */, - F86AEFE51AE6A282007D9C76 /* TLSEvaluationTests.swift */, - 4CCFA7991B2BE71600B6F460 /* URLProtocolTests.swift */, - F8AE910119D28DCC0078C7B2 /* ValidationTests.swift */, - ); - name = Features; - sourceTree = ""; - }; - 4C3238E91B3617A600FE04AE /* Resources */ = { - isa = PBXGroup; - children = ( - 4C33A1171B5207DB00873DFF /* Certificates */, - 4C33A1221B5207DB00873DFF /* Images */, - 4CFB02E81D7D2FA20056F249 /* Responses */, - ); - name = Resources; - sourceTree = ""; - }; - 4C33A1171B5207DB00873DFF /* Certificates */ = { - isa = PBXGroup; - children = ( - 4C812C391B535F060017E0BF /* alamofire.org */, - 4CCB20671D4549E000C64D5B /* expired.badssl.com */, - B39E2F821C1A72E5002DA1A9 /* Varying Encoding Types and Extensions */, - ); - name = Certificates; - path = Resources/Certificates; - sourceTree = ""; - }; - 4C33A1221B5207DB00873DFF /* Images */ = { - isa = PBXGroup; - children = ( - 4C33A1231B5207DB00873DFF /* rainbow.jpg */, - 4C33A1241B5207DB00873DFF /* unicorn.png */, - ); - name = Images; - path = Resources/Images; - sourceTree = ""; - }; - 4C33A13D1B52080800873DFF /* Root */ = { - isa = PBXGroup; - children = ( - 4C812C3A1B535F220017E0BF /* alamofire-root-ca.cer */, - ); - name = Root; - sourceTree = ""; - }; - 4C33A13E1B52081100873DFF /* Intermediate */ = { - isa = PBXGroup; - children = ( - 4C812C3D1B535F2E0017E0BF /* alamofire-signing-ca1.cer */, - 4C812C3E1B535F2E0017E0BF /* alamofire-signing-ca2.cer */, - ); - name = Intermediate; - sourceTree = ""; - }; - 4C33A13F1B52081A00873DFF /* Leaf */ = { - isa = PBXGroup; - children = ( - 4C33A1401B52084400873DFF /* Signed by CA1 */, - 4C33A1411B52084E00873DFF /* Signed by CA2 */, - ); - name = Leaf; - sourceTree = ""; - }; - 4C33A1401B52084400873DFF /* Signed by CA1 */ = { - isa = PBXGroup; - children = ( - 4C812C441B535F400017E0BF /* multiple-dns-names.cer */, - 4C812C451B535F400017E0BF /* signed-by-ca1.cer */, - 4C812C461B535F400017E0BF /* test.alamofire.org.cer */, - 4C812C431B535F400017E0BF /* wildcard.alamofire.org.cer */, - ); - name = "Signed by CA1"; - sourceTree = ""; - }; - 4C33A1411B52084E00873DFF /* Signed by CA2 */ = { - isa = PBXGroup; - children = ( - 4C812C4F1B535F540017E0BF /* expired.cer */, - 4C812C501B535F540017E0BF /* missing-dns-name-and-uri.cer */, - 4C812C511B535F540017E0BF /* signed-by-ca2.cer */, - 4C812C521B535F540017E0BF /* valid-dns-name.cer */, - 4C812C531B535F540017E0BF /* valid-uri.cer */, - ); - name = "Signed by CA2"; - sourceTree = ""; - }; - 4C4366991D7BB92700C38AAD /* Extensions */ = { - isa = PBXGroup; - children = ( - 4C43669A1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift */, - 319917B8209CE53A00103A19 /* OperationQueue+Alamofire.swift */, - 4C0CB640220CA89400604EDC /* URLRequest+Alamofire.swift */, - 31F5085C20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift */, - 4196936122FA1E05001EA5D5 /* Result+Alamofire.swift */, - ); - name = Extensions; - sourceTree = ""; - }; - 4C7C8D201B9D0D7300948136 /* Extensions */ = { - isa = PBXGroup; - children = ( - 31ED52E61D73889D00199085 /* AFError+AlamofireTests.swift */, - 4CFB028F1D7CF28F0056F249 /* FileManager+AlamofireTests.swift */, - ); - name = Extensions; - sourceTree = ""; - }; - 4C7DD7E9224C625500249836 /* Helpers */ = { - isa = PBXGroup; - children = ( - 4C7DD7EA224C627300249836 /* Result+Alamofire.swift */, - ); - name = Helpers; - sourceTree = ""; - }; - 4C812C391B535F060017E0BF /* alamofire.org */ = { - isa = PBXGroup; - children = ( - 4C33A13D1B52080800873DFF /* Root */, - 4C33A13E1B52081100873DFF /* Intermediate */, - 4C33A13F1B52081A00873DFF /* Leaf */, - ); - name = alamofire.org; - sourceTree = ""; - }; - 4C9E88361F5FB39F000BEC61 /* Migration Guides */ = { - isa = PBXGroup; - children = ( - 4C9E88371F5FB3B0000BEC61 /* Alamofire 2.0 Migration Guide.md */, - 4C9E88381F5FB3B0000BEC61 /* Alamofire 3.0 Migration Guide.md */, - 4C9E88391F5FB3B0000BEC61 /* Alamofire 4.0 Migration Guide.md */, - ); - name = "Migration Guides"; - sourceTree = ""; - }; - 4CCB20671D4549E000C64D5B /* expired.badssl.com */ = { - isa = PBXGroup; - children = ( - 4CCB20681D4549E000C64D5B /* expired.badssl.com-leaf.cer */, - 4CCB206A1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer */, - 4CCB206B1D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer */, - 4CCB20691D4549E000C64D5B /* expired.badssl.com-root-ca.cer */, - ); - path = expired.badssl.com; - sourceTree = ""; - }; - 4CDE2C481AF8A14A00BABAE5 /* Core */ = { - isa = PBXGroup; - children = ( - 4C1DC8531B68908E00476DE3 /* AFError.swift */, - 319917A9209CDCB000103A19 /* HTTPHeaders.swift */, - 31727417218BAEC90039FFCC /* HTTPMethod.swift */, - 4CB928281C66BFBC00CE5F08 /* Notifications.swift */, - 3172741C218BB1790039FFCC /* ParameterEncoder.swift */, - 4CE2724E1AF88FB500F1D59A /* ParameterEncoding.swift */, - 3191B5741F5F53A6003960A8 /* Protector.swift */, - 31991790209CDA7F00103A19 /* Request.swift */, - 319917A4209CDAC400103A19 /* RequestTaskMap.swift */, - 31991791209CDA7F00103A19 /* Response.swift */, - 31991792209CDA7F00103A19 /* Session.swift */, - 31991793209CDA7F00103A19 /* SessionDelegate.swift */, - 31D83FCD20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift */, - ); - name = Core; - sourceTree = ""; - }; - 4CDE2C491AF8A14E00BABAE5 /* Features */ = { - isa = PBXGroup; - children = ( - 31DADDFA224811ED0051390F /* AlamofireExtended.swift */, - 4C4466EA21F8F5D800AC9703 /* CachedResponseHandler.swift */, - 3111CE8720A77843008315E2 /* EventMonitor.swift */, - 4C23EB421B327C5B0090E0BC /* MultipartFormData.swift */, - 311B198F20B0D3B40036823B /* MultipartUpload.swift */, - 4C3D00531C66A63000D1F709 /* NetworkReachabilityManager.swift */, - 4C0CB645220CA8A400604EDC /* RedirectHandler.swift */, - 4C256A0521EEB69000AD5D87 /* RequestInterceptor.swift */, - 4CDE2C451AF89FF300BABAE5 /* ResponseSerialization.swift */, - 4C256A1921F1449C00AD5D87 /* RetryPolicy.swift */, - 4C811F8C1B51856D00E0F59A /* ServerTrustEvaluation.swift */, - 31FB2F8622C828D8007FD6D5 /* URLEncodedFormEncoder.swift */, - 4CDE2C421AF89F0900BABAE5 /* Validation.swift */, - ); - name = Features; - sourceTree = ""; - }; - 4CE292301EF4A386008DA555 /* Documentation */ = { - isa = PBXGroup; - children = ( - 312D1E0C1FC2551400E51FF1 /* AdvancedUsage.md */, - 4CE292321EF4A393008DA555 /* CHANGELOG.md */, - 4CE292331EF4A393008DA555 /* CONTRIBUTING.md */, - 316250E41F00ABE900E207A6 /* ISSUE_TEMPLATE.md */, - 316250E51F00ACD000E207A6 /* PULL_REQUEST_TEMPLATE.md */, - 4CE292311EF4A393008DA555 /* README.md */, - 312D1E0B1FC2551400E51FF1 /* Usage.md */, - 4C9E88361F5FB39F000BEC61 /* Migration Guides */, - ); - name = Documentation; - sourceTree = ""; - }; - 4CE292381EF4B116008DA555 /* Deployment */ = { - isa = PBXGroup; - children = ( - 4CE292391EF4B12B008DA555 /* Alamofire.podspec */, - 4CF3B4281F5FC7900075BE59 /* LICENSE */, - 31B2CA9521AA25CD005B371A /* Package.swift */, - ); - name = Deployment; - sourceTree = ""; - }; - 4CFB02E81D7D2FA20056F249 /* Responses */ = { - isa = PBXGroup; - children = ( - 4CFB02E91D7D2FA20056F249 /* JSON */, - 4CFB02F11D7D2FA20056F249 /* String */, - ); - name = Responses; - path = Resources/Responses; - sourceTree = ""; - }; - 4CFB02E91D7D2FA20056F249 /* JSON */ = { - isa = PBXGroup; - children = ( - 4CFB02EA1D7D2FA20056F249 /* empty_data.json */, - 4CFB02EB1D7D2FA20056F249 /* invalid_data.json */, - 4CFB02EC1D7D2FA20056F249 /* valid_data.json */, - ); - path = JSON; - sourceTree = ""; - }; - 4CFB02F11D7D2FA20056F249 /* String */ = { - isa = PBXGroup; - children = ( - 4CFB02F21D7D2FA20056F249 /* empty_string.txt */, - 4CFB02F31D7D2FA20056F249 /* utf32_string.txt */, - 4CFB02F41D7D2FA20056F249 /* utf8_string.txt */, - ); - path = String; - sourceTree = ""; - }; - B39E2F821C1A72E5002DA1A9 /* Varying Encoding Types and Extensions */ = { - isa = PBXGroup; - children = ( - B39E2F831C1A72F8002DA1A9 /* certDER.cer */, - B39E2F841C1A72F8002DA1A9 /* certDER.crt */, - B39E2F851C1A72F8002DA1A9 /* certDER.der */, - B39E2F861C1A72F8002DA1A9 /* certPEM.cer */, - B39E2F871C1A72F8002DA1A9 /* certPEM.crt */, - B39E2F891C1A72F8002DA1A9 /* randomGibberish.crt */, - B39E2F8A1C1A72F8002DA1A9 /* keyDER.der */, - ); - name = "Varying Encoding Types and Extensions"; - sourceTree = ""; - }; - F8111E2919A95C8B0040E7D1 = { - isa = PBXGroup; - children = ( - 4CE292381EF4B116008DA555 /* Deployment */, - 4CE292301EF4A386008DA555 /* Documentation */, - F8111E3519A95C8B0040E7D1 /* Source */, - F8111E3F19A95C8B0040E7D1 /* Tests */, - F8111E3419A95C8B0040E7D1 /* Products */, - ); - indentWidth = 4; - sourceTree = ""; - tabWidth = 4; - usesTabs = 0; - }; - F8111E3419A95C8B0040E7D1 /* Products */ = { - isa = PBXGroup; - children = ( - F8111E3319A95C8B0040E7D1 /* Alamofire.framework */, - F8111E3E19A95C8B0040E7D1 /* Alamofire iOS Tests.xctest */, - 4DD67C0B1A5C55C900ED2280 /* Alamofire.framework */, - F829C6B21A7A94F100A2CD59 /* Alamofire macOS Tests.xctest */, - E4202FE01B667AA100C997FB /* Alamofire.framework */, - 4CF626EF1BA7CB3E0011A099 /* Alamofire.framework */, - 4CF626F81BA7CB3E0011A099 /* Alamofire tvOS Tests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - F8111E3519A95C8B0040E7D1 /* Source */ = { - isa = PBXGroup; - children = ( - F897FF4019AA800700AB5182 /* Alamofire.swift */, - 4CDE2C481AF8A14A00BABAE5 /* Core */, - 4C4366991D7BB92700C38AAD /* Extensions */, - 4CDE2C491AF8A14E00BABAE5 /* Features */, - F8111E3619A95C8B0040E7D1 /* Supporting Files */, - ); - path = Source; - sourceTree = ""; - }; - F8111E3619A95C8B0040E7D1 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - F8111E3819A95C8B0040E7D1 /* Alamofire.h */, - F8111E3719A95C8B0040E7D1 /* Info.plist */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - F8111E3F19A95C8B0040E7D1 /* Tests */ = { - isa = PBXGroup; - children = ( - 4C256A501B096C2C0065714F /* BaseTestCase.swift */, - 31727421218BB9A50039FFCC /* HTTPBin.swift */, - 31F9683B20BB70290009606F /* NSLoggingEventMonitor.swift */, - 4C256A4E1B09656A0065714F /* Core */, - 4C7C8D201B9D0D7300948136 /* Extensions */, - 4C256A4F1B09656E0065714F /* Features */, - 4C7DD7E9224C625500249836 /* Helpers */, - 4C3238E91B3617A600FE04AE /* Resources */, - F8111E4019A95C8B0040E7D1 /* Supporting Files */, - ); - path = Tests; - sourceTree = ""; - }; - F8111E4019A95C8B0040E7D1 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - F8111E4119A95C8B0040E7D1 /* Info.plist */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 4CF626EC1BA7CB3E0011A099 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CF627061BA7CBE30011A099 /* Alamofire.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4DD67C081A5C55C900ED2280 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 4DD67C241A5C58FB00ED2280 /* Alamofire.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E4202FDA1B667AA100C997FB /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CEC605C1B745C9B00E684F4 /* Alamofire.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E3019A95C8B0040E7D1 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - F8111E3919A95C8B0040E7D1 /* Alamofire.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 4CF626EE1BA7CB3E0011A099 /* Alamofire tvOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4CF627041BA7CB3E0011A099 /* Build configuration list for PBXNativeTarget "Alamofire tvOS" */; - buildPhases = ( - 4CF626EA1BA7CB3E0011A099 /* Sources */, - 4CF626EB1BA7CB3E0011A099 /* Frameworks */, - 4CF626EC1BA7CB3E0011A099 /* Headers */, - 4CF626ED1BA7CB3E0011A099 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "Alamofire tvOS"; - productName = "Alamofire tvOS"; - productReference = 4CF626EF1BA7CB3E0011A099 /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; - 4CF626F71BA7CB3E0011A099 /* Alamofire tvOS Tests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4CF627051BA7CB3E0011A099 /* Build configuration list for PBXNativeTarget "Alamofire tvOS Tests" */; - buildPhases = ( - 4CF626F41BA7CB3E0011A099 /* Sources */, - 4CF626F51BA7CB3E0011A099 /* Frameworks */, - 4CF626F61BA7CB3E0011A099 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 4CF626FB1BA7CB3E0011A099 /* PBXTargetDependency */, - ); - name = "Alamofire tvOS Tests"; - productName = "Alamofire tvOSTests"; - productReference = 4CF626F81BA7CB3E0011A099 /* Alamofire tvOS Tests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 4DD67C0A1A5C55C900ED2280 /* Alamofire macOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4DD67C1E1A5C55C900ED2280 /* Build configuration list for PBXNativeTarget "Alamofire macOS" */; - buildPhases = ( - 4DD67C061A5C55C900ED2280 /* Sources */, - 4DD67C071A5C55C900ED2280 /* Frameworks */, - 4DD67C081A5C55C900ED2280 /* Headers */, - 4DD67C091A5C55C900ED2280 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "Alamofire macOS"; - productName = AlamofireOSX; - productReference = 4DD67C0B1A5C55C900ED2280 /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; - E4202FCD1B667AA100C997FB /* Alamofire watchOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = E4202FDD1B667AA100C997FB /* Build configuration list for PBXNativeTarget "Alamofire watchOS" */; - buildPhases = ( - E4202FCE1B667AA100C997FB /* Sources */, - E4202FD91B667AA100C997FB /* Frameworks */, - E4202FDA1B667AA100C997FB /* Headers */, - E4202FDC1B667AA100C997FB /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "Alamofire watchOS"; - productName = Alamofire; - productReference = E4202FE01B667AA100C997FB /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; - F8111E3219A95C8B0040E7D1 /* Alamofire iOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = F8111E4619A95C8B0040E7D1 /* Build configuration list for PBXNativeTarget "Alamofire iOS" */; - buildPhases = ( - F8111E2E19A95C8B0040E7D1 /* Sources */, - F8111E2F19A95C8B0040E7D1 /* Frameworks */, - F8111E3019A95C8B0040E7D1 /* Headers */, - F8111E3119A95C8B0040E7D1 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "Alamofire iOS"; - productName = Alamofire; - productReference = F8111E3319A95C8B0040E7D1 /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; - F8111E3D19A95C8B0040E7D1 /* Alamofire iOS Tests */ = { - isa = PBXNativeTarget; - buildConfigurationList = F8111E4919A95C8B0040E7D1 /* Build configuration list for PBXNativeTarget "Alamofire iOS Tests" */; - buildPhases = ( - F8111E3A19A95C8B0040E7D1 /* Sources */, - F8111E3B19A95C8B0040E7D1 /* Frameworks */, - F8111E3C19A95C8B0040E7D1 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - F8111E6619A967880040E7D1 /* PBXTargetDependency */, - ); - name = "Alamofire iOS Tests"; - productName = AlamofireTests; - productReference = F8111E3E19A95C8B0040E7D1 /* Alamofire iOS Tests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - F829C6B11A7A94F100A2CD59 /* Alamofire macOS Tests */ = { - isa = PBXNativeTarget; - buildConfigurationList = F829C6BB1A7A94F100A2CD59 /* Build configuration list for PBXNativeTarget "Alamofire macOS Tests" */; - buildPhases = ( - F829C6AE1A7A94F100A2CD59 /* Sources */, - F829C6AF1A7A94F100A2CD59 /* Frameworks */, - F829C6B01A7A94F100A2CD59 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - F829C6BA1A7A94F100A2CD59 /* PBXTargetDependency */, - ); - name = "Alamofire macOS Tests"; - productName = "Alamofire OSX Tests"; - productReference = F829C6B21A7A94F100A2CD59 /* Alamofire macOS Tests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - F8111E2A19A95C8B0040E7D1 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 1020; - ORGANIZATIONNAME = Alamofire; - TargetAttributes = { - 4CF626EE1BA7CB3E0011A099 = { - CreatedOnToolsVersion = 7.1; - LastSwiftMigration = 0900; - ProvisioningStyle = Manual; - }; - 4CF626F71BA7CB3E0011A099 = { - CreatedOnToolsVersion = 7.1; - LastSwiftMigration = 0900; - ProvisioningStyle = Manual; - }; - 4DD67C0A1A5C55C900ED2280 = { - CreatedOnToolsVersion = 6.1.1; - LastSwiftMigration = 0900; - ProvisioningStyle = Manual; - }; - E4202FCD1B667AA100C997FB = { - LastSwiftMigration = 0900; - ProvisioningStyle = Manual; - }; - F8111E3219A95C8B0040E7D1 = { - CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 1020; - ProvisioningStyle = Manual; - }; - F8111E3D19A95C8B0040E7D1 = { - CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 1020; - ProvisioningStyle = Manual; - }; - F829C6B11A7A94F100A2CD59 = { - CreatedOnToolsVersion = 6.1.1; - LastSwiftMigration = 0900; - ProvisioningStyle = Manual; - }; - }; - }; - buildConfigurationList = F8111E2D19A95C8B0040E7D1 /* Build configuration list for PBXProject "Alamofire" */; - compatibilityVersion = "Xcode 10.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = F8111E2919A95C8B0040E7D1; - productRefGroup = F8111E3419A95C8B0040E7D1 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - F8111E3219A95C8B0040E7D1 /* Alamofire iOS */, - F8111E3D19A95C8B0040E7D1 /* Alamofire iOS Tests */, - 4DD67C0A1A5C55C900ED2280 /* Alamofire macOS */, - F829C6B11A7A94F100A2CD59 /* Alamofire macOS Tests */, - 4CF626EE1BA7CB3E0011A099 /* Alamofire tvOS */, - 4CF626F71BA7CB3E0011A099 /* Alamofire tvOS Tests */, - E4202FCD1B667AA100C997FB /* Alamofire watchOS */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 4CF626ED1BA7CB3E0011A099 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4CF626F61BA7CB3E0011A099 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4C743D031C22772D00BCB23E /* wildcard.alamofire.org.cer in Resources */, - 4CCB20771D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */, - 4C743CFF1C22772D00BCB23E /* alamofire-signing-ca2.cer in Resources */, - 4CFB03091D7D2FA20056F249 /* empty_string.txt in Resources */, - 4C743D061C22772D00BCB23E /* signed-by-ca2.cer in Resources */, - 4CF627341BA7CC300011A099 /* rainbow.jpg in Resources */, - 4CCB20741D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */, - 4C743D081C22772D00BCB23E /* valid-uri.cer in Resources */, - 4C743CFC1C22772D00BCB23E /* keyDER.der in Resources */, - 4CFB02FD1D7D2FA20056F249 /* valid_data.json in Resources */, - 4CCB206E1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */, - 4CFB030C1D7D2FA20056F249 /* utf32_string.txt in Resources */, - 4CFB030F1D7D2FA20056F249 /* utf8_string.txt in Resources */, - 4C743CF81C22772D00BCB23E /* certDER.der in Resources */, - 4C743D051C22772D00BCB23E /* missing-dns-name-and-uri.cer in Resources */, - 4C743CFB1C22772D00BCB23E /* randomGibberish.crt in Resources */, - 4C743CFE1C22772D00BCB23E /* alamofire-signing-ca1.cer in Resources */, - 4C743D001C22772D00BCB23E /* multiple-dns-names.cer in Resources */, - 4C743D011C22772D00BCB23E /* signed-by-ca1.cer in Resources */, - 4C743D021C22772D00BCB23E /* test.alamofire.org.cer in Resources */, - 4C743CF61C22772D00BCB23E /* certDER.cer in Resources */, - 4C743CFD1C22772D00BCB23E /* alamofire-root-ca.cer in Resources */, - 4C743CF91C22772D00BCB23E /* certPEM.cer in Resources */, - 4CF627351BA7CC300011A099 /* unicorn.png in Resources */, - 4C743CFA1C22772D00BCB23E /* certPEM.crt in Resources */, - 4C743CF71C22772D00BCB23E /* certDER.crt in Resources */, - 4CCB20711D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */, - 4C743D071C22772D00BCB23E /* valid-dns-name.cer in Resources */, - 4C743D041C22772D00BCB23E /* expired.cer in Resources */, - 4CFB02FA1D7D2FA20056F249 /* invalid_data.json in Resources */, - 4CFB02F71D7D2FA20056F249 /* empty_data.json in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4DD67C091A5C55C900ED2280 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E4202FDC1B667AA100C997FB /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E3119A95C8B0040E7D1 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E3C19A95C8B0040E7D1 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4C743D2F1C22772F00BCB23E /* wildcard.alamofire.org.cer in Resources */, - 4CCB20751D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */, - 4C743D2B1C22772F00BCB23E /* alamofire-signing-ca2.cer in Resources */, - 4CFB03071D7D2FA20056F249 /* empty_string.txt in Resources */, - 4C743D321C22772F00BCB23E /* signed-by-ca2.cer in Resources */, - 4C33A13B1B5207DB00873DFF /* unicorn.png in Resources */, - 4CCB20721D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */, - 4C743D341C22772F00BCB23E /* valid-uri.cer in Resources */, - 4C743D281C22772F00BCB23E /* keyDER.der in Resources */, - 4CFB02FB1D7D2FA20056F249 /* valid_data.json in Resources */, - 4CCB206C1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */, - 4CFB030A1D7D2FA20056F249 /* utf32_string.txt in Resources */, - 4CFB030D1D7D2FA20056F249 /* utf8_string.txt in Resources */, - 4C743D241C22772F00BCB23E /* certDER.der in Resources */, - 4C743D311C22772F00BCB23E /* missing-dns-name-and-uri.cer in Resources */, - 4C743D271C22772F00BCB23E /* randomGibberish.crt in Resources */, - 4C743D2A1C22772F00BCB23E /* alamofire-signing-ca1.cer in Resources */, - 4C743D2C1C22772F00BCB23E /* multiple-dns-names.cer in Resources */, - 4C743D2D1C22772F00BCB23E /* signed-by-ca1.cer in Resources */, - 4C743D2E1C22772F00BCB23E /* test.alamofire.org.cer in Resources */, - 4C743D221C22772F00BCB23E /* certDER.cer in Resources */, - 4C743D291C22772F00BCB23E /* alamofire-root-ca.cer in Resources */, - 4C743D251C22772F00BCB23E /* certPEM.cer in Resources */, - 4C33A1391B5207DB00873DFF /* rainbow.jpg in Resources */, - 4C743D261C22772F00BCB23E /* certPEM.crt in Resources */, - 4C743D231C22772F00BCB23E /* certDER.crt in Resources */, - 4CCB206F1D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */, - 4C743D331C22772F00BCB23E /* valid-dns-name.cer in Resources */, - 4C743D301C22772F00BCB23E /* expired.cer in Resources */, - 4CFB02F81D7D2FA20056F249 /* invalid_data.json in Resources */, - 4CFB02F51D7D2FA20056F249 /* empty_data.json in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F829C6B01A7A94F100A2CD59 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4C743D191C22772E00BCB23E /* wildcard.alamofire.org.cer in Resources */, - 4CCB20761D4549E000C64D5B /* expired.badssl.com-intermediate-ca-2.cer in Resources */, - 4C743D151C22772E00BCB23E /* alamofire-signing-ca2.cer in Resources */, - 4CFB03081D7D2FA20056F249 /* empty_string.txt in Resources */, - 4C743D1C1C22772E00BCB23E /* signed-by-ca2.cer in Resources */, - 4C33A13C1B5207DB00873DFF /* unicorn.png in Resources */, - 4CCB20731D4549E000C64D5B /* expired.badssl.com-intermediate-ca-1.cer in Resources */, - 4C743D1E1C22772E00BCB23E /* valid-uri.cer in Resources */, - 4C743D121C22772E00BCB23E /* keyDER.der in Resources */, - 4CFB02FC1D7D2FA20056F249 /* valid_data.json in Resources */, - 4CCB206D1D4549E000C64D5B /* expired.badssl.com-leaf.cer in Resources */, - 4CFB030B1D7D2FA20056F249 /* utf32_string.txt in Resources */, - 4CFB030E1D7D2FA20056F249 /* utf8_string.txt in Resources */, - 4C743D0E1C22772E00BCB23E /* certDER.der in Resources */, - 4C743D1B1C22772E00BCB23E /* missing-dns-name-and-uri.cer in Resources */, - 4C743D111C22772E00BCB23E /* randomGibberish.crt in Resources */, - 4C743D141C22772E00BCB23E /* alamofire-signing-ca1.cer in Resources */, - 4C743D161C22772E00BCB23E /* multiple-dns-names.cer in Resources */, - 4C743D171C22772E00BCB23E /* signed-by-ca1.cer in Resources */, - 4C743D181C22772E00BCB23E /* test.alamofire.org.cer in Resources */, - 4C743D0C1C22772E00BCB23E /* certDER.cer in Resources */, - 4C743D131C22772E00BCB23E /* alamofire-root-ca.cer in Resources */, - 4C743D0F1C22772E00BCB23E /* certPEM.cer in Resources */, - 4C33A13A1B5207DB00873DFF /* rainbow.jpg in Resources */, - 4C743D101C22772E00BCB23E /* certPEM.crt in Resources */, - 4C743D0D1C22772E00BCB23E /* certDER.crt in Resources */, - 4CCB20701D4549E000C64D5B /* expired.badssl.com-root-ca.cer in Resources */, - 4C743D1D1C22772E00BCB23E /* valid-dns-name.cer in Resources */, - 4C743D1A1C22772E00BCB23E /* expired.cer in Resources */, - 4CFB02F91D7D2FA20056F249 /* invalid_data.json in Resources */, - 4CFB02F61D7D2FA20056F249 /* empty_data.json in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 4CF626EA1BA7CB3E0011A099 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CF627081BA7CBF60011A099 /* AFError.swift in Sources */, - 3191B5771F5F53A6003960A8 /* Protector.swift in Sources */, - 3199179A209CDA7F00103A19 /* Response.swift in Sources */, - 31D83FD020D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */, - 319917A7209CDAC400103A19 /* RequestTaskMap.swift in Sources */, - 4CF627131BA7CBF60011A099 /* Validation.swift in Sources */, - 31F5085F20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */, - 4196936422FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */, - 3172741F218BB1790039FFCC /* ParameterEncoder.swift in Sources */, - 319917BB209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */, - 319917AC209CDCB000103A19 /* HTTPHeaders.swift in Sources */, - 3172741A218BAEC90039FFCC /* HTTPMethod.swift in Sources */, - 4C0CB648220CA8A400604EDC /* RedirectHandler.swift in Sources */, - 4CF6270E1BA7CBF60011A099 /* MultipartFormData.swift in Sources */, - 4CB9282B1C66BFBC00CE5F08 /* Notifications.swift in Sources */, - 31FB2F8922C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */, - 4C0CB643220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */, - 4CF6270F1BA7CBF60011A099 /* ResponseSerialization.swift in Sources */, - 4C256A0821EEB69000AD5D87 /* RequestInterceptor.swift in Sources */, - 4C43669D1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */, - 4C3D00561C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */, - 311B199220B0E3480036823B /* MultipartUpload.swift in Sources */, - 4C4466ED21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */, - 319917A2209CDA7F00103A19 /* SessionDelegate.swift in Sources */, - 4CF6270A1BA7CBF60011A099 /* ParameterEncoding.swift in Sources */, - 4C256A1C21F1449C00AD5D87 /* RetryPolicy.swift in Sources */, - 31991796209CDA7F00103A19 /* Request.swift in Sources */, - 4CF627101BA7CBF60011A099 /* ServerTrustEvaluation.swift in Sources */, - 3199179E209CDA7F00103A19 /* Session.swift in Sources */, - 4CF627071BA7CBF60011A099 /* Alamofire.swift in Sources */, - 3111CE8A20A77945008315E2 /* EventMonitor.swift in Sources */, - 31DADDFD224811ED0051390F /* AlamofireExtended.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4CF626F41BA7CB3E0011A099 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CF627181BA7CC240011A099 /* RequestTests.swift in Sources */, - 3111CE9720A7EC3A008315E2 /* ServerTrustEvaluatorTests.swift in Sources */, - 3111CE9420A7EC32008315E2 /* ResponseSerializationTests.swift in Sources */, - 3111CE8E20A7EBE7008315E2 /* MultipartFormDataTests.swift in Sources */, - 311B199620B0ED990036823B /* UploadTests.swift in Sources */, - 4C0CB633220BC70300604EDC /* RequestInterceptorTests.swift in Sources */, - 3107EA3720A11AE200445260 /* AuthenticationTests.swift in Sources */, - 31ED52EA1D73891C00199085 /* AFError+AlamofireTests.swift in Sources */, - 4C0CB64D220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */, - 3107EA3A20A11F9700445260 /* ResponseTests.swift in Sources */, - 4CFB02921D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */, - 4CF627141BA7CC240011A099 /* BaseTestCase.swift in Sources */, - 4C7DD7ED224C627300249836 /* Result+Alamofire.swift in Sources */, - 31727424218BB9A50039FFCC /* HTTPBin.swift in Sources */, - 311A89C123185BC0003BB714 /* CachedResponseHandlerTests.swift in Sources */, - 31EBD9C320D1D89D00D1FF34 /* ValidationTests.swift in Sources */, - 3111CE8620A76370008315E2 /* SessionTests.swift in Sources */, - 31C2B0F220B271380089BA7C /* TLSEvaluationTests.swift in Sources */, - 3111CE9D20A7EC58008315E2 /* URLProtocolTests.swift in Sources */, - 4CBD2182220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */, - 317A6A7820B2208000A9FEC5 /* DownloadTests.swift in Sources */, - 31F9683E20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */, - 3113D46D21878227001CCD21 /* HTTPHeadersTests.swift in Sources */, - 31501E8A2196962A005829F2 /* ParameterEncoderTests.swift in Sources */, - 3107EA4120A1267D00445260 /* SessionDelegateTests.swift in Sources */, - 31C2B0EC20B271060089BA7C /* CacheTests.swift in Sources */, - 3111CE9120A7EC27008315E2 /* NetworkReachabilityManagerTests.swift in Sources */, - 4CF627171BA7CC240011A099 /* ParameterEncodingTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4DD67C061A5C55C900ED2280 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CE272501AF88FB500F1D59A /* ParameterEncoding.swift in Sources */, - 3191B5761F5F53A6003960A8 /* Protector.swift in Sources */, - 4CDE2C471AF89FF300BABAE5 /* ResponseSerialization.swift in Sources */, - 31991799209CDA7F00103A19 /* Response.swift in Sources */, - 31D83FCF20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */, - 319917A6209CDAC400103A19 /* RequestTaskMap.swift in Sources */, - 4C1DC8551B68908E00476DE3 /* AFError.swift in Sources */, - 31F5085E20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */, - 4196936322FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */, - 3172741E218BB1790039FFCC /* ParameterEncoder.swift in Sources */, - 319917BA209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */, - 319917AB209CDCB000103A19 /* HTTPHeaders.swift in Sources */, - 31727419218BAEC90039FFCC /* HTTPMethod.swift in Sources */, - 4C0CB647220CA8A400604EDC /* RedirectHandler.swift in Sources */, - 4CB9282A1C66BFBC00CE5F08 /* Notifications.swift in Sources */, - 4DD67C251A5C590000ED2280 /* Alamofire.swift in Sources */, - 31FB2F8822C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */, - 4C0CB642220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */, - 4C23EB441B327C5B0090E0BC /* MultipartFormData.swift in Sources */, - 4C256A0721EEB69000AD5D87 /* RequestInterceptor.swift in Sources */, - 4C43669C1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */, - 4C811F8E1B51856D00E0F59A /* ServerTrustEvaluation.swift in Sources */, - 311B199120B0E3470036823B /* MultipartUpload.swift in Sources */, - 4C4466EC21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */, - 319917A1209CDA7F00103A19 /* SessionDelegate.swift in Sources */, - 4C3D00551C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */, - 4C256A1B21F1449C00AD5D87 /* RetryPolicy.swift in Sources */, - 31991795209CDA7F00103A19 /* Request.swift in Sources */, - 4CDE2C441AF89F0900BABAE5 /* Validation.swift in Sources */, - 3199179D209CDA7F00103A19 /* Session.swift in Sources */, - 3111CE8920A77944008315E2 /* EventMonitor.swift in Sources */, - 31DADDFC224811ED0051390F /* AlamofireExtended.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E4202FCE1B667AA100C997FB /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CEE82AD1C6813CF00E9C9F0 /* NetworkReachabilityManager.swift in Sources */, - E4202FD01B667AA100C997FB /* ParameterEncoding.swift in Sources */, - 3191B5781F5F53A6003960A8 /* Protector.swift in Sources */, - 3199179B209CDA7F00103A19 /* Response.swift in Sources */, - 31D83FD120D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */, - 319917A8209CDAC400103A19 /* RequestTaskMap.swift in Sources */, - 4CEC605A1B745C9100E684F4 /* AFError.swift in Sources */, - 31F5086020B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */, - 4196936522FA1EAD001EA5D5 /* Result+Alamofire.swift in Sources */, - 31727420218BB1790039FFCC /* ParameterEncoder.swift in Sources */, - 319917BC209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */, - 319917AD209CDCB000103A19 /* HTTPHeaders.swift in Sources */, - 3172741B218BAEC90039FFCC /* HTTPMethod.swift in Sources */, - 4C0CB649220CA8A400604EDC /* RedirectHandler.swift in Sources */, - E4202FD21B667AA100C997FB /* ResponseSerialization.swift in Sources */, - 4CB9282C1C66BFBC00CE5F08 /* Notifications.swift in Sources */, - 31FB2F8A22C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */, - 4C0CB644220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */, - 4C256A0921EEB69000AD5D87 /* RequestInterceptor.swift in Sources */, - 4C43669E1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */, - E4202FD41B667AA100C997FB /* Alamofire.swift in Sources */, - 311B199320B0E3480036823B /* MultipartUpload.swift in Sources */, - 4C4466EE21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */, - 319917A3209CDA7F00103A19 /* SessionDelegate.swift in Sources */, - E4202FD51B667AA100C997FB /* MultipartFormData.swift in Sources */, - 4C256A1D21F1449C00AD5D87 /* RetryPolicy.swift in Sources */, - 31991797209CDA7F00103A19 /* Request.swift in Sources */, - E4202FD61B667AA100C997FB /* ServerTrustEvaluation.swift in Sources */, - 3199179F209CDA7F00103A19 /* Session.swift in Sources */, - E4202FD81B667AA100C997FB /* Validation.swift in Sources */, - 3111CE8B20A77945008315E2 /* EventMonitor.swift in Sources */, - 31DADDFE224811ED0051390F /* AlamofireExtended.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E2E19A95C8B0040E7D1 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4CE2724F1AF88FB500F1D59A /* ParameterEncoding.swift in Sources */, - 3191B5751F5F53A6003960A8 /* Protector.swift in Sources */, - 4CDE2C461AF89FF300BABAE5 /* ResponseSerialization.swift in Sources */, - 31991798209CDA7F00103A19 /* Response.swift in Sources */, - 31D83FCE20D5C29300D93E47 /* URLConvertible+URLRequestConvertible.swift in Sources */, - 319917A5209CDAC400103A19 /* RequestTaskMap.swift in Sources */, - 4C1DC8541B68908E00476DE3 /* AFError.swift in Sources */, - 31F5085D20B50DC400FE2A0C /* URLSessionConfiguration+Alamofire.swift in Sources */, - 4196936222FA1E05001EA5D5 /* Result+Alamofire.swift in Sources */, - 3172741D218BB1790039FFCC /* ParameterEncoder.swift in Sources */, - 319917B9209CE53A00103A19 /* OperationQueue+Alamofire.swift in Sources */, - 319917AA209CDCB000103A19 /* HTTPHeaders.swift in Sources */, - 31727418218BAEC90039FFCC /* HTTPMethod.swift in Sources */, - 4C0CB646220CA8A400604EDC /* RedirectHandler.swift in Sources */, - F897FF4119AA800700AB5182 /* Alamofire.swift in Sources */, - 4C23EB431B327C5B0090E0BC /* MultipartFormData.swift in Sources */, - 31FB2F8722C828D8007FD6D5 /* URLEncodedFormEncoder.swift in Sources */, - 4C0CB641220CA89400604EDC /* URLRequest+Alamofire.swift in Sources */, - 4C811F8D1B51856D00E0F59A /* ServerTrustEvaluation.swift in Sources */, - 4C256A0621EEB69000AD5D87 /* RequestInterceptor.swift in Sources */, - 4C43669B1D7BB93D00C38AAD /* DispatchQueue+Alamofire.swift in Sources */, - 4C3D00541C66A63000D1F709 /* NetworkReachabilityManager.swift in Sources */, - 311B199020B0D3B40036823B /* MultipartUpload.swift in Sources */, - 4C4466EB21F8F5D800AC9703 /* CachedResponseHandler.swift in Sources */, - 319917A0209CDA7F00103A19 /* SessionDelegate.swift in Sources */, - 4CDE2C431AF89F0900BABAE5 /* Validation.swift in Sources */, - 4C256A1A21F1449C00AD5D87 /* RetryPolicy.swift in Sources */, - 31991794209CDA7F00103A19 /* Request.swift in Sources */, - 4CB928291C66BFBC00CE5F08 /* Notifications.swift in Sources */, - 3199179C209CDA7F00103A19 /* Session.swift in Sources */, - 3111CE8820A77843008315E2 /* EventMonitor.swift in Sources */, - 31DADDFB224811ED0051390F /* AlamofireExtended.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8111E3A19A95C8B0040E7D1 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 31ED52E81D73891B00199085 /* AFError+AlamofireTests.swift in Sources */, - 3111CE9520A7EC39008315E2 /* ServerTrustEvaluatorTests.swift in Sources */, - 3111CE9220A7EC30008315E2 /* ResponseSerializationTests.swift in Sources */, - 3111CE8C20A7EBE6008315E2 /* MultipartFormDataTests.swift in Sources */, - 311B199420B0ED980036823B /* UploadTests.swift in Sources */, - 4C0CB631220BC70300604EDC /* RequestInterceptorTests.swift in Sources */, - 3107EA3520A11AE100445260 /* AuthenticationTests.swift in Sources */, - 4CFB02901D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */, - 4C0CB64B220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */, - 3107EA3820A11F9600445260 /* ResponseTests.swift in Sources */, - F8858DDD19A96B4300F55F93 /* RequestTests.swift in Sources */, - 4C256A531B096C770065714F /* BaseTestCase.swift in Sources */, - 4C7DD7EB224C627300249836 /* Result+Alamofire.swift in Sources */, - 31727422218BB9A50039FFCC /* HTTPBin.swift in Sources */, - 311A89BF23185BBF003BB714 /* CachedResponseHandlerTests.swift in Sources */, - 31EBD9C120D1D89C00D1FF34 /* ValidationTests.swift in Sources */, - 3111CE8420A7636E008315E2 /* SessionTests.swift in Sources */, - 31C2B0F020B271370089BA7C /* TLSEvaluationTests.swift in Sources */, - 3111CE9B20A7EC57008315E2 /* URLProtocolTests.swift in Sources */, - 4CBD2180220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */, - 317A6A7620B2207F00A9FEC5 /* DownloadTests.swift in Sources */, - 31F9683C20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */, - 3113D46B21878227001CCD21 /* HTTPHeadersTests.swift in Sources */, - 31501E882196962A005829F2 /* ParameterEncoderTests.swift in Sources */, - 3107EA3F20A1267C00445260 /* SessionDelegateTests.swift in Sources */, - 31C2B0EA20B271040089BA7C /* CacheTests.swift in Sources */, - 3111CE8F20A7EC26008315E2 /* NetworkReachabilityManagerTests.swift in Sources */, - F8111E6119A9674D0040E7D1 /* ParameterEncodingTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F829C6AE1A7A94F100A2CD59 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 31ED52E91D73891C00199085 /* AFError+AlamofireTests.swift in Sources */, - 3111CE9620A7EC3A008315E2 /* ServerTrustEvaluatorTests.swift in Sources */, - 3111CE9320A7EC31008315E2 /* ResponseSerializationTests.swift in Sources */, - 3111CE8D20A7EBE7008315E2 /* MultipartFormDataTests.swift in Sources */, - 311B199520B0ED980036823B /* UploadTests.swift in Sources */, - 4C0CB632220BC70300604EDC /* RequestInterceptorTests.swift in Sources */, - 3107EA3620A11AE100445260 /* AuthenticationTests.swift in Sources */, - 4CFB02911D7CF28F0056F249 /* FileManager+AlamofireTests.swift in Sources */, - 4C0CB64C220CA8D600604EDC /* RedirectHandlerTests.swift in Sources */, - 3107EA3920A11F9600445260 /* ResponseTests.swift in Sources */, - F829C6BE1A7A950600A2CD59 /* ParameterEncodingTests.swift in Sources */, - F829C6BF1A7A950600A2CD59 /* RequestTests.swift in Sources */, - 4C7DD7EC224C627300249836 /* Result+Alamofire.swift in Sources */, - 31727423218BB9A50039FFCC /* HTTPBin.swift in Sources */, - 311A89C023185BBF003BB714 /* CachedResponseHandlerTests.swift in Sources */, - 31EBD9C220D1D89C00D1FF34 /* ValidationTests.swift in Sources */, - 3111CE8520A7636F008315E2 /* SessionTests.swift in Sources */, - 31C2B0F120B271370089BA7C /* TLSEvaluationTests.swift in Sources */, - 3111CE9C20A7EC58008315E2 /* URLProtocolTests.swift in Sources */, - 4CBD2181220B48AE008F1C59 /* RetryPolicyTests.swift in Sources */, - 317A6A7720B2208000A9FEC5 /* DownloadTests.swift in Sources */, - 31F9683D20BB70290009606F /* NSLoggingEventMonitor.swift in Sources */, - 3113D46C21878227001CCD21 /* HTTPHeadersTests.swift in Sources */, - 31501E892196962A005829F2 /* ParameterEncoderTests.swift in Sources */, - 3107EA4020A1267C00445260 /* SessionDelegateTests.swift in Sources */, - 31C2B0EB20B271050089BA7C /* CacheTests.swift in Sources */, - 3111CE9020A7EC27008315E2 /* NetworkReachabilityManagerTests.swift in Sources */, - 4C256A541B096C770065714F /* BaseTestCase.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 4CF626FB1BA7CB3E0011A099 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4CF626EE1BA7CB3E0011A099 /* Alamofire tvOS */; - targetProxy = 4CF626FA1BA7CB3E0011A099 /* PBXContainerItemProxy */; - }; - F8111E6619A967880040E7D1 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = F8111E3219A95C8B0040E7D1 /* Alamofire iOS */; - targetProxy = F8111E6519A967880040E7D1 /* PBXContainerItemProxy */; - }; - F829C6BA1A7A94F100A2CD59 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4DD67C0A1A5C55C900ED2280 /* Alamofire macOS */; - targetProxy = F829C6B91A7A94F100A2CD59 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 4CF627001BA7CB3E0011A099 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = appletvos; - SKIP_INSTALL = YES; - }; - name = Debug; - }; - 4CF627011BA7CB3E0011A099 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = appletvos; - SKIP_INSTALL = YES; - }; - name = Release; - }; - 4CF627021BA7CB3E0011A099 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.Alamofire-tvOSTests"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = appletvos; - }; - name = Debug; - }; - 4CF627031BA7CB3E0011A099 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.Alamofire-tvOSTests"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = appletvos; - }; - name = Release; - }; - 4DD67C1F1A5C55C900ED2280 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - FRAMEWORK_VERSION = A; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = macosx; - SKIP_INSTALL = YES; - }; - name = Debug; - }; - 4DD67C201A5C55C900ED2280 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - FRAMEWORK_VERSION = A; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = macosx; - SKIP_INSTALL = YES; - }; - name = Release; - }; - E4202FDE1B667AA100C997FB /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = org.alamofire.Alamofire.watchOS; - SDKROOT = watchos; - SKIP_INSTALL = YES; - }; - name = Debug; - }; - E4202FDF1B667AA100C997FB /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = org.alamofire.Alamofire.watchOS; - SDKROOT = watchos; - SKIP_INSTALL = YES; - }; - name = Release; - }; - F8111E4419A95C8B0040E7D1 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - APPLICATION_EXTENSION_API_ONLY = YES; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_UNDEFINED_BEHAVIOR_SANITIZER_INTEGER = YES; - CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_STYLE = Manual; - COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - INFOPLIST_FILE = Source/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - MACOSX_DEPLOYMENT_TARGET = 10.12; - ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = ( - "-framework", - CFNetwork, - ); - PRODUCT_BUNDLE_IDENTIFIER = org.alamofire.Alamofire; - PRODUCT_NAME = Alamofire; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = Off; - SWIFT_VERSION = 5.0; - TVOS_DEPLOYMENT_TARGET = 10.0; - VERSIONING_SYSTEM = "apple-generic"; - WATCHOS_DEPLOYMENT_TARGET = 3.0; - }; - name = Debug; - }; - F8111E4519A95C8B0040E7D1 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - APPLICATION_EXTENSION_API_ONLY = YES; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_UNDEFINED_BEHAVIOR_SANITIZER_INTEGER = YES; - CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_STYLE = Manual; - COPY_PHASE_STRIP = YES; - CURRENT_PROJECT_VERSION = 1; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - INFOPLIST_FILE = Source/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - MACOSX_DEPLOYMENT_TARGET = 10.12; - OTHER_LDFLAGS = ( - "-framework", - CFNetwork, - ); - PRODUCT_BUNDLE_IDENTIFIER = org.alamofire.Alamofire; - PRODUCT_NAME = Alamofire; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_SWIFT3_OBJC_INFERENCE = Off; - SWIFT_VERSION = 5.0; - TVOS_DEPLOYMENT_TARGET = 10.0; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - WATCHOS_DEPLOYMENT_TARGET = 3.0; - }; - name = Release; - }; - F8111E4719A95C8B0040E7D1 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - F8111E4819A95C8B0040E7D1 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; - F8111E4A19A95C8B0040E7D1 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - CODE_SIGN_STYLE = Manual; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = iphoneos; - }; - name = Debug; - }; - F8111E4B19A95C8B0040E7D1 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - CODE_SIGN_STYLE = Manual; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = iphoneos; - }; - name = Release; - }; - F829C6BC1A7A94F100A2CD59 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/../Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; - }; - name = Debug; - }; - F829C6BD1A7A94F100A2CD59 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - APPLICATION_EXTENSION_API_ONLY = NO; - INFOPLIST_FILE = Tests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - "@loader_path/../Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.$(PRODUCT_NAME:rfc1034identifier)"; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = macosx; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 4CF627041BA7CB3E0011A099 /* Build configuration list for PBXNativeTarget "Alamofire tvOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4CF627001BA7CB3E0011A099 /* Debug */, - 4CF627011BA7CB3E0011A099 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4CF627051BA7CB3E0011A099 /* Build configuration list for PBXNativeTarget "Alamofire tvOS Tests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4CF627021BA7CB3E0011A099 /* Debug */, - 4CF627031BA7CB3E0011A099 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4DD67C1E1A5C55C900ED2280 /* Build configuration list for PBXNativeTarget "Alamofire macOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4DD67C1F1A5C55C900ED2280 /* Debug */, - 4DD67C201A5C55C900ED2280 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - E4202FDD1B667AA100C997FB /* Build configuration list for PBXNativeTarget "Alamofire watchOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - E4202FDE1B667AA100C997FB /* Debug */, - E4202FDF1B667AA100C997FB /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F8111E2D19A95C8B0040E7D1 /* Build configuration list for PBXProject "Alamofire" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F8111E4419A95C8B0040E7D1 /* Debug */, - F8111E4519A95C8B0040E7D1 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F8111E4619A95C8B0040E7D1 /* Build configuration list for PBXNativeTarget "Alamofire iOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F8111E4719A95C8B0040E7D1 /* Debug */, - F8111E4819A95C8B0040E7D1 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F8111E4919A95C8B0040E7D1 /* Build configuration list for PBXNativeTarget "Alamofire iOS Tests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F8111E4A19A95C8B0040E7D1 /* Debug */, - F8111E4B19A95C8B0040E7D1 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F829C6BB1A7A94F100A2CD59 /* Build configuration list for PBXNativeTarget "Alamofire macOS Tests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F829C6BC1A7A94F100A2CD59 /* Debug */, - F829C6BD1A7A94F100A2CD59 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = F8111E2A19A95C8B0040E7D1 /* Project object */; -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 7d39b0e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire iOS.xcscheme b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire iOS.xcscheme deleted file mode 100644 index 6041c08..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire iOS.xcscheme +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire macOS.xcscheme b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire macOS.xcscheme deleted file mode 100644 index e1e22e2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire macOS.xcscheme +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire tvOS.xcscheme b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire tvOS.xcscheme deleted file mode 100644 index 307fe9f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire tvOS.xcscheme +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire watchOS.xcscheme b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire watchOS.xcscheme deleted file mode 100644 index 5cf8f64..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcodeproj/xcshareddata/xcschemes/Alamofire watchOS.xcscheme +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/contents.xcworkspacedata b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 748f4a0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Alamofire.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/CHANGELOG.md b/Lesson12/Carthage/Checkouts/Alamofire/CHANGELOG.md deleted file mode 100644 index e86e9b4..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/CHANGELOG.md +++ /dev/null @@ -1,2520 +0,0 @@ -# Change Log -All notable changes to this project will be documented in this file. -`Alamofire` adheres to [Semantic Versioning](https://semver.org/). - -#### 5.x Releases -- `5.0.0` Release Candidates - [5.0.0-rc.1](#500-rc1) | [5.0.0-rc.2](#500-rc2) | [5.0.0-rc.3](#500-rc3) -- `5.0.0` Betas - [5.0.0-beta.1](#500-beta1) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) - -#### 4.x Releases -- `4.9.x` Releases - [4.9.0](#490) | [4.9.1](#491) -- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481) | [4.8.2](#482) -- `4.7.x` Releases - [4.7.0](#470) | [4.7.1](#471) | [4.7.2](#472) | [4.7.3](#473) -- `4.6.x` Releases - [4.6.0](#460) -- `4.5.x` Releases - [4.5.0](#450) | [4.5.1](#451) -- `4.4.x` Releases - [4.4.0](#440) -- `4.3.x` Releases - [4.3.0](#430) -- `4.2.x` Releases - [4.2.0](#420) -- `4.1.x` Releases - [4.1.0](#410) -- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401) -- `4.0.0` Betas - [4.0.0-beta.1](#400-beta1) | [4.0.0-beta.2](#400-beta2) - -#### 3.x Releases -- `3.5.x` Releases - [3.5.0](#350) | [3.5.1](#351) -- `3.4.x` Releases - [3.4.0](#340) | [3.4.1](#341) | [3.4.2](#342) -- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331) -- `3.2.x` Releases - [3.2.0](#320) | [3.2.1](#321) -- `3.1.x` Releases - [3.1.0](#310) | [3.1.1](#311) | [3.1.2](#312) | [3.1.3](#313) | [3.1.4](#314) | [3.1.5](#315) -- `3.0.x` Releases - [3.0.0](#300) | [3.0.1](#301) -- `3.0.0` Betas - [3.0.0-beta.1](#300-beta1) | [3.0.0-beta.2](#300-beta2) | [3.0.0-beta.3](#300-beta3) - -#### 2.x Releases -- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) -- `2.0.0` Betas - [2.0.0-beta.1](#200-beta1) | [2.0.0-beta.2](#200-beta2) | [2.0.0-beta.3](#200-beta3) | [2.0.0-beta.4](#200-beta4) - -#### 1.x Releases -- `1.3.x` Releases - [1.3.0](#130) | [1.3.1](#131) -- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122) | [1.2.3](#123) -- `1.1.x` Releases - [1.1.0](#110) | [1.1.1](#111) | [1.1.2](#112) | [1.1.3](#113) | [1.1.4](#114) | [1.1.5](#115) -- `1.0.x` Releases - [1.0.0](#100) | [1.0.1](#101) - ---- - -## [5.0.0-rc.3](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-rc.3) -Released on 2019-10-26. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/62?closed=1). **Note:** Alamofire 5 is now API stable. - -#### Updated -- Automatic `resume()` behavior to be called after the first response handler is added instead of immediately after task creation. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2965](https://github.com/Alamofire/Alamofire/pull/2965). - -#### Fixed -- Incorrect header convenience method in Usage documentation. - - Fixed by [Sebastian](https://github.com/Buesing-Sebastian) in Pull Request [#2952](https://github.com/Alamofire/Alamofire/pull/2952). -- Unstable parameter ordering in `URLEncodedFormEncoder`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2961](https://github.com/Alamofire/Alamofire/pull/2961). -- Xcode build issues and precompiled binary build issues by removing the dynamic bundle identifier. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2966](https://github.com/Alamofire/Alamofire/pull/2966). -- Build warnings for deprecated `SecTrust` API when building for Catalyst. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2977](https://github.com/Alamofire/Alamofire/pull/2977). -- Regression from Alamofire 4 causing Alamofire to reject NTLM and Negotiate authentication methods. - - Fixed by [Adrian Kashivskyy](https://github.com/akashivskyy) in Pull Request [#2975](https://github.com/Alamofire/Alamofire/pull/2975). - -## [5.0.0-rc.2](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-rc.2) -Released on 2019-09-08. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/59?closed=1). **Note:** Alamofire 5 is now API stable. - -#### Fixed -- Single remaining use of `Error` instead of generic `Failure` constraint in `DataResponse` API. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2937](https://github.com/Alamofire/Alamofire/pull/2937). - -## [5.0.0-rc.1](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-rc.1) -Released on 2019-09-04. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/58?closed=1). **Note:** Alamofire 5 is now API stable. - -#### Added -- `cancelAllRequests` method on `Session` to cancel all in flight requests. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2890](https://github.com/Alamofire/Alamofire/pull/2890). -- Ability to inject `FileManager` instance into `UploadRequest`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2898](https://github.com/Alamofire/Alamofire/pull/2898). -- `DataPreprocessor` protocol and implementations, allowing the preprocessing of data before serialization. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2903](https://github.com/Alamofire/Alamofire/pull/2903). -- Internal `URLRequest` validation and error. `GET` requests with body data will now produce an error. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2905](https://github.com/Alamofire/Alamofire/pull/2905). -- Generic `Failure` constraint to `DataResponse` and `DownloadResponse`, making them `DataResponse` and `DownloadResponse`. - - Added by [philtre](https://github.com/philtre) in Pull Request [#2893](https://github.com/Alamofire/Alamofire/pull/2893). -- Precondition to ensure `Session` can't be used with background `URLSessionConfiguration`s. Alamofire will explicitly support such functionality at some point in the future. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2917](https://github.com/Alamofire/Alamofire/pull/2917). -- SwiftFormat configuration and updated styling. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2918](https://github.com/Alamofire/Alamofire/pull/2918). -- `AFDataResponse` and `AFDownloadResponse` typealiases to help deal with the doubly generic responses. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2921](https://github.com/Alamofire/Alamofire/pull/2921). - -#### Updated - -- All internal `Result` usage to use the fully qualified type instead of `AFResult`. - - Updated by [philtre](https://github.com/philtre) in Pull Request [#2891](https://github.com/Alamofire/Alamofire/pull/2891). -- `DataRequest` and `DownloadRequest` functional API, renaming `flatMap` to `tryMap`. - - Updated by [philtre](https://github.com/philtre) in Pull Request [#2892](https://github.com/Alamofire/Alamofire/pull/2892). -- `HTTPMethod` to be a struct rather than an enum. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2901](https://github.com/Alamofire/Alamofire/pull/2901). -- All errors produced by Alamofire to be `AFError` by default. All responses will now start with an `AFError` `Failure` type. - - Updated by [philtre](https://github.com/philtre) in Pull Request [#2893](https://github.com/Alamofire/Alamofire/pull/2893). -- `NetworkReachabilityManager` to simplify and modernize its API. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2915](https://github.com/Alamofire/Alamofire/pull/2915). -- `Usage.md` documentation to be fully up-to-date with Alamofire 5. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2895](https://github.com/Alamofire/Alamofire/pull/2895). -- Bundle identifiers to include the platform name, fixing ITMS-90806. - - Updated by [Jonathan](https://github.com/JonMo) in Pull Request [#2928](https://github.com/Alamofire/Alamofire/pull/2928). - -#### Fixed -- Thread-safety issue with serialization queue usage. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2885](https://github.com/Alamofire/Alamofire/pull/2885). - -## [5.0.0-beta.7](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.7) -Released on 2019-07-29. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/57?closed=1). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- `URLEncodedFormEncoder.DataEncoding` and `URLEncodedFormEncoder.KeyEncoding` to customize the encoding of `Data` and `CodingKeys` in `URLEncodedFormEncoder`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2858](https://github.com/Alamofire/Alamofire/pull/2858). -- Asynchronous `cURLDescription` method to produce `cURL` commands for `Request`s which are in the process of creating their initial `URLRequest`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2863](https://github.com/Alamofire/Alamofire/pull/2863). - -#### Updated -- All inline API documentation. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2845](https://github.com/Alamofire/Alamofire/pull/2845). -- Handling of response serializers appended after a `Request` has completed. This no longer produces an error but will instead trigger the normal `Request` lifetime methods. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2862](https://github.com/Alamofire/Alamofire/pull/2862). - -#### Fixed -- Empty parameters being encoded as an empty `String` instead of `nil` by `URLEncodedFormEncoder`. - - Fixed by [David Barry](https://github.com/DavidBarry) in Pull Request [#2818](https://github.com/Alamofire/Alamofire/pull/2818). -- Handling of `os_unfair_lock` to prevent rare crash. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2836](https://github.com/Alamofire/Alamofire/pull/2836). - -## [5.0.0-beta.6](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.6) -Released on 2019-04-23. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/56?closed=1). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Updated -- `ServerTrustEvaluation` logic by simplifying public key equality checks for `SecKey` types. - - Updated by [Aleksandar Vacić](https://github.com/radianttap) in Pull Request [#2800](https://github.com/Alamofire/Alamofire/pull/2800). -- `Request.State` access to lock access and task updates using internal locking API. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2814](https://github.com/Alamofire/Alamofire/pull/2814). - -#### Fixed -- Issues in `DownloadRequest` where some events were being duplicated and some were missing. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2807](https://github.com/Alamofire/Alamofire/pull/2807). -- Issue with AppStore submissions where the pre-release version in the bundle short versions string was being rejected when built with Carthage or as a submodule. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2808](https://github.com/Alamofire/Alamofire/pull/2808). -- Issue where response serializer completions were not called when appended to a completed `Request`. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2810](https://github.com/Alamofire/Alamofire/pull/2810). - -## [5.0.0-beta.5](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.5) -Released on 2019-04-12. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/55). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- `Request.didResumeTaskNotification`, `Request.didSuspendTaskNotification`, `Request.didCancelTaskNotification`, and `Request.didCompleteTaskNotification` notifications. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2803](https://github.com/Alamofire/Alamofire/pull/2803). -- Separate `URLSessionTask` lifetime events to `EventMonitor`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2796](https://github.com/Alamofire/Alamofire/pull/2796). - -#### Updated -- `SessionStateProvider` to no longer be `public` and renamed the file it lives in. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2801](https://github.com/Alamofire/Alamofire/pull/2801). -- `MultipartUpload` to no longer be `public`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2805](https://github.com/Alamofire/Alamofire/pull/2805). -- `Request`, `DataRequest`, `UploadRequest`, and `DownloadRequest` to longer be `open`, as Alamofire does not support subclassing these types. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2804](https://github.com/Alamofire/Alamofire/pull/2804). -- Names of the notifications posted by `Request` to include `Notification`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2803](https://github.com/Alamofire/Alamofire/pull/2803). -- `httpHeaders` extensions on `URLRequest`, `HTTPURLResponse`, and `URLSessionConfiguration` to be `headers` instead. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2802](https://github.com/Alamofire/Alamofire/pull/2802). - -#### Fixed -- Issue in `Request` where calling `cancel()` inside a response serializer would result in the serializer running again. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2778](https://github.com/Alamofire/Alamofire/pull/2778). -- Issue in `Session` where the delegate `precondition` would be triggered when running with a swizzled `URLSessionDelegate`. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2783](https://github.com/Alamofire/Alamofire/pull/2783). -- Compiler error in the example app. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2786](https://github.com/Alamofire/Alamofire/pull/2786). -- Issues `Request` where certain lifetime events could be triggered more than once by repeatedly calling `resume()`, `suspend()`, or `cancel()`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2796](https://github.com/Alamofire/Alamofire/pull/2796) in Regards to Issue [#2759](https://github.com/Alamofire/Alamofire/issues/2759). -- Framework version string to be compatible with TestFlight and AppStore releases. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2799](https://github.com/Alamofire/Alamofire/pull/2799) in Regards to Issue [#2797](https://github.com/Alamofire/Alamofire/issues/2797). - -## [5.0.0-beta.4](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.4) -Released on 2019-03-29. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A5.0.0-beta.4). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- The `AlamofireExtended` protocol and used it to namespace all public extensions. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2758](https://github.com/Alamofire/Alamofire/pull/2758). -- The ability to retry requests after encountering response serialization errors. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2716](https://github.com/Alamofire/Alamofire/pull/2716). - -#### Updated -- The `switch` and `DispatchQueue` logic throughout codebase to simplify usage patterns. - - Updated by [Joan Disho](https://github.com/jdisho) and [Christian Noon](https://github.com/cnoon) in Pull Requests [#2691](https://github.com/Alamofire/Alamofire/pull/2691) and [#2765](https://github.com/Alamofire/Alamofire/pull/2765). -- The `MultipartFormData` data APIs by condensing them using optional parameters. - - Updated by [Ernesto Rivera](https://github.com/rivera-ernesto) in Pull Request [#2766](https://github.com/Alamofire/Alamofire/pull/2766). -- The upload APIs for `MultipartFormData` to support custom boundaries. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2764](https://github.com/Alamofire/Alamofire/pull/2764). -- The Xcode project, source code, SPM package, and podspec to support Swift 5 only. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2771](https://github.com/Alamofire/Alamofire/pull/2771). -- The Alamofire `Result` type to be a new `AFResult` typealias on the new `Swift.Result` type in Swift 5 and removed all public extensions. - - Updated by [Dave Camp](https://github.com/AtomicCat), [Eric Jensen](https://github.com/ejensen), and [Christian Noon](https://github.com/cnoon) in Pull Requests [#2769](https://github.com/Alamofire/Alamofire/pull/2769) and [#2774](https://github.com/Alamofire/Alamofire/pull/2774). - -#### Fixed -- Issue in `RequestInterceptor` closures where callback arguments were not marked as `@escaping`. - - Fixed by [Scott Talbot](https://github.com/cysp) in Pull Request [#2747](https://github.com/Alamofire/Alamofire/pull/2747). -- Issue in response serializers where `emptyResponseAllowed` logic was not working as expected. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2772](https://github.com/Alamofire/Alamofire/pull/2772) in Regards to Issue [#2770](https://github.com/Alamofire/Alamofire/issues/2770). - -## [5.0.0-beta.3](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.3) -Released on 2019-01-07. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A5.0.0-beta.3). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- The `EmptyResponse` protocol, to allow any type to provides values to stand in for an empty response. - - Added by [James Van Noord](https://github.com/jvannoord) in Pull Request [#2664](https://github.com/Alamofire/Alamofire/pull/2664). -- Request and response bodies to `Request`'s `debugDescription`. - - Added by [rain2540](https://github.com/rain2540) in Pull Request [#2700](https://github.com/Alamofire/Alamofire/pull/2700). - -#### Updated -- `Package.swift` for Swift 5 support, moving Swift 4.2 support to `Package@swift-4.2.swift`. - - Updated by [Mattt](https://github.com/mattt) in Pull Requests [#2737](https://github.com/Alamofire/Alamofire/pull/2737) and [#2736](https://github.com/Alamofire/Alamofire/pull/2736). -- Use of `Array` to `Range` in `Request`'s default `acceptableResponseCodes`. - - Updated by [StevenArmandLee](https://github.com/StevenArmandLee) in Pull Request [#2720](https://github.com/Alamofire/Alamofire/pull/2720). -- `RetryPolicy` to allow subclasses to override `retry(_:, for: Session, dueTo:, completion:)`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2713](https://github.com/Alamofire/Alamofire/pull/2713). -- Alamofire's `didResume` notification to `didFinish`, which is now called when a `Request` finished, not when tasks resume. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2728](https://github.com/Alamofire/Alamofire/pull/2728). - -#### Fixed -- `Request`s not finishing when their controlling `Session` is `deinit`d or invalidated. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2728](https://github.com/Alamofire/Alamofire/pull/2728). -- Memory leak when using `validate()` due to reference cycle from implicit `self` capture when using an `@autoclosure`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2728](https://github.com/Alamofire/Alamofire/pull/2728). -- Crash when using `requestDidParseAnyResponse` when using `ClosureEventMonitor`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2740](https://github.com/Alamofire/Alamofire/pull/2740). -- `RetryPolicy` to properly conform to `RequestInterceptor`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2739](https://github.com/Alamofire/Alamofire/pull/2739). -- Typos in documentation. - - Fixed by [Łukasz Mróz](https://github.com/sunshinejr), [Jacob Wood](https://github.com/jacoblukewood), [Paulo Henrique](https://github.com/Cardoso222), and [Todd Lahtinen](https://github.com/toddlahtinen0) in Pull Requests [#2715](https://github.com/Alamofire/Alamofire/pull/2715), [#2725](https://github.com/Alamofire/Alamofire/pull/2725), [#2729](https://github.com/Alamofire/Alamofire/pull/2729), and [#2697](https://github.com/Alamofire/Alamofire/pull/2697). - -## [5.0.0-beta.2](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.2) -Released on 2019-01-07. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A5.0.0-beta.2). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- Support for controlling redirect behavior per `Session` and per `Request` using the `RedirectHandler` protocol. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2699](https://github.com/Alamofire/Alamofire/pull/2699). -- Support for controlling cached response behavior per `Session` and per `Request` using the `CachedResponseHandler` protocol. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2701](https://github.com/Alamofire/Alamofire/pull/2701). -- Support for controlling retry behavior per `Session` and per `Request` using the `RequestInterceptor` protocol. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2704](https://github.com/Alamofire/Alamofire/pull/2704) in regards to Issue [#2241](https://github.com/Alamofire/Alamofire/issues/2241). -- The `Adapter`, `Retrier`, and `Interceptor` types to provide fine grained control of retry behavior. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2704](https://github.com/Alamofire/Alamofire/pull/2704). -- Support for exponential backoff retry policies through the new `RetryPolicy` and `ConnectionLostRetryPolicy` types. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2704](https://github.com/Alamofire/Alamofire/pull/2704). - -#### Updated -- The `RequestRetrier` protocol to take a `RetryResult` in the `completion` closure allowing custom retry errors to be thrown. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request [#2704](https://github.com/Alamofire/Alamofire/pull/2704). -- The `Hashable` implementation on `Request` to use new `hash(into:)` API. - - Updated by [Jeff Kelley](https://github.com/SlaunchaMan) in Pull Request [#2696](https://github.com/Alamofire/Alamofire/pull/2696). - -## [5.0.0-beta.1](https://github.com/Alamofire/Alamofire/releases/tag/5.0.0-beta.1) -Released on 2018-12-06. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A5.0.0.beta-1). **Note:** Alamofire will not be following semantic versioning during the beta process. There may be breaking changes until 5.0.0 is released. - -#### Added -- Support for `Decodable` response serialization with `responseDecodable`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Requests [#2265](https://github.com/Alamofire/Alamofire/pull/2265) and [#2657](https://github.com/Alamofire/Alamofire/pull/2657). -- Support for Brotli `Content-Encoding` in Alamofire's default headers. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2346](https://github.com/Alamofire/Alamofire/pull/2346). -- `HTTPHeaders` type and convenience APIs. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2629](https://github.com/Alamofire/Alamofire/pull/2629). -- Support for `Encodable` parameter types with `JSONParameterEncoder` and `URLEncodedFormParameterEncoder`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2637](https://github.com/Alamofire/Alamofire/pull/2637). -- Customizable empty response handling in response serializers. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2639](https://github.com/Alamofire/Alamofire/pull/2639). -- `EventMonitor` protocol, to tap in to internal Alamofire lifetime events. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- `ServerTrustFailureReason` to `AFError`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2608](https://github.com/Alamofire/Alamofire/pull/2608). -- Asynchronous request creation. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). - -#### Updated -- `ResponseSerializer` and associated protocols' requirements and implementations. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Requests [#2265](https://github.com/Alamofire/Alamofire/pull/2265) and [#2639](https://github.com/Alamofire/Alamofire/pull/2639). -- `RequestAdapter` to allow for asynchronous adaptation. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2628](https://github.com/Alamofire/Alamofire/pull/2628) . -- `SessionManager` to `Session`, with rewritten implementation and API. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- `Request`, `DataRequest`, `UploadRequest`, and `DownloadRequest` with rewritten implementation and API. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- Top level `request` API to be inside a real `AF` namespace enum rather than unnecessary `Alamofire.` usage. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2585](https://github.com/Alamofire/Alamofire/pull/2585). - -#### Removed -- Support for iOS < 10, macOS < 10.12, tvOS < 10, watchOS < 3. - - Removed by [Jon Shier](https://github.com/jshier) in Pull Requests [#2254](https://github.com/Alamofire/Alamofire/pull/2254) and [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- Support for `PropertyListSerialization` and `responsePropertyList`. - - Removed by [Jon Shier](https://github.com/jshier) in Pull Request [#2265](https://github.com/Alamofire/Alamofire/pull/2265). -- Support for `URLSessionStreamTask`. - - Removed by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- Closure override and customization API. - - Removed by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). -- `Timeline` type, as Alamofire now gathers `URLSessionTaskMetrics` for every request. - - Removed by [Jon Shier](https://github.com/jshier) in Pull Request [#2521](https://github.com/Alamofire/Alamofire/pull/2521). - ---- - -## [4.9.1](https://github.com/Alamofire/Alamofire/releases/tag/4.9.1) -Released on 2019-10-26. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/milestone/61?closed=1). - -#### Added -- Support for GitHub Actions for CI. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request [#2979](https://github.com/Alamofire/Alamofire/pull/2979). - -#### Updated -- `DataResponse` and `DownloadResponse` `debugDescription` to include more useful information. - - Updated by [rain2540](https://github.com/rain2540) in Pull Request [#2976](https://github.com/Alamofire/Alamofire/pull/2976). - -#### Fixed -- Dynamic bundle identifier causing issues with Xcode and precompiled binaries by removing the dynamic behavior. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2967](https://github.com/Alamofire/Alamofire/pull/2967). -- Compiler warnings when building for Catalyst by updating the usage of deprecated API. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2979](https://github.com/Alamofire/Alamofire/pull/2979). - -## [4.9.0](https://github.com/Alamofire/Alamofire/releases/tag/4.9.0) -Released on 2019-09-03. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.9.0). - -#### Added -- API to cancel `DownloadRequest`s without producing resume data. - - Added by [ullstrm](https://github.com/ullstrm) in Pull Request [#2851](https://github.com/Alamofire/Alamofire/pull/2851). - -#### Updated -- Bundle identifiers to include the platform name, fixing ITMS-90806. - - Updated by [Jonathan](https://github.com/JonMo) in Pull Request [#2930](https://github.com/Alamofire/Alamofire/pull/2930). - -#### Fixed -- `NetworkReachabilityManager` behavior regression from 4.8.1. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2931](https://github.com/Alamofire/Alamofire/pull/2931). -- Memory leak when using `validate()`. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request [#2931](https://github.com/Alamofire/Alamofire/pull/2931). - -## [4.8.2](https://github.com/Alamofire/Alamofire/releases/tag/4.8.2) -Released on 2019-03-27. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.8.2). - -#### Updated -- Project for compatability with Xcode 10.2. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2767](https://github.com/Alamofire/Alamofire/pull/2767). -- MultipartFormData to have a mutable boundary. - - Updated by [Ondrej Stocek](https://github.com/ondrejstocek) in Pull Request [#2705](https://github.com/Alamofire/Alamofire/pull/2705). - -#### Fixed -- Compatability with SPM from Xcode 10.2. - - Fixed by [Klaas](https://github.com/klaas) in Pull Request [#2762](https://github.com/Alamofire/Alamofire/pull/2762). - -## [4.8.1](https://github.com/Alamofire/Alamofire/releases/tag/4.8.1) -Released on 2019-01-15. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.8.1). - -#### Fixed -- Issue where the network reachability listener closure was not being called immediately when launching an app in airplane mode. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request [#2688](https://github.com/Alamofire/Alamofire/pull/2688) regards to Issues [#2275](https://github.com/Alamofire/Alamofire/issues/2275) and [#2677](https://github.com/Alamofire/Alamofire/issues/2677). - -## [4.8.0](https://github.com/Alamofire/Alamofire/releases/tag/4.8.0) -Released on 2018-11-24. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.8.0). - -#### Added -- Optional encoding completion callback queue for multipart upload. - - Added by [jaltreuter](https://github.com/jaltreuter) in Pull Request [#2620](https://github.com/Alamofire/Alamofire/pull/2620). -- Versioned Swift package manifests. - - Added by [Wanbok Choi (Wayne)](https://github.com/wanbok) in Pull Request [#2621](https://github.com/Alamofire/Alamofire/pull/2621) and [Jon Shier](https://github.com/jshier) in Pull Request [#2648](https://github.com/Alamofire/Alamofire/pull/2648). - -#### Updated -- Project Swift version to 4. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2648](https://github.com/Alamofire/Alamofire/pull/2648). -- Various `Result` methods to be `throw`/`rethrows`. - - Updated by [Stéphane Copin](https://github.com/stephanecopin) in Pull Request [#2488](https://github.com/Alamofire/Alamofire/pull/2488). -- cURL representation implementation readability. - - Updated by [Giulio](https://github.com/giulio92) in Pull Request [#2625](https://github.com/Alamofire/Alamofire/pull/2625). - ---- - -## [4.7.3](https://github.com/Alamofire/Alamofire/releases/tag/4.7.3) -Released on 2018-7-8. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.7.3). - -#### Updated -- Project for Xcode 10 and Swift 4.2 beta versions. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2552](https://github.com/Alamofire/Alamofire/pull/2552). -- Documentation styling and content. - - Updated by [Constantin Lungu](https://github.com/nemesis) in Pull Request [#2505](https://github.com/Alamofire/Alamofire/pull/2505), [Xing He](https://github.com/kukushi) in Pull Request [#2484](https://github.com/Alamofire/Alamofire/pull/2484), and [Karim](https://github.com/karimhm) in Pull Request [#2550](https://github.com/Alamofire/Alamofire/pull/2550). - -## [4.7.2](https://github.com/Alamofire/Alamofire/releases/tag/4.7.2) -Released on 2018-4-15. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.7.2). - -#### Fixed -- Leak of `Requests` after retry. - - Fixed by [Artem Shimankski](https://github.com/mrdepth) in Pull Request [#2412](https://github.com/Alamofire/Alamofire/pull/2412). - -## [4.7.1](https://github.com/Alamofire/Alamofire/releases/tag/4.7.1) -Released on 2018-3-31. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.7.1). - -#### Updated -- Project for Xcode 9.3 and Swift 4.1 release versions. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2473](https://github.com/Alamofire/Alamofire/pull/2473). - -#### Fixed -- Quote escaping in cURL representation. - - Fixed by [Jonah](https://github.com/jonah-williams) in Pull Request [#2474](https://github.com/Alamofire/Alamofire/pull/2474). - -## [4.7.0](https://github.com/Alamofire/Alamofire/releases/tag/4.7.0) -Released on 2018-3-5. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.7.0). - -#### Added -- Open accessibility to `NetworkReachabilityManager` - - Added by [Pär Strindevall](https://github.com/parski) in Pull Request [#2393](https://github.com/Alamofire/Alamofire/pull/2393). -- Configurable parameter encoding for `URLEncoding` - - Added by [Morten Heiberg](https://github.com/heiberg) in Pull Request [#2431](https://github.com/Alamofire/Alamofire/pull/2431). -- Response `Data` to `.DidComplete` notification. - - Added by [Sven Driemecker](https://github.com/svendr) in Pull Request [#2427](https://github.com/Alamofire/Alamofire/pull/2427). -- Radar link for `URLSessionTaskMetrics` bug on watchOS. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request [#2387](https://github.com/Alamofire/Alamofire/pull/2387). - -#### Updated -- Project for Xcode 9.3 and Swift 4.1. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request [#2441](https://github.com/Alamofire/Alamofire/pull/2441). -- OS versions affected by resume data bug. - - Updated by [Aaron Brager](https://github.com/getaaron) in Pull Request [#2389](https://github.com/Alamofire/Alamofire/pull/2389). - -#### Fixed -- Typos in `ResultTests`. - - Fixed by [Aleph Retamal](https://github.com/alaphao) in Pull Request [#2416](https://github.com/Alamofire/Alamofire/pull/2416). - ---- - -## [4.6.0](https://github.com/Alamofire/Alamofire/releases/tag/4.6.0) -Released on 2017-12-3. All issues associated with this milestone can be found using this [filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.6.0). - -#### Added -- Error mapping functions to `Response` types. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request - [#2361](https://github.com/Alamofire/Alamofire/pull/2361). -- Separation of Usage and Advanced Usage docs from README. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request - [#2360](https://github.com/Alamofire/Alamofire/pull/2360). - -#### Updated -- Travis CI and Ruby dependencies. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Requests - [#2361](https://github.com/Alamofire/Alamofire/pull/2361), [#2302](https://github.com/Alamofire/Alamofire/pull/2302), [#2345](https://github.com/Alamofire/Alamofire/pull/2345). -- Swift Package Manager instructions. - - Updated by [Ryosuke Hayashi](https://github.com/hayashikun) in Pull Request - [#2341](https://github.com/Alamofire/Alamofire/pull/2341). - -#### Fixed -- `#session-manager` link in Advanced Usage docs. - - Fixed by [Naeem Shaikh](https://github.com/naeemshaikh90) in Pull Request - [#2373](https://github.com/Alamofire/Alamofire/pull/2373). -- Missing `@discardableResult`. - - Fixed by [Aron Cedercrantz](https://github.com/rastersize) in Pull Request - [#2338](https://github.com/Alamofire/Alamofire/pull/2338). -- Colon placement. - - Fixed by [Issarapong Poesua](https://github.com/Dekablade01) in Pull Request - [#2329](https://github.com/Alamofire/Alamofire/pull/2329). - ---- - -## [4.5.1](https://github.com/Alamofire/Alamofire/releases/tag/4.5.1) -Released on 2017-09-06. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.5.1). - -#### Added -- GitHub templates for issues and pull requests. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request - [#2179](https://github.com/Alamofire/Alamofire/pull/2179). -- Jazzy docs for the release to work with GitHub Pages. - - Added by [Aaron McTavish](https://github.com/aamctustwo) in Pull Request - [#2250](https://github.com/Alamofire/Alamofire/pull/2250). -- Dash support for Jazzy docs. - - Added by [Jon Shier](https://github.com/jshier). - -#### Updated -- The project to work with Xcode 9 beta 6 on Swift 3.2 and 4.0. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#2198](https://github.com/Alamofire/Alamofire/pull/2198). -- The Travis CI config to work with Xcode 9 beta 6. - - Updated by [Jon Shier](https://github.com/jshier). -- The cURL representation logic to no longer force unwrap `URLCredential` values. - - Updated by [Andrey Chernoprudov](https://github.com/achernoprudov) in Pull Request - [#2184](https://github.com/Alamofire/Alamofire/pull/2184). -- The radars section of the README to split out open vs. resolved radars. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#2263](https://github.com/Alamofire/Alamofire/pull/2263). -- The installation section of the README to use the current version. - - Updated by [Kim de Vos](https://github.com/kimdv) in Pull Request - [#2266](https://github.com/Alamofire/Alamofire/pull/2266). - -#### Fixed -- Issue in `TaskDelegate` where task access was not thread safe. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#2190](https://github.com/Alamofire/Alamofire/pull/2190). -- Issue in AF 4 migration guide where supported iOS versions was incorrect. - - Fixed by [Antoine Cœur](https://github.com/Coeur) in Pull Request - [#2212](https://github.com/Alamofire/Alamofire/pull/2212). -- Issue in README sample code where PNG representation API was incorrect. - - Fixed by [Andy Ron](https://github.com/andyRon) in Pull Request - [#2244](https://github.com/Alamofire/Alamofire/pull/2244). -- Swift 3.2+ API warnings for `substring` APIs. - - Fixed by [htinlinn](https://github.com/htinlinn) in Pull Request - [#2240](https://github.com/Alamofire/Alamofire/pull/2240). - -## [4.5.0](https://github.com/Alamofire/Alamofire/releases/tag/4.5.0) -Released on 2017-06-16. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.5.0). - -#### Added -- Missing `@escaping` annotation for session delegate closures. - - Added by [Alexey Aleshkov](https://github.com/djmadcat) in Pull Request - [#1951](https://github.com/Alamofire/Alamofire/pull/1951). -- New `mapError`, `flatMapError`, `withValue`, `withError`, `ifSuccess`, and `ifFailure` APIs to `Result`. - - Added by [Jon Shier](https://github.com/jshier) in Pull Request - [#2135](https://github.com/Alamofire/Alamofire/pull/2135). - -#### Updated -- The Travis config file to Xcode 8.3. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#2059](https://github.com/Alamofire/Alamofire/pull/2059). -- Response serialization implementation to use separate internal variable. - - Updated by [Eunju Amy Sohn](https://github.com/EJSohn) in Pull Request - [#2125](https://github.com/Alamofire/Alamofire/pull/2125). -- `SessionDelegate` internal implementation by removing redundant optional unwrap. - - Updated by [Boris Dušek](https://github.com/dusek) in Pull Request - [#2056](https://github.com/Alamofire/Alamofire/pull/2056). -- The `debugPrintable` implementation of `Request` to use `curl -v` instead of `curl -i` to be more verbose. - - Updated by [Simon Warta](https://github.com/webmaster128) in Pull Request - [#2070](https://github.com/Alamofire/Alamofire/pull/2070). -- The `MultipartFormData` contentType property to be mutable. - - Updated by [Eric Desa](https://github.com/ericdesa) in Pull Request - [#2072](https://github.com/Alamofire/Alamofire/pull/2072). -- Travis CI yaml file to enable watchOS 3.2 builds. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#2135](https://github.com/Alamofire/Alamofire/pull/2135). -- Alamofire to build with Xcode 9 with Swift 3.2 and 4.0 in addition to Xcode 8.3 and Swift 3.1. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#2163](https://github.com/Alamofire/Alamofire/pull/2163). - -#### Removed -- Custom string extension no longer needed in the test suite. - - Removed by [Nicholas Maccharoli](https://github.com/Nirma) in Pull Request - [#1994](https://github.com/Alamofire/Alamofire/pull/1994). - -#### Fixed -- Issue in the `URLProtocolTestCase` where HTTP header capitalization was wrong due to httpbin.org change. - - Fixed by [Natascha Fadeeva](https://github.com/Tanaschita) in Pull Request - [#2025](https://github.com/Alamofire/Alamofire/pull/2025). -- Issues and typos throughout the README documentation and sample code and source code docstrings. - - Fixed by - [Raphael R.](https://github.com/reitzig), - [helloyako](https://github.com/helloyako), - [DongHyuk Kim](https://github.com/sss989870), - [Bas Broek](https://github.com/BasThomas), - [Jorge Lucena](https://github.com/jorgifumi), - [MasahitoMizogaki](https://github.com/MMizogaki), - [José Manuel Sánchez](https://github.com/buscarini), - [SabinLee](https://github.com/SabinLee), - [Mat Trudel](https://github.com/mtrudel), - [Wolfgang Lutz](https://github.com/Lutzifer), and - [Christian Noon](https://github.com/cnoon) in Pull Requests - [#1995](https://github.com/Alamofire/Alamofire/pull/1995), - [#1997](https://github.com/Alamofire/Alamofire/pull/1997), - [#1998](https://github.com/Alamofire/Alamofire/pull/1998), - [#2022](https://github.com/Alamofire/Alamofire/pull/2022), - [#2031](https://github.com/Alamofire/Alamofire/pull/2031), - [#2035](https://github.com/Alamofire/Alamofire/pull/2035), - [#2080](https://github.com/Alamofire/Alamofire/pull/2080), - [#2081](https://github.com/Alamofire/Alamofire/pull/2081), - [#2092](https://github.com/Alamofire/Alamofire/pull/2092), - [#2095](https://github.com/Alamofire/Alamofire/pull/2095), - [#2104](https://github.com/Alamofire/Alamofire/pull/2104). -- Several warnings in the test suite related to Xcode 8.3. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#2057](https://github.com/Alamofire/Alamofire/pull/2057). -- Issue where reachability calculation incorrectly reported `.reachable` status with [`.connectionRequired`, `.isWWAN`] combination. - - Fixed by [Marco Santarossa](https://github.com/MarcoSantarossa) in Pull Request - [#2060](https://github.com/Alamofire/Alamofire/pull/2060). - ---- - -## [4.4.0](https://github.com/Alamofire/Alamofire/releases/tag/4.4.0) -Released on 2017-02-26. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.4.0). - -#### Added -- A new `Alamofire/Alamofire` Gitter channel and also added badge to the README. - - Added by [Christian Noon](https://github.com/cnoon). -- Functional extensions for Result, Data and Download Response. - - Added by [Gwendal Roué](https://github.com/groue) in Pull Request - [#1836](https://github.com/Alamofire/Alamofire/pull/1836). - -### Fixed -- Typo in the README in the Swift Package Manager section. - - Fixed by [Sebastian Limbach](https://github.com/bastilimbach) in Pull Request - [#1918](https://github.com/Alamofire/Alamofire/pull/1918). -- Issue in the "Modifying the Session Configuration" example code of the README where the - `defaultHTTPHeaders` property was called incorrectly. - - Fixed by [Artur Antonov](https://github.com/goingreen) in Pull Request - [#1927](https://github.com/Alamofire/Alamofire/pull/1927). -- Issue in the "Security" section of the README where some example code was outdated. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#1973](https://github.com/Alamofire/Alamofire/pull/1973). -- Issue in the README where the POST request with parameters example was using the wrong method. - - Fixed by [Pablo Bartolome](https://github.com/pbartolome) in Pull Request - [#1984](https://github.com/Alamofire/Alamofire/pull/1984). -- Issue where `taskDidComplete` override closure was not calling task delegate leading to - potential memory leaks. - - Fixed by [Jon Shier](https://github.com/jshier) in regards to Issue - [#1938](https://github.com/Alamofire/Alamofire/pull/1938). - ---- - -## [4.3.0](https://github.com/Alamofire/Alamofire/releases/tag/4.3.0) -Released on 2017-01-15. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.3.0). - -#### Added -- The host and path to router example in README. - - Added by [Michael](https://github.com/muescha) in Pull Request - [#1830](https://github.com/Alamofire/Alamofire/pull/1830). -- A `macOS` disclaimer to download request example in README. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1818](https://github.com/Alamofire/Alamofire/issues/1818). -- New `value` and `error` computed properties to data and download responses. - - Added by [Christian Noon](https://github.com/cnoon) in Pull request - [#1865](https://github.com/Alamofire/Alamofire/pull/1865). -- The HTTP method to the data and download response debug descriptions. - - Added by [Jon Shier](https://github.com/jshier) in Pull request - [#1880](https://github.com/Alamofire/Alamofire/pull/1880). -- A README entry about installing through SPM. - - Added by [Jon Shier](https://github.com/jshier) in Pull request - [#1898](https://github.com/Alamofire/Alamofire/pull/1898). -- The `dependencies` parameter to `Package` file for SPM since it's now required. - - Added by [Arnaldo Capo](https://github.com/cyberdude) in Pull request - [#1905](https://github.com/Alamofire/Alamofire/pull/1905). -- TLS evaluation tests for revoked certs for no policy and default policy. - - Added by [Christian Noon](https://github.com/cnoon). -- New server trust policy for revoked certificates along with matching tests. - - Added by [Wataru Suzuki](https://github.com/WataruSuzuki) in Pull request - [#1822](https://github.com/Alamofire/Alamofire/pull/1822). - -#### Updated -- Project to Xcode 8.2 recommend settings. - - Updated by [Jon Shier](https://github.com/jshier) in Pull request - [#1854](https://github.com/Alamofire/Alamofire/pull/1854). -- The `NetworkReachabilityManager` to have a `public` instead of `open` ACL. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1809](https://github.com/Alamofire/Alamofire/issues/1809). -- The initializers for both default responses public and added metrics parameter. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1865](https://github.com/Alamofire/Alamofire/pull/1865). -- Internals by replacing `syncResult` extension with DispatchQueue `sync`. - - Updated by [Alexander Ignition](https://github.com/Alexander-Ignition) in Pull Request - [#1893](https://github.com/Alamofire/Alamofire/pull/1893). -- TLS tests for tvOS 10.1 and added expiration test for revoked evaluation. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- `DownloadRequest` sample code issue in AF 4 migration guide. - - Fixed by [Luca Torella](https://github.com/lucatorella) in Pull Request - [#1802](https://github.com/Alamofire/Alamofire/pull/1802). -- `URLConvertible` compiler issue in the README example. - - Fixed by [Wu Zhong](https://github.com/zhongwuzw) in Pull Request - [#1844](https://github.com/Alamofire/Alamofire/pull/1844). -- An invalid comment in AF 4 migration guide. - - Fixed by [Tom Brow](https://github.com/brow) in Pull Request - [#1863](https://github.com/Alamofire/Alamofire/pull/1863). -- An issue where the `SessionManager` did not respect retry time delay. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1864](https://github.com/Alamofire/Alamofire/pull/1864) in regards to Issue - [#1853](https://github.com/Alamofire/Alamofire/issues/1853). -- A broken reference link in the README. - - Fixed by [Ulug'bek Ro'zimboyev](https://github.com/ulugbekrozimboyev) in Pull Request - [#1866](https://github.com/Alamofire/Alamofire/pull/1866). -- Compiler issues in `RequestAdapter` and `RequestRetrier` examples in README. - - Fixed by [William Entriken](https://github.com/fulldecent) in Pull Request - [#1916](https://github.com/Alamofire/Alamofire/pull/1916). - ---- - -## [4.2.0](https://github.com/Alamofire/Alamofire/releases/tag/4.2.0) -Released on 2016-11-20. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.2.0). - -#### Added -- Request property overrides to fallback on original task if available. - - Added by [Aron Cedercrantz](https://github.com/rastersize) in Pull Request - [#1792](https://github.com/Alamofire/Alamofire/pull/1792). -- `Timeline` generation to `DefaultDataResponse` and `DefaultDownloadResponse`. - - Added by [Christian Noon](https://github.com/cnoon). -- JSON encoding `encode` method that takes a JSON object along with unit tests. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- The `RequestRetrier` example in the README to safely extract tokens. - - Updated by [Pontus Andersson](https://github.com/pontus-andersson) in Pull Request - [#1794](https://github.com/Alamofire/Alamofire/pull/1794). -- `TaskDelegate` `data` and `error` properties to a `public` ACL. - - Updated by [Christian Noon](https://github.com/cnoon). -- Multipart form data uploads to now delete temp file if encoding fails. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue where `AdaptError` instances were being incorrectly sent to the `RequestRetrier`. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1785](https://github.com/Alamofire/Alamofire/issues/1785). -- Issue where TLS tests were failing on iOS 10.0 and not on iOS 10.1. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [4.1.0](https://github.com/Alamofire/Alamofire/releases/tag/4.1.0) -Released on 2016-11-15. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.1.0). - -#### Added -- Docstrings and a note to the README about `resumeData` and background session behavior. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1553](https://github.com/Alamofire/Alamofire/issues/1553). -- Request `retryCount` property to support the `RequestRetrier`. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1672](https://github.com/Alamofire/Alamofire/issues/1672). - -#### Updated -- SPM package file to exclude tests since current configuration is not supported. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1544](https://github.com/Alamofire/Alamofire/issues/1544). -- An example in the README to use proper error checking in download response handler. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1722](https://github.com/Alamofire/Alamofire/pull/1722). -- Embedded framework installation instructions. - - Updated by [ILI4S K4RIM](https://github.com/ILI4S) in Pull Request - [#1721](https://github.com/Alamofire/Alamofire/pull/1721). -- The AF4 Migration Guide to no longer use `DispatchQueue` internal APIs in the example. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1736](https://github.com/Alamofire/Alamofire/pull/1736). -- The `RequestAdapter` to call the `RequestRetrier` when an `Error` is thrown. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1682](https://github.com/Alamofire/Alamofire/pull/1682). -- The `SessionManager` to clean up the temporary multipart form data file after upload. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1742](https://github.com/Alamofire/Alamofire/issues/1742). -- The deployment targets to **iOS 8.0** and **macOS 10.10**. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1774](https://github.com/Alamofire/Alamofire/pull/1774). -- The Travis CI yaml file to support iOS 8 simulators. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1774](https://github.com/Alamofire/Alamofire/pull/1774). -- The iOS Example app deployment target to iOS 8.0. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1774](https://github.com/Alamofire/Alamofire/pull/1774). - -#### Removed -- Duplicate auto-code signing on macOS. - - Removed by [Christian Noon](https://github.com/cnoon) -- Duplicate code signing identities on various targets. - - Removed by [Christian Noon](https://github.com/cnoon) - -#### Fixed -- A compiler error in response validation sample code in the README. - - Fixed by [Vishrut Shah](https://github.com/vishrutshah) in Pull Request - [#1615](https://github.com/Alamofire/Alamofire/pull/1615). -- Several internal `SessionManager` links that were broken in the README. - - Fixed by [Vishrut Shah](https://github.com/vishrutshah) in Pull Request - [#1625](https://github.com/Alamofire/Alamofire/pull/1625). -- Issue in the sample code of the README where `response.error` was used incorrectly. - - Fixed by [Bob](https://github.com/bot2600) in Pull Request - [#1633](https://github.com/Alamofire/Alamofire/pull/1633). -- Issue in the `ServerTrustPolicy` tests where a `macOS 10.12` check was needed. - - Fixed by [Jon Shier](https://github.com/jshier). -- Compiler issue with `DownloadRequest` in AF4 Migration Guide. - - Fixed by [Wolfgang Lutz](https://github.com/Lutzifer) in Pull Request - [#1670](https://github.com/Alamofire/Alamofire/pull/1670). -- Test target compiler warning by not requiring app extension APIs only. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Typo in the HTTP Headers section of the README. - - Fixed by [Carlos McEvilly](https://github.com/carlosmcevilly) in Pull Request - [#1734](https://github.com/Alamofire/Alamofire/pull/1734). -- Incorrect response type in the response README examples. - - Fixed by [Julien Chaumond](https://github.com/julien-c) in Pull Request - [#1760](https://github.com/Alamofire/Alamofire/pull/1760). -- Xcode 8.1 compiler warnings and project suggestions. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#1735](https://github.com/Alamofire/Alamofire/pull/1735). -- Issue where download completion could crash on a `nil` response. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#1723](https://github.com/Alamofire/Alamofire/pull/1723). -- Issue in TLS tests where root certificate was missing from server trust. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [4.0.1](https://github.com/Alamofire/Alamofire/releases/tag/4.0.1) -Released on 2016-09-24. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.0.1). - -#### Added -- The `OS_ACTIVITY_MODE` environment variable to iOS, tvOS and iOS Example. - - Added by [Christian Noon](https://github.com/cnoon). -- Test verifying download request can be resumed with resume data. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- All instances of `com.alamofire` with `org.alamofire` throughout the project. - - Updated by [Christian Noon](https://github.com/cnoon). -- Project by adding `.swift-version` file and re-enabling `pod lib lint` in Travis file. - - Updated by [Thibault Vlacich](https://github.com/ThibaultVlacich) in Pull Request - [#1534](https://github.com/Alamofire/Alamofire/pull/1534). -- The entire project to use `macOS` in place of `OS X`. - - Updated by [Justin Jia](https://github.com/JustinJiaDev) in Pull Request - [#1520](https://github.com/Alamofire/Alamofire/pull/1520). -- Framework and test target override settings that duplicated the project settings. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue where the test suite was accidentally deleting contents of `~/Library/Application Support` - on macOS. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1512](https://github.com/Alamofire/Alamofire/issues/1512). -- Typo in the migration guide around availability checks. - - Fixed by [Alexsander Akers](https://github.com/a2) in Pull Request - [#1510](https://github.com/Alamofire/Alamofire/pull/1510). -- Typo in the README around response handlers. - - Fixed by [Glenn R. Fisher](https://github.com/glennrfisher) in Pull Request - [#1515](https://github.com/Alamofire/Alamofire/pull/1515). -- Issue in the download example in the README where a `to` parameter was missing. - - Fixed by [Julien Colin](https://github.com/Toldy) in Pull Request - [#1532](https://github.com/Alamofire/Alamofire/pull/1532). -- Issue in `AFError` where wrong case was used in several property implementations. - - Fixed by [Victor Chee](https://github.com/victorchee) in Pull Request - [#1558](https://github.com/Alamofire/Alamofire/pull/1558). -- Typo in AF 4 migration guide where "enhancements" was spelled incorrectly. - - Fixed by [YeralYamil](https://github.com/YeralYamil) in Pull Request - [#1590](https://github.com/Alamofire/Alamofire/pull/1590). -- Typo in code sample documentation where "already" was misspelled. - - Fixed by [Fuad Kamal](https://github.com/abunur) in Pull Request - [#1599](https://github.com/Alamofire/Alamofire/pull/1599). -- Typos in the Open Radars and Donations sections of README. - - Fixed by [Brian Lu](https://github.com/bakemecookies) in Pull Request - [#1606](https://github.com/Alamofire/Alamofire/pull/1606). -- Issue in `DispatchQueue` extension where `Foundation` needed to be imported for submodules. - - Fixed by [CodeEagle](https://github.com/CodeEagle) in Pull Request - [#1603](https://github.com/Alamofire/Alamofire/pull/1603). -- Memory leak in `Validation` closures where reference to `self` was causing retain cycle. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1551](https://github.com/Alamofire/Alamofire/issues/1551). -- Compilation issue in response handler section of the README. - - Fixed by [Vishrut Shah](https://github.com/vishrutshah) in Pull Request - [#1612](https://github.com/Alamofire/Alamofire/pull/1612). - -## [4.0.0](https://github.com/Alamofire/Alamofire/releases/tag/4.0.0) -Released on 2016-09-11. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.0.0). - -#### Added -- Internal `DispatchQueue` extension set of convenience properties and methods. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1450](https://github.com/Alamofire/Alamofire/pull/1450). -- `RequestAdapter` and `RequestRetrier` protocols allowing requests to be retried. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1450](https://github.com/Alamofire/Alamofire/pull/1450). -- `RequestAdapter` tests on all testable `SessionManager` request APIs. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1450](https://github.com/Alamofire/Alamofire/pull/1450). -- Added an `Adapting and Retrying Requests` section to the README. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1450](https://github.com/Alamofire/Alamofire/pull/1450). -- `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` subclasses. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- Top-level APIs for creating `StreamRequest` instances. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- Extra `responseToSelector` overrides for stream delegate APIs. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- A new `syncResult` extension to `DispatchQueue` to simplify thread-safe locking. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- Two serialization failure reasons to support download response serializers. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1457](https://github.com/Alamofire/Alamofire/pull/1457). -- Download response serialization tests for all serializer types. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1457](https://github.com/Alamofire/Alamofire/pull/1457). -- The `dataFileNil` and `dataFileReadFailed` cases to `ResponseValidationFailureReason`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1461](https://github.com/Alamofire/Alamofire/pull/1461). -- The `isWildcard` property to MIMEType struct for convenience. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1461](https://github.com/Alamofire/Alamofire/pull/1461). -- Missing `CustomDebugStringCovertible` conformance to `DownloadResponse`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- URL variants to the `FileManager` extension in the test suite. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- `DownloadOptions` option set to make moving files more robust. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- Tests validating success and failure scenarios for `DownloadOptions`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- Parameter encoding failure docstrings and refactored reasons to be consistent. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1465](https://github.com/Alamofire/Alamofire/pull/1465). -- Safeguards to url parameter encoding when extracting the url request’s url. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1465](https://github.com/Alamofire/Alamofire/pull/1465). -- The new `URLSessionTaskMetrics` to all `Response types`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1492](https://github.com/Alamofire/Alamofire/pull/1492). -- The Alamofire 4.0 Migration Guide to the README. - - Added by [Christian Noon](https://github.com/cnoon). -- `HTTPHeaders` typealias for top-level API convenience. - - Added by [Christian Noon](https://github.com/cnoon). -- Complete safeguards to `URLStringConvertible`, `URLRequestConvertible` and `RequestAdapter`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). -- Tests around invalidURL error cases for `Request` creation and adaptation. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). - -#### Updated -- The `authorizationHeader` static method over to returning optional tuple. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- `SessionManager` queues to each have a unique name using a UUID suffix. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- The progress tracking system across all `Request` subclasses to improve accuracy. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1455](https://github.com/Alamofire/Alamofire/pull/1455). -- `BaseTestCase` to delete contents of common directories at the start of each test. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1457](https://github.com/Alamofire/Alamofire/pull/1457). -- Response handler extensions by moving them into `DataRequest` and added equivalents - for `DownloadRequest`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1457](https://github.com/Alamofire/Alamofire/pull/1457). -- The response serializer types to use the `Protocol` suffix. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1457](https://github.com/Alamofire/Alamofire/pull/1457). -- `Validation` typealias to include response data in a `DataRequest` type. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1461](https://github.com/Alamofire/Alamofire/pull/1461). -- `Validation` typealias to include temporary and destination URLs in a `DownloadRequest` type. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1461](https://github.com/Alamofire/Alamofire/pull/1461). -- `SessionManager` APIs to all leverage `TaskConvertible` conformance. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1461](https://github.com/Alamofire/Alamofire/pull/1461). -- `DownloadFileDestination` closures to be optional on top-level `DownloadRequest` APIs. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- The `request` and `download` APIs now default to `.get` method and `upload` defaults to `.post`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1462](https://github.com/Alamofire/Alamofire/pull/1462). -- The `ParameterEncoding` encode API to throw instead of returning tuple. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1465](https://github.com/Alamofire/Alamofire/pull/1465). -- The `TaskDelegate` to only store the url session task error if `error` is `nil`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1465](https://github.com/Alamofire/Alamofire/pull/1465). -- `ParameterEncoding` enum by switching to a protocol backed by url, json and plist structs. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1465](https://github.com/Alamofire/Alamofire/pull/1465). -- Updated RequestRetrier completion to be escaping. - - Updated by [Aron Cedercrantz](https://github.com/rastersize) in Pull Request - [#1489](https://github.com/Alamofire/Alamofire/pull/1489). -- Code signing to automatic with no team on framework, test and app targets. - - Updated by [Christian Noon](https://github.com/cnoon). -- README for Swift 3 and Alamofire 4 along with reorganization. - - Updated by [Christian Noon](https://github.com/cnoon). -- README with improved `Error` examples as well as typo and whitespace fixes. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1504](https://github.com/Alamofire/Alamofire/pull/1504). -- `Request` task property is now optional allowing errors to propagate through. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). -- The Travis-CI device list in the yaml file. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). -- The top-level APIs by removing external `resource` parameter name. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). -- The `URLStringCovertible` by renaming to `URLConvertible` and removed protocol property. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). -- The README and migration guide with the `URLConvertible` and top-level API changes. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1505](https://github.com/Alamofire/Alamofire/pull/1505). - -#### Removed -- Unnecessary `public` ACL declarations on `AFError` extensions. - - Removed by [Christian Noon](https://github.com/cnoon). -- `URLStringConvertible` conformance on `URLRequest`. - - Removed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1491](https://github.com/Alamofire/Alamofire/pull/1491). -- Removed `downloadProgress` and `uploadProgress` Int64 variants. - - Removed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1467](https://github.com/Alamofire/Alamofire/issues/1467) reported by - [thebluepotato](https://github.com/thebluepotato). -- Duplicated change log message in the migration guide. - - Removed by [Justin Jia](https://github.com/JustinJiaDev) in Pull Request - [#1503](https://github.com/Alamofire/Alamofire/pull/1503). -- Code coverage generation by default to improve test suite stability. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Fixed `URLEncoding` issue around `NSNumber` parameter encoding. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1458](https://github.com/Alamofire/Alamofire/issues/1458) reported by - [Dhanush Balachandran](https://github.com/dhanushram). -- Issue where `MultipartFormData` temp directory creation needed to be done serially. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1333](https://github.com/Alamofire/Alamofire/issues/1333) reported by - [Fernando Mazzon](https://github.com/fer662). -- Issue in resume data tests where request was being cancelled multiple times. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [4.0.0-beta.2](https://github.com/Alamofire/Alamofire/releases/tag/4.0.0-beta.2) -Released on 2016-08-29. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.0.0-beta.2). - -#### Fixed -- Build issue with `Manager` class due to cherry picked change that merged incorrectly. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1438](https://github.com/Alamofire/Alamofire/pull/1438). - -## [4.0.0-beta.1](https://github.com/Alamofire/Alamofire/releases/tag/4.0.0-beta.1) -Released on 2016-08-28. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A4.0.0-beta.1). - -#### Added -- `discardableResult` annotations to all top-level Request APIs. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- All source, test and example logic as well as project settings to compile against - the Xcode 8 beta releases. - - Updated by [Kevin Harwood](https://github.com/kcharwood), - [Jon Shier](https://github.com/jshier) and - [Christian Noon](https://github.com/cnoon). -- Deployment targets to iOS 9.0, macOS 10.11, tvOS 9.0 and watchOS 2.0. - - Updated by [Christian Noon](https://github.com/cnoon). -- Notifications to use nested structs inside `Notification.Name` namespace. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `Manager` class to `SessionManager` to be more descriptive. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1385](https://github.com/Alamofire/Alamofire/pull/1385). -- The `SessionDelegate`, `TaskDelegate` and subclasses by pulling them into the global namespace. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1385](https://github.com/Alamofire/Alamofire/pull/1385). -- All the Core APIs and documentation to match Swift 3 API design guidelines. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1385](https://github.com/Alamofire/Alamofire/pull/1385). -- The `SessionDelegate` to store `Request` instances internally to prepare for retry logic. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1391](https://github.com/Alamofire/Alamofire/pull/1391). -- The podspec to 4.0.0-beta.1 and bumped the deployment targets. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1401](https://github.com/Alamofire/Alamofire/pull/1401). -- The parameter order of custom `URLRequest` initializer to match other APIs. - - Updated by [Christian Noon](https://github.com/cnoon). -- The travis yaml file for Xcode 8. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `Error` enum to `AFError` which now conforms to the new `Error` protocol. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1419](https://github.com/Alamofire/Alamofire/pull/1419). - -#### Fixed -- Typo in a parameter name in the `MultipartFormData` Swift 3 API refactor. - - Fixed by [Joshua Hudson](https://github.com/jhudsonWA) in Pull Request - [#1395](https://github.com/Alamofire/Alamofire/pull/1395). - -#### Upgrade Notes -This release requires Xcode 8.0 beta 6+ because it has been completely refactored to compile against Swift 3.0. Any older versions of Xcode will **NOT COMPILE**. - -This release is the start of the Alamofire 4.0.0 beta releases. We still have quite a few large changes we're trying to squeeze in before the Xcode 8 GM drops, so the APIs will continue to change over the next few weeks. Please keep in mind that each beta will likely bring new APIs and also refactor others. The betas **WILL NOT** follow semantic versioning. We'll most likely conform to semantic versioning once we start releasing the RCs unless we run into a major unforeseen issue. - -We'd really appreciate everyone trying out the betas and letting us know if you find issues. We want to address every possible issue prior to the official Alamofire 4.0.0 release. - ---- - -## [3.5.1](https://github.com/Alamofire/Alamofire/releases/tag/3.5.1) -Released on 2016-10-01. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.5.1). - -#### Fixed -- Assorted memory leaks caused by underlying Swift runtime bugs. - - Fixed by [Jon Shier](https://github.com/jshier) in regards to Issue - [#1626](https://github.com/Alamofire/Alamofire/issues/1626). -- Issue in the test suite logic on macOS 10.12. - - Fixed by [Jon Shier](https://github.com/jshier). - -## [3.5.0](https://github.com/Alamofire/Alamofire/releases/tag/3.5.0) -Released on 2016-09-07. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.5.0). - -#### Updated -- The `User-Agent` header generation formatting and also added docs and tests. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1456](https://github.com/Alamofire/Alamofire/pull/1456) in regards to Issue - [#1452](https://github.com/Alamofire/Alamofire/issues/1452). -- All source, test and example logic as well as project settings to compile against - Xcode 7 and 8 against Swift 2.2 or 2.3 respectively. - - Updated by [Kevin Harwood](https://github.com/kcharwood), - [Jon Shier](https://github.com/jshier) and - [Christian Noon](https://github.com/cnoon). -- The Travis CI yaml file to support both Xcode 7.3 and 8 simultaneously. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- A TLS evaluation test that could fail with a different error when behind a proxy. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [3.4.2](https://github.com/Alamofire/Alamofire/releases/tag/3.4.2) -Released on 2016-08-28. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.4.2). - -#### Added -- Added Cleanup Whitespace target to remove excess whitespace from Swift files. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- All TLS evaluation tests from `disig.sk` to `badssl.com` to be more reliant and robust. - - Updated by [Christian Noon](https://github.com/cnoon). -- Internal `URLRequest` method to maintain mutable variant data on an `NSURLRequest` passed - into the top-level APIs. - - Updated by [Greedwolf DSS](https://github.com/passchaos) in Pull Request - [#1330](https://github.com/Alamofire/Alamofire/pull/1330). -- The `User-Agent` header to include version and build numbers. - - Updated by [Sergey Demchenko](https://github.com/antrix1989) in Pull Request - [#1420](https://github.com/Alamofire/Alamofire/pull/1420). - -#### Removed -- All excess whitespace from Swift files using the `Cleanup Whitespace` target. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- `Request` debug description tests to no longer require parameters in a specific order. - - Fixed by [Marius Serban](https://github.com/marius-serban) in Pull Request - [#1318](https://github.com/Alamofire/Alamofire/pull/1318). -- Small ACL issue in code sample of the Handling Errors section of the README. - - Fixed by [Adrian Brink](https://github.com/adrianbrink) in Pull Request - [#1315](https://github.com/Alamofire/Alamofire/pull/1315). - -## [3.4.1](https://github.com/Alamofire/Alamofire/releases/tag/3.4.1) -Released on 2016-06-12. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.4.1). - -#### Added -- Rdar `26761490` to the list of rdars affecting Alamofire. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1262](https://github.com/Alamofire/Alamofire/pull/1262). -- A new `debugDescription` test for a MultipartFormData Request with duplicate headers. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1303](https://github.com/Alamofire/Alamofire/issues/1303). - -#### Updated -- CocoaPod installation instructions in README to be compatible with 1.x. - - Updated by [Luis Ferro](https://github.com/lferro9000) in Pull Request - [#1288](https://github.com/Alamofire/Alamofire/pull/1288). -- The README to reflect the best error practices in response serializers. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1273](https://github.com/Alamofire/Alamofire/pull/1273). -- The generation of the `User-Agent` header to use non-localized sources. - - Updated by [Jon Shier](https://github.com/jshier) in Pull Request - [#1292](https://github.com/Alamofire/Alamofire/pull/1292) in regards to Issue - [#1269](https://github.com/Alamofire/Alamofire/pull/1269). -- The `Generic Response Object Serialization` section of the README to use protocol extension. - - Updated by [Raphael Oliveira](https://github.com/raphaeloliveira) in Pull Request - [#1257](https://github.com/Alamofire/Alamofire/pull/1257). -- Reachability by removing explicit IPv6 logic since OS handles this automatically. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1308](https://github.com/Alamofire/Alamofire/pull/1308) in regards to Issue - [#1228](https://github.com/Alamofire/Alamofire/pull/1228). -- Host manager reachability test to use different hostname to improve test reliability. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1308](https://github.com/Alamofire/Alamofire/pull/1308). - -#### Removed -- `ReleaseTest` configuration and updated Travis-CI yaml file to enable testability directly. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Memory leak in `Timeline` description and debugDescription due to string interpolation. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1262](https://github.com/Alamofire/Alamofire/issues/1262) in regards to Issue - [#1232](https://github.com/Alamofire/Alamofire/issues/1232). - -## [3.4.0](https://github.com/Alamofire/Alamofire/releases/tag/3.4.0) -Released on 2016-05-08. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.4.0). - -#### Added -- Status code and content type values into validation `NSError` userInfo dictionaries. - - Added by [Cédric Luthi](https://github.com/0xced) in Pull Request - [#1166](https://github.com/Alamofire/Alamofire/pull/1166). -- New `authorizationHeader` API to generate base64 encoded authorization header. - - Added by [Cédric Luthi](https://github.com/0xced) in Pull Request - [#1187](https://github.com/Alamofire/Alamofire/pull/1187). - -#### Updated -- URLProtocol tests to demonstrate using `NSURLProtocol` with `NSURLSession`. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1160](https://github.com/Alamofire/Alamofire/issues/1160). -- The `SesionDelegate` to no longer be `final` to allow subclassing. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1172](https://github.com/Alamofire/Alamofire/issues/1172) in regards to Issue - [#1145](https://github.com/Alamofire/Alamofire/issues/1145). -- The `SessionDelegate` subscript public to allow full control when subclassing. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1172](https://github.com/Alamofire/Alamofire/issues/1172). -- The `Response Serialization` section of the README to include validation examples. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1213](https://github.com/Alamofire/Alamofire/issues/1213). -- The delegate guard in the `Manager` initializer in front of property assignment. - - Updated by [Broccoliii](https://github.com/broccolii) in Pull Request - [#1226](https://github.com/Alamofire/Alamofire/issues/1226). -- Header example in the README to use `Accept` header instead of `Content-Type`. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Pull Request - [#1229](https://github.com/Alamofire/Alamofire/issues/1229). - -#### Deprecated -- The `errorWithCode` APIs and updated NSURLError* domains to `NSURLErrorDomain`. - - Deprecated by [Cédric Luthi](https://github.com/0xced) in Pull Request - [#1166](https://github.com/Alamofire/Alamofire/pull/1166). - -#### Fixed -- Issue where Requests with invalid credentials were not terminating with 401 status code. - - Fixed by [Cédric Luthi](https://github.com/0xced) in Pull Request - [#1164](https://github.com/Alamofire/Alamofire/pull/1164) in regards to Issue - [#1159](https://github.com/Alamofire/Alamofire/issues/1159). -- Issue in URLProtocol test where config headers are not passed prior to iOS 9.0. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Issue where Request `cURLRepresentation` method was not coalescing duplicate headers. - - Fixed by [Chris Richards](https://github.com/chrisrichards) in Pull Request - [#1186](https://github.com/Alamofire/Alamofire/pull/1186) in regards to Issue - [#1184](https://github.com/Alamofire/Alamofire/issues/1184). -- Issue where incorrect dash in License file was breaking markdown parsing. - - Fixed by [Gemma Barlow](https://github.com/gemmakbarlow) in Pull Request - [#1218](https://github.com/Alamofire/Alamofire/issues/1218). -- Issue where internal quotes were not escaped correctly in cURL output. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [3.3.1](https://github.com/Alamofire/Alamofire/releases/tag/3.3.1) -Released on 2016-04-06. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.3.1). - -#### Added -- Tests for the `SessionDelegate` redirect with completion override closure. - - Added by [Kevin Harwood](https://github.com/kcharwood) in Pull Request - [#1141](https://github.com/Alamofire/Alamofire/issues/1141). -- Tests for all the `SessionDelegate` override closures. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- The authentication test cases to clear out all cookies to help stabilize Travis-CI. - - Updated by [Christian Noon](https://github.com/cnoon). -- The cache test check for no store header to use availability checks. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- The `respondsToSelector` check for the new HTTP redirect closure with completion. - - Fixed by [Kevin Harwood](https://github.com/kcharwood) in Pull Request - [#1141](https://github.com/Alamofire/Alamofire/issues/1141) in regards to Issue - [#1140](https://github.com/Alamofire/Alamofire/issues/1140). -- Issue where the challenge and response `SessionDelegate` override closures were not called. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Typo in the Travis YAML file that was causing all tests to always fail on iOS 9.1. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Race condition in the cache tests that was causing random failures on Travis-CI. - - Fixed by [Christian Noon](https://github.com/cnoon). - -## [3.3.0](https://github.com/Alamofire/Alamofire/releases/tag/3.3.0) -Released on 2016-03-23. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.3.0). - -#### Added -- Added override closures for all `SessionDelegate` APIs with completion handlers. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1099](https://github.com/Alamofire/Alamofire/pull/1099). - -#### Updated -- The `User-Agent` header implementation to use more aggressive type-safety checks. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1100](https://github.com/Alamofire/Alamofire/issues/1100). -- All shared response serializers to accept a custom queue for execution. - - Updated by [Luca Torella](https://github.com/lucatorella) in Pull Request - [#1112](https://github.com/Alamofire/Alamofire/pull/1112). -- The network reachability manager to use IPv4 on iOS 8.x and OSX 10.9.x. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#1086](https://github.com/Alamofire/Alamofire/issues/1086). -- All source, test and example code to compile against Swift 2.2. - - Updated by [James Barrow](https://github.com/Baza207) and [Dominik Hadl](https://github.com/nickskull) in Pull Requests - [#1030](https://github.com/Alamofire/Alamofire/pull/1030) and - [#1128](https://github.com/Alamofire/Alamofire/pull/1128). -- The Travis CI YAML file to use Xcode 7.3 and also updated matrix targets. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue in JSON response serialization test case where the wrong serializer was being tested. - - Fixed by [Gregory J.H. Rho](https://github.com/topchul) in Pull Request - [#1108](https://github.com/Alamofire/Alamofire/pull/1108). -- Issue where multipart form data encoding was unnecessarily scheduling input and output - streams with the current runloop. - - Fixed by [Brian King](https://github.com/KingOfBrian) in Pull Request - [#1121](https://github.com/Alamofire/Alamofire/pull/1121). - -#### Upgrade Notes -This release requires Xcode 7.3+ otherwise the Swift 2.2 changes will **NOT COMPILE**. There are several reasons why this was deployed as a MINOR and not MAJOR release. First off, the public API changes of this release are fully backwards compatible. There are no breaking API changes in the public APIs. Strictly following semver dictates that this is a MINOR, not MAJOR release. - -> See [semver](https://semver.org/#semantic-versioning-specification-semver) for more info. - -We also realize that this can be frustrating for those out there not ready to upgrade to Xcode 7.3. Please know that we consider each release version carefully before deploying. Our decision to bump the MINOR version was not only due to strictly following semver, but also because it's difficult and undesirable for all OSS libraries to bump MAJOR versions each time the Swift APIs are incremented. Alamofire would have had to go through 6 additional MAJOR versions if this was the policy. That would mean we'd already be running on Alamofire 10.x. Incrementing MAJOR versions this quickly is disruptive to the community and would cause even more confusion. Instead, we try to carefully plan our MAJOR version releases and accompany them with detailed Migration Guides to help make the transition as smooth as possible. - -If anyone has additional questions, please feel free to open an issue and we'll be more than happy to discuss further. - ---- - -## [3.2.1](https://github.com/Alamofire/Alamofire/releases/tag/3.2.1) -Released on 2016-02-27. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.2.1). - -#### Updated -- `StringResponseSerializer` implementation to build with the latest Swift toolchain. - - Updated by [Chris Cieslak](https://github.com/vivid-cieslak) in Pull Request - [#1050](https://github.com/Alamofire/Alamofire/pull/1050). -- Expanded the Component Libraries section and moved it up in the README. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue where JSON and plist custom content types were not retained during parameter encoding. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1088](https://github.com/Alamofire/Alamofire/pull/1088). - -## [3.2.0](https://github.com/Alamofire/Alamofire/releases/tag/3.2.0) -Released on 2016-02-07. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.2.0). - -#### Added -- Notifications that post when an `NSURLSessionTask` changes state to allow support for the - network activity indicator. - - Added by [Christian Noon](https://github.com/cnoon). -- `Timeline` struct to capture timings throughout the lifecycle of a `Request`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1054](https://github.com/Alamofire/Alamofire/issues/1054). -- A new `Timeline` section to the README. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1054](https://github.com/Alamofire/Alamofire/issues/1054). -- `NetworkReachabilityManager` to listen for reachability status changes. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1053](https://github.com/Alamofire/Alamofire/issues/1053). -- Unit tests for all the testable network reachability manager APIs. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1053](https://github.com/Alamofire/Alamofire/issues/1053). -- A new `Network Reachability` section to the README. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#1053](https://github.com/Alamofire/Alamofire/issues/1053). - -#### Updated -- The `NSURLSessionStream` APIs to support `tvOS`. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `ParameterEncoding` encode method to allow empty parameters to still be encoded. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issues - [#1032](https://github.com/Alamofire/Alamofire/issues/1032) and - [#1049](https://github.com/Alamofire/Alamofire/issues/1049). - -#### Fixed -- Broken CocoaDocs generation by moving iOS Example project into Examples folder. - - Fixed by [Jon Shier](https://github.com/jshier) in Pull Request - [#1027](https://github.com/Alamofire/Alamofire/issues/1027) in regards to Issue - [#1025](https://github.com/Alamofire/Alamofire/issues/1025). - ---- - -## [3.1.5](https://github.com/Alamofire/Alamofire/releases/tag/3.1.5) -Released on 2016-01-17. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.5). - -#### Added -- `Package.swift` to the project to support Swift Package Manager (SPM). - - Added by [Kyle Fuller](https://github.com/kylef) in Pull Request - [#979](https://github.com/Alamofire/Alamofire/pull/979). -- Safeguards to the `Request` class's `debugDescription` property. - - Added by [tokorom](https://github.com/tokorom) in Pull Request - [#983](https://github.com/Alamofire/Alamofire/pull/983). - -#### Updated -- `Accept-Language` header generation to use functional style. - - Updated by [Dapeng Gao](https://github.com/dapenggao) in Pull Request - [#982](https://github.com/Alamofire/Alamofire/pull/982). -- `Accept-Encoding` and `Accept-Language` header values to have separator spaces between values. - - Updated by [Christian Noon](https://github.com/cnoon). -- Copyright headers to include 2016! 🎉🎉🎉 - - Updated by [Christian Noon](https://github.com/cnoon). - -## [3.1.4](https://github.com/Alamofire/Alamofire/releases/tag/3.1.4) -Released on 2015-12-16. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.4). - -#### Added -- `NSTemporaryExceptionMinimumTLSVersion` documentation to the ATS section in the README. - - Added by [Marandon Antoine](https://github.com/ntnmrndn) in Pull Request - [#952](https://github.com/Alamofire/Alamofire/pull/952). -- Added `ReleaseTest` configuration to allow running tests against optimized build. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- Carthage instructions in the README to clearly callout the `carthage update` command. - - Updated by [vlad](https://github.com/vlastachu) in Pull Request - [#955](https://github.com/Alamofire/Alamofire/pull/955). -- `ParameterEncoding` to early out when passed an empty parameters dictionary. - - Updated by [Anthony Miller](https://github.com/AnthonyMDev) in Pull Request - [#954](https://github.com/Alamofire/Alamofire/pull/954). -- The `certificatesInBundle` to support `cer`, `crt` and `der` extensions. - - Updated by [Jacob Jennings](https://github.com/jacobjennings) in Pull Request - [#956](https://github.com/Alamofire/Alamofire/pull/956). -- The `ENABLE_TESTABILITY` flag to `NO` for Release configuration and disabled tests for - non-test builds to better support Carthage. - - Updated by [Jed Lewison](https://github.com/jedlewison) in Pull Request - [#953](https://github.com/Alamofire/Alamofire/pull/953). -- The server certificates for the TLS tests and added all certificates to all test targets. - - Updated by [Christian Noon](https://github.com/cnoon). -- The Travis-CI configuration to Xcode 7.2, iOS 9.2, tvOS 9.1 and watchOS 2.1. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Removed -- `SecCertificate` array Swift workaround in `ServerTrustPolicy` for Xcode 7.2. - - Removed by [Christian Noon](https://github.com/cnoon). - -## [3.1.3](https://github.com/Alamofire/Alamofire/releases/tag/3.1.3) -Released on 2015-11-22. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.3). - -#### Added -- Custom `Info.plist` for tvOS setting the `UIRequiredDeviceCapabilities` to `arm64`. - - Added by [Simon Støvring](https://github.com/simonbs) in Pull Request - [#913](https://github.com/Alamofire/Alamofire/pull/913). - -#### Updated -- All code samples in the README to use `https` instead of `http`. - - Updated by [Tomonobu Sato](https://github.com/tmnb) in Pull Request - [#912](https://github.com/Alamofire/Alamofire/pull/912). - -## [3.1.2](https://github.com/Alamofire/Alamofire/releases/tag/3.1.2) -Released on 2015-11-06. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.2). - -#### Updated -- Code signing on iOS simulator builds to not sign simulator builds. - - Updated by [John Heaton](https://github.com/JRHeaton) in Pull Request - [#903](https://github.com/Alamofire/Alamofire/pull/903). -- Code signing on watchOS and tvOS simulators builds to not sign simulator builds. - - Updated by [Christian Noon](https://github.com/cnoon). - -## [3.1.1](https://github.com/Alamofire/Alamofire/releases/tag/3.1.1) -Released on 2015-10-31. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.1). - -#### Added -- Support for 204 response status codes in the response serializers. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#889](https://github.com/Alamofire/Alamofire/pull/889). -- ATS section to the README explaining how to configure the settings. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#876](https://github.com/Alamofire/Alamofire/issues/876). - -#### Updated -- Several unnecessary uses of `NSString` with `String`. - - Updated by [Nicholas Maccharoli](https://github.com/Nirma) in Pull Request - [#885](https://github.com/Alamofire/Alamofire/pull/885). -- Content type validation to always succeeds when server data is `nil` or zero length. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#890](https://github.com/Alamofire/Alamofire/pull/890). - -#### Removed -- The mention of rdar://22307360 from the README since Xcode 7.1 has been released. - - Removed by [Elvis Nuñez](https://github.com/3lvis) in Pull Request - [#891](https://github.com/Alamofire/Alamofire/pull/891). -- An unnecessary availability check now that Xcode 7.1 is out of beta. - - Removed by [Christian Noon](https://github.com/cnoon). -- The playground from the project due to instability reasons. - - Removed by [Christian Noon](https://github.com/cnoon). -- The data length checks in the `responseData` and `responseString` serializers. - - Removed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#889](https://github.com/Alamofire/Alamofire/pull/889). - -## [3.1.0](https://github.com/Alamofire/Alamofire/releases/tag/3.1.0) -Released on 2015-10-22. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.1.0). - -#### Added -- New tvOS framework and test targets to the project. - - Added by [Bob Scarano](https://github.com/bscarano) in Pull Request - [#767](https://github.com/Alamofire/Alamofire/pull/767). -- The tvOS deployment target to the podspec. - - Added by [Christian Noon](https://github.com/cnoon). -- The `BITCODE_GENERATION_MODE` user defined setting to tvOS framework target. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- The README to include tvOS and bumped the required version of Xcode. - - Updated by [Christian Noon](https://github.com/cnoon). -- The default tvOS and watchOS deployment targets in the Xcode project. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `APPLICATION_EXTENSION_API_ONLY` enabled flag to `YES` in the tvOS framework target. - - Updated by [James Barrow](https://github.com/Baza207) in Pull Request - [#771](https://github.com/Alamofire/Alamofire/pull/771). -- The Travis-CI yaml file to run watchOS and tvOS builds and tests on xcode7.1 osx_image. - - Updated by [Christian Noon](https://github.com/cnoon). - ---- - -## [3.0.1](https://github.com/Alamofire/Alamofire/releases/tag/3.0.1) -Released on 2015-10-19. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.0.1). - -#### Added -- Tests around content type validation with accept parameters. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Content type validation issue where parameter parsing on `;` was incorrect. - - Fixed by [Christian Noon](https://github.com/cnoon). - -## [3.0.0](https://github.com/Alamofire/Alamofire/releases/tag/3.0.0) -Released on 2015-10-10. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.0.0). - -#### Updated -- `Downloading a File` code sample in the README to compile against Swift 2.0. - - Updated by [Screon](https://github.com/Screon) in Pull Request - [#827](https://github.com/Alamofire/Alamofire/pull/827). -- Download code samples in the README to use `response` serializer. - - Updated by [Christian Noon](https://github.com/cnoon). -- CocoaPods and Carthage installation instructions for 3.0. - - Updated by [Christian Noon](https://github.com/cnoon). -- Carthage description and installation instructions in the README. - - Updated by [Ashton Williams](https://github.com/Ashton-W) in Pull Request - [#843](https://github.com/Alamofire/Alamofire/pull/843). -- URL encoding internals to leverage the dictionary keys lazy evaluation. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Small typo in the Alamofire 3.0 Migration Guide `Response` section. - - Fixed by [neugartf](https://github.com/neugartf) in Pull Request - [#826](https://github.com/Alamofire/Alamofire/pull/826). -- User defined `BITCODE_GENERATION_MODE` setting for Carthage builds. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#835](https://github.com/Alamofire/Alamofire/issues/835). - ---- - -## [3.0.0-beta.3](https://github.com/Alamofire/Alamofire/releases/tag/3.0.0-beta.3) -Released on 2015-09-27. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.0.0-beta.3). - -#### Updated -- The `Response` initializer to have a `public` ACL instead of `internal`. - - Updated by [Christian Noon](https://github.com/cnoon). - -## [3.0.0-beta.2](https://github.com/Alamofire/Alamofire/releases/tag/3.0.0-beta.2) -Released on 2015-09-26. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.0.0-beta.2). - -#### Added -- Tests around the header behavior for redirected requests. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#798](https://github.com/Alamofire/Alamofire/issues/798). -- A migration guide for Alamofire 3.0 documenting all API changes. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- `Response` initializer to have `internal` ACL. - - Updated by [Christian Noon](https://github.com/cnoon). -- All sample code in the README to conform to the Alamofire 3.0 APIs. - - Updated by [Christian Noon](https://github.com/cnoon). -- URL percent escaping to only batch on OS's where required improving -overall performance. - - Updated by [Christian Noon](https://github.com/cnoon). -- Basic auth example in the README to compile on Swift 2.0. - - Updated by [David F. Muir V](https://github.com/dfmuir) in Pull Request - [#810](https://github.com/Alamofire/Alamofire/issues/810). - -#### Fixed -- Compiler errors in the playground due to the new response serializer APIs. - - Fixed by [Christian Noon](https://github.com/cnoon). - -## [3.0.0-beta.1](https://github.com/Alamofire/Alamofire/releases/tag/3.0.0-beta.1) -Released on 2015-09-21. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A3.0.0-beta.1). - -#### Added -- A new `Response` struct to simplify response serialization. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#792](https://github.com/Alamofire/Alamofire/pull/792). -- A new initializer to the `Manager` allowing dependency injection of the -underlying `NSURLSession`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#795](https://github.com/Alamofire/Alamofire/pull/795). -- Tests around the new `Manager` initialization methods. - -#### Updated -- Result type to take two generic parameters (`Value` and `Error`) where `Error` -conforms to `ErrorType`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#791](https://github.com/Alamofire/Alamofire/pull/791). -- All response serializers to now return the original server data as `NSData?`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#791](https://github.com/Alamofire/Alamofire/pull/791). -- The `TaskDelegate` to store an error as an `NSError` instead of `ErrorType`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#791](https://github.com/Alamofire/Alamofire/pull/791). -- The `ValidationResult` failure case to require an `NSError` instead of `ErrorType`. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#791](https://github.com/Alamofire/Alamofire/pull/791). -- All tests around response serialization and `Result` type usage. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#791](https://github.com/Alamofire/Alamofire/pull/791). -- All response serializers to use the new `Response` type. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - - [#792](https://github.com/Alamofire/Alamofire/pull/792). -- The designated initializer for a `Manager` to accept a `SessionDelegate` parameter -allowing dependency injection for better background session support. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#795](https://github.com/Alamofire/Alamofire/pull/795). - ---- - -## [2.0.2](https://github.com/Alamofire/Alamofire/releases/tag/2.0.2) -Released on 2015-09-20. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.2). - -#### Updated -- The Embedded Framework documentation to include `git init` info. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#782](https://github.com/Alamofire/Alamofire/issues/782). - -#### Fixed -- Alamofire iOS framework target by adding Alamofire iOS Tests as Target Dependency. - - Fixed by [Nicky Gerritsen](https://github.com/nickygerritsen) in Pull Request - [#780](https://github.com/Alamofire/Alamofire/pull/780). -- Percent encoding issue for long Chinese strings using URL parameter encoding. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#206](https://github.com/Alamofire/Alamofire/issues/206). - -## [2.0.1](https://github.com/Alamofire/Alamofire/releases/tag/2.0.1) -Released on 2015-09-16. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.1). - -#### Updated -- The CocoaPods installation instructions in the README. - - Updated by [Christian Noon](https://github.com/cnoon). -- The Carthage installation instructions in the README. - - Updated by [Gustavo Barbosa](https://github.com/barbosa) in Pull Request - [#759](https://github.com/Alamofire/Alamofire/pull/759). - -#### Fixed -- The link to the 2.0 migration guide in the README. - - Fixed by [Dwight Watson](https://github.com/dwightwatson) in Pull Request - [#750](https://github.com/Alamofire/Alamofire/pull/750). -- Issue where NTLM authentication credentials were not used for authentication challenges. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#721](https://github.com/Alamofire/Alamofire/pull/721). - -## [2.0.0](https://github.com/Alamofire/Alamofire/releases/tag/2.0.0) -Released on 2015-09-09. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.0). - -#### Added -- A new `URLEncodedInURL` case to the `ParameterEncoding` for encoding in the URL. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#742](https://github.com/Alamofire/Alamofire/pull/742). - ---- - -## [2.0.0-beta.4](https://github.com/Alamofire/Alamofire/releases/tag/2.0.0-beta.4) -Released on 2015-09-06. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.0-beta.4). - -#### Added -- The `parameters` and `encoding` parameters to download APIs. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#719](https://github.com/Alamofire/Alamofire/issues/719). -- Section to the README about wildcard domain matching with server trust policies. - - Added by [Sai](https://github.com/sai-prasanna) in Pull Request - [#718](https://github.com/Alamofire/Alamofire/pull/718). -- A UTF-8 charset to Content-Type header for a URL encoded body. - - Added by [Cheolhee Han](https://github.com/cheolhee) in Pull Request - [#731](https://github.com/Alamofire/Alamofire/pull/731). -- Tests around posting unicode parameters with URL encoding. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Pull Request - [#731](https://github.com/Alamofire/Alamofire/pull/731). -- Tests for uploading base 64 encoded image data inside JSON. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#738](https://github.com/Alamofire/Alamofire/issues/738). -- An Alamofire 2.0 migration guide document to the new Documentation folder. - - Added by [Christian Noon](https://github.com/cnoon). -- A Migration Guides section to the README with link to 2.0 guide. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- Response serialization to prevent unnecessary call to response serializer. - - Updated by [Julien Ducret](https://github.com/brocoo) in Pull Request - [#716](https://github.com/Alamofire/Alamofire/pull/716). -- Travis-CI yaml file to support iOS 9, OSX 10.11 and Xcode 7. - - Updated by [Christian Noon](https://github.com/cnoon). -- Result types to store an `ErrorType` instead of `NSError`. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#732](https://github.com/Alamofire/Alamofire/issues/732). -- Docstrings on the download method to be more accurate. - - Updated by [Christian Noon](https://github.com/cnoon). -- The README to require Xcode 7 beta 6. - - Updated by [Christian Noon](https://github.com/cnoon). -- The background session section of the README to use non-deprecated API. - - Updated by [David F. Muir V](https://github.com/dfmuir) in Pull Request - [#724](https://github.com/Alamofire/Alamofire/pull/724). -- The playground to use the `Result` type. - - Updated by [Jonas Schmid](https://github.com/jschmid) in Pull Request - [#726](https://github.com/Alamofire/Alamofire/pull/726). -- Updated progress code samples in the README to show how to call onto the main queue. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Removed -- The AFNetworking sections from the FAQ in the README. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue on Windows where the wildcarded cert name in the test suite included asterisk. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#723](https://github.com/Alamofire/Alamofire/issues/723). -- Crash when multipart form data was uploaded from in-memory data on background session. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#740](https://github.com/Alamofire/Alamofire/issues/740). -- Issue where the background session completion handler was not called on the main queue. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#728](https://github.com/Alamofire/Alamofire/issues/728). - -## [2.0.0-beta.3](https://github.com/Alamofire/Alamofire/releases/tag/2.0.0-beta.3) -Released on 2015-08-25. - -#### Removed -- The override for `NSMutableURLRequest` for the `URLRequestConvertible` protocol -conformance that could cause unwanted URL request referencing. - - Removed by [Christian Noon](https://github.com/cnoon). - -## [2.0.0-beta.2](https://github.com/Alamofire/Alamofire/releases/tag/2.0.0-beta.2) -Released on 2015-08-24. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.0-beta.2). - -#### Added -- Host and certificate chain validation section to the README. - - Added by [Christian Noon](https://github.com/cnoon). -- Tests verifying configuration headers are sent with all configuration types. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#692](https://github.com/Alamofire/Alamofire/issues/692). -- New rdar to the list in the README about the #available check issue. - - Added by [Christian Noon](https://github.com/cnoon). -- Override for `NSMutableURLRequest` for the `URLRequestConvertible` protocol. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- The README to note that CocoaPods 0.38.2 is required. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#682](https://github.com/Alamofire/Alamofire/issues/682). -- The README to include note about keeping a reference to the `Manager`. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#681](https://github.com/Alamofire/Alamofire/issues/681). -- Server trust host validation over to use SSL policy evaluation. - - Updated by [Christian Noon](https://github.com/cnoon). -- The documentation for the `URLRequestConvertible` section in the README. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `ServerTrustPolicyManager` to be more flexible by using `public` ACL. - - Updated by [Jan Riehn](https://github.com/jriehn) in Pull Request - [#696](https://github.com/Alamofire/Alamofire/pull/696). -- The `ServerTrustPolicyManager` policies property to use `public` ACL and -added docstrings. - - Updated by [Christian Noon](https://github.com/cnoon). -- The Ono response serializer example for Swift 2.0 in the README. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#700](https://github.com/Alamofire/Alamofire/issues/700). -- `Result` failure case to store an `ErrorType` instead of `NSError`. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#703](https://github.com/Alamofire/Alamofire/issues/703). -- All source code to compile with Xcode 7 beta 6. - - Updated by [Michael Gray](https://github.com/mishagray) in Pull Request - [#707](https://github.com/Alamofire/Alamofire/pull/707). - -#### Removed -- The `required` declaration on the `Manager` init method. - - Removed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#672](https://github.com/Alamofire/Alamofire/issues/672). - -#### Fixed -- Issue where the `TaskDelegate` operation queue would leak if the task was -never started. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Compiler issue on OS X target when creating background configurations -in the test suite. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#693](https://github.com/Alamofire/Alamofire/issues/693). - -## [2.0.0-beta.1](https://github.com/Alamofire/Alamofire/releases/tag/2.0.0-beta.1) -Released on 2015-08-10. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A2.0.0-beta.1). - -#### Added -- A `watchOS` deployment target to the podspec. - - Added by [Kyle Fuller](https://github.com/kylef) in Pull Request - [#574](https://github.com/Alamofire/Alamofire/pull/574). -- Full screen support in the iOS Example App. - - Added by [Corinne Krych](https://github.com/corinnekrych) in Pull Request - [#612](https://github.com/Alamofire/Alamofire/pull/612). -- Temporary workaround for `SecCertificate` array compiler crash. - - Added by [Robert Rasmussen](https://github.com/robrasmussen) in Issue - [#610](https://github.com/Alamofire/Alamofire/issues/610). -- `Result` and `Error` types to refactor response validation and serialization. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#627](https://github.com/Alamofire/Alamofire/pull/627). -- Tests around response data, string and json serialization result behavior. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#627](https://github.com/Alamofire/Alamofire/pull/627). -- `CustomStringConvertible` and `CustomDebugStringConvertible` conformance -to the `Result` enumeration. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#648](https://github.com/Alamofire/Alamofire/pull/648). -- A Resume Data section to the README inside the Downloads section. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#648](https://github.com/Alamofire/Alamofire/pull/648). -- A `watchOS` framework target to the project. - - Added by [Tobias Ottenweller](https://github.com/tomco) in Pull Request - [#616](https://github.com/Alamofire/Alamofire/pull/616). -- `Result` tests pushing code coverage for `Result` enum to 100%. - - Added by [Christian Noon](https://github.com/cnoon). -- Tests around all response serializer usage. - - Added by [Christian Noon](https://github.com/cnoon). -- Public docstrings for all public `SessionDelegate` methods. - - Added by [Christian Noon](https://github.com/cnoon). -- A section to the README that calls out all open rdars affecting Alamofire. - - Added by [Christian Noon](https://github.com/cnoon). -- Test for wildcard validation that contains response with nil MIME type. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#662](https://github.com/Alamofire/Alamofire/pull/662). -- Support for stream tasks in iOS 9+ and OSX 10.11+. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#659](https://github.com/Alamofire/Alamofire/pull/659). - -#### Updated -- All logic to compile against Swift 2.0. - - Updated by [Christian Noon](https://github.com/cnoon). -- All logic to use the latest Swift 2.0 conventions. - - Updated by [Christian Noon](https://github.com/cnoon). -- All public docstrings to the latest Swift 2.0 syntax. - - Updated by [Christian Noon](https://github.com/cnoon). -- `URLRequestConvertible` to return an `NSMutableURLRequest`. - - Updated by [Christian Noon](https://github.com/cnoon). -- All HTTP requests to HTTPS to better align with ATS. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `escape` method in `ParameterEncoding` to use non-deprecated methods. - - Updated by [Christian Noon](https://github.com/cnoon). -- All source code and docstrings to fit roughly within 120 characters. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `MultipartFormData` encoding to leverage Swift 2.0 error handling. - - Updated by [Christian Noon](https://github.com/cnoon). -- All README code samples to match the latest Swift 2.0 API changes. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#648](https://github.com/Alamofire/Alamofire/pull/648). -- All frameworks to enable code coverage generation. - - Updated by [Christian Noon](https://github.com/cnoon). -- All frameworks to set the enable testability flag to YES for release builds. - - Updated by [Christian Noon](https://github.com/cnoon) in regard to Issue - [#652](https://github.com/Alamofire/Alamofire/issues/652). -- `ParameterEncoding` to leverage guard for parameters to increase safety. - - Updated by [Christian Noon](https://github.com/cnoon). -- iOS Example App to use optional bind around response to safely extract headers. - - Updated by [John Pope](https://github.com/johndpope) in Pull Request - [#665](https://github.com/Alamofire/Alamofire/pull/665). -- The `queryComponents` and `escape` methods in `ParameterEncoding` to `public` to -better support `.Custom` encoding. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#660](https://github.com/Alamofire/Alamofire/pull/660). -- The static error convenience functions to a public ACL. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#668](https://github.com/Alamofire/Alamofire/issues/668). - -#### Removed -- Explicit string values in `ParameterEncoding` since they are now implied. - - Removed by [Christian Noon](https://github.com/cnoon). -- An OSX cookie check in the `CustomDebugStringConvertible` conformance of a `Request`. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Issue in automatic validation tests where mutable URL request was not used. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Potential crash cases in Validation MIME type logic exposed by chaining. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Compiler issue in the iOS Example App around `Result` type usage. - - Fixed by [Jan Kase](https://github.com/jankase) in Pull Request - [#639](https://github.com/Alamofire/Alamofire/pull/639). -- The error code in the custom response serializers section of the README. - - Fixed by [Christian Noon](https://github.com/cnoon). - ---- - -## [1.3.1](https://github.com/Alamofire/Alamofire/releases/tag/1.3.1) -Released on 2015-08-10. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A1.3.1). - -#### Fixed -- Issue where a completed task was not released by the `SessionDelegate` if the -task override closure was set. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#622](https://github.com/Alamofire/Alamofire/issues/622). - -## [1.3.0](https://github.com/Alamofire/Alamofire/releases/tag/1.3.0) -Released on 2015-07-24. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A1.3.0). - -#### Added -- Test case around `NSURLProtocol` checking header passthrough behaviors. - - Added by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#473](https://github.com/Alamofire/Alamofire/issues/473). -- Stream method on `Request` to receive data incrementally from data responses. - - Added by [Peter Sobot](https://github.com/psobot) in Pull Request - [#512](https://github.com/Alamofire/Alamofire/pull/512). -- Example to the README demonstrating how to use the `responseCollection` serializer. - - Added by [Josh Brown](https://github.com/joshuatbrown) in Pull Request - [#532](https://github.com/Alamofire/Alamofire/pull/532). -- Link to the README to the CocoaDocs documentation for Alamofire. - - Added by [Robert](https://github.com/rojotek) in Pull Request - [#541](https://github.com/Alamofire/Alamofire/pull/541). -- Support for uploading `MultipartFormData` in-memory and streaming from disk. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#539](https://github.com/Alamofire/Alamofire/pull/539). -- Tests for uploading `MultipartFormData` with complete code coverage. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#539](https://github.com/Alamofire/Alamofire/pull/539). -- The iOS 8.4 simulator to the Travis CI builds by switching to the Xcode 6.4 build. - - Added by [Syo Ikeda](https://github.com/ikesyo) in Pull Request - [#568](https://github.com/Alamofire/Alamofire/pull/568). -- Tests for the custom header support with complete code coverage. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#586](https://github.com/Alamofire/Alamofire/pull/586). -- Section to the README about new HTTP header support in the global functions. - - Added by [Christian Noon](https://github.com/cnoon). -- Basic auth `Authorization` header example to the README. - - Added by [Christian Noon](https://github.com/cnoon). -- TLS certificate and public key pinning support through the `ServerTrustPolicy`. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#581](https://github.com/Alamofire/Alamofire/pull/581). -- Tests for TLS certificate and public key pinning with complete code coverage. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#581](https://github.com/Alamofire/Alamofire/pull/581). -- Security section to the README detailing various server trust policies. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#581](https://github.com/Alamofire/Alamofire/pull/581). -- The `resumeData` property to `Request` to expose outside data response serializer. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#595](https://github.com/Alamofire/Alamofire/pull/595). -- Download request sample to iOS example app. - - Added by [Kengo Yokoyama](https://github.com/kentya6) in Pull Request - [#579](https://github.com/Alamofire/Alamofire/pull/579). - -#### Updated -- The INFOPLIST_FILE Xcode project setting to be a relative path. - - Updated by [Christian Noon](https://github.com/cnoon). -- Exposed persistence parameter for basic auth credentials. - - Updated by [Christian Noon](https://github.com/cnoon) in regard to Issue - [#537](https://github.com/Alamofire/Alamofire/issues/537). -- The Travis CI builds to run a full `pod lib lint` pass on the source. - - Updated by [Kyle Fuller](https://github.com/kylef) in Pull Request - [#542](https://github.com/Alamofire/Alamofire/pull/542). -- All cases of force unwrapping with optional binding and where clause when applicable. - - Updated by [Syo Ikeda](https://github.com/ikesyo) in Pull Request - [#557](https://github.com/Alamofire/Alamofire/pull/557). -- The `ParameterEncoding` encode return tuple to return a mutable URL request. - - Updated by [Petr Korolev](https://github.com/skywinder) in Pull Request - [#478](https://github.com/Alamofire/Alamofire/pull/478). -- The `URLRequest` convenience method to return a mutable `NSURLRequest`. - - Updated by [Christian Noon](https://github.com/cnoon). -- The `request` / `download` / `upload` methods to support custom headers. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#586](https://github.com/Alamofire/Alamofire/pull/586). -- The global `request` / `download` / `upload` method external parameters convention. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#586](https://github.com/Alamofire/Alamofire/pull/586). -- Response serialization to use generics and a `ResponseSerializer` protocol. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#593](https://github.com/Alamofire/Alamofire/pull/593). -- Download task delegate to store resume data for a failed download if available. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#595](https://github.com/Alamofire/Alamofire/pull/595). -- The `TaskDelegate.queue` to public to allow custom request extension operations. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#590](https://github.com/Alamofire/Alamofire/pull/590). -- The README code samples for Advanced Response Serialization. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Removed -- An unnecessary `NSURLSessionConfiguration` type declaration that can be inferred. - - Removed by [Avismara](https://github.com/avismarahl) in Pull Request - [#576](https://github.com/Alamofire/Alamofire/pull/576). -- Unnecessary `respondsToSelector` overrides for `SessionDelegate` methods. - - Removed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#590](https://github.com/Alamofire/Alamofire/pull/590). -- Unnecessary calls to `self` throughout source, test and example logic. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- Random test suite basic auth failures by clearing credentials in `setUp` method. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Error where wildcard was failing due to missing response MIME type. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#598](https://github.com/Alamofire/Alamofire/pull/598). -- Typo in the basic auth headers example code in the README. - - Fixed by [蒲公英の生活](https://github.com/fewspider) in Pull Request - [#605](https://github.com/Alamofire/Alamofire/pull/605). -- Issue where the example app was printing elapsed time in optional form. - - Fixed by [Christian Noon](https://github.com/cnoon). - -#### Upgrade Notes -There are a couple changes in the 1.3.0 release that are not fully backwards -compatible and need to be called out. - -* The global `request` / `download` / `upload` external parameter naming conventions -were not consistent nor did they match the `Manager` equivalents. By making them -consistent across the board, this introduced the possibility that you "may" need to -make slight modifications to your global function calls. -* In order to support generic response serializers, the lowest level -`Request.response` method had to be converted to a generic method leveraging the new -`ResponseSerializer` protocol. This has many advantages, the most obvious being that -the `response` convenience method now returns an `NSData?` optional instead of an -`AnyObject?` optional. Nice! - - > Please note that every effort is taken to maintain proper semantic versioning. In -these two rare cases, it was deemed to be in the best interest of the community to -slightly break semantic versioning to unify naming conventions as well as expose a -much more powerful form of response serialization. - - > If you have any issues, please don't hesitate to reach out through -[GitHub](https://github.com/Alamofire/Alamofire/issues) or -[Twitter](https://twitter.com/AlamofireSF). - ---- - -## [1.2.3](https://github.com/Alamofire/Alamofire/releases/tag/1.2.3) -Released on 2015-06-12. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A1.2.3). - -#### Added -- Tests for data task progress closure and NSProgress updates. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#494](https://github.com/Alamofire/Alamofire/pull/494). -- More robust tests around download and upload progress. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#494](https://github.com/Alamofire/Alamofire/pull/494). -- More robust redirect tests around default behavior and task override closures. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#507](https://github.com/Alamofire/Alamofire/pull/507). -- The "[" and "]" to the legal escape characters and added more documentation. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#504](https://github.com/Alamofire/Alamofire/pull/504). -- Percent escaping tests around reserved / unreserved / illegal characters. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#504](https://github.com/Alamofire/Alamofire/pull/504). -- Tests for various Cache-Control headers with different request cache policies. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#505](https://github.com/Alamofire/Alamofire/pull/505). -- Link to Carthage in the README. - - Added by [Josh Brown](https://github.com/joshuatbrown) in Pull Request - [#520](https://github.com/Alamofire/Alamofire/pull/520). - -#### Updated -- iOS 7 instructions to cover multiple Swift files in the README. - - Updated by [Sébastien Michoy](https://github.com/SebastienMichoy) in regards - to Issue [#479](https://github.com/Alamofire/Alamofire/pull/479). -- All tests to follow the Given / When / Then structure. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#489](https://github.com/Alamofire/Alamofire/pull/489). -- All tests to be crash safe. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#489](https://github.com/Alamofire/Alamofire/pull/489). -- The OS X tests so that they are all passing again. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#489](https://github.com/Alamofire/Alamofire/pull/489). -- Re-enabled Travis-CI tests for both iOS and Mac OS X. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#506](https://github.com/Alamofire/Alamofire/pull/506). -- Travis-CI test suite to run all tests in both debug and release. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#506](https://github.com/Alamofire/Alamofire/pull/506). -- Travis-CI test suite to run all tests on iOS 8.1, 8.2 and 8.3 as well as Mac OS X 10.10. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#506](https://github.com/Alamofire/Alamofire/pull/506). -- Travis-CI test suite to run `pod lib lint` against the latest version of CocoaPods. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#506](https://github.com/Alamofire/Alamofire/pull/506). - -#### Fixed -- Random deinitialization test failure by handling task state race condition. - - Fixed by [Christian Noon](https://github.com/cnoon). -- Typo in the API Parameter Abstraction in the README. - - Fixed by [Josh Brown](https://github.com/joshuatbrown) in Pull Request - [#500](https://github.com/Alamofire/Alamofire/pull/500). -- Cookies are now only applied in the DebugPrintable API when appropriate. - - Fixed by [Alex Plescan](https://github.com/alexpls) in Pull Request - [#516](https://github.com/Alamofire/Alamofire/pull/516). - -## [1.2.2](https://github.com/Alamofire/Alamofire/releases/tag/1.2.2) -Released on 2015-05-13. All issues associated with this milestone can be found using this -[filter](https://github.com/Alamofire/Alamofire/issues?utf8=✓&q=milestone%3A1.2.2). - -#### Added -- Contributing Guidelines document to the project. - - Added by [Mattt Thompson](https://github.com/mattt). -- Documentation to the `URLStringConvertible` protocol around RFC specs. - - Added by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#464](https://github.com/Alamofire/Alamofire/pull/464). -- The `Carthage/Build` ignore flag to the `.gitignore` file. - - Added by [Tomáš Slíž](https://github.com/tomassliz) in Pull Request - [#451](https://github.com/Alamofire/Alamofire/pull/451). -- The `.DS_Store` ignore flag to the `.gitignore` file. - - Added by [Christian Noon](https://github.com/cnoon). -- Response status code asserts for redirect tests. - - Added by [Christian Noon](https://github.com/cnoon). -- A CHANGELOG to the project documenting each official release. - - Added by [Christian Noon](https://github.com/cnoon). - -#### Updated -- `SessionDelegate` override closure properties to match the method signatures. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#456](https://github.com/Alamofire/Alamofire/pull/456). -- Documentation for the `Printable` protocol on `Request` to reference output stream -rather than the specific `OutputStreamType`. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Deployment targets to iOS 8.0 and OS X 10.9 for the respective frameworks. - - Updated by [Christian Noon](https://github.com/cnoon). -- `SessionDelegate` willPerformHTTPRedirection method to accept optional return type -from override closure. - - Updated by [Chungsub Kim](https://github.com/subicura) in Pull Request - [#469](https://github.com/Alamofire/Alamofire/pull/469). -- Embedded Framework and Source File documentation in the README. - - Updated by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#427](https://github.com/Alamofire/Alamofire/pull/427). -- Alamofire source to be split into multiple core files and feature files. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#471](https://github.com/Alamofire/Alamofire/pull/471). -- `TaskDelegate` override closure signatures and delegate method implementations. - - Updated by [Christian Noon](https://github.com/cnoon). - -#### Removed -- Travis-CI build status from the README until Xcode 6.3 is supported. - - Removed by [Mattt Thompson](https://github.com/mattt). -- Unnecessary parentheses from closure parameters and typealiases. - - Removed by [Christian Noon](https://github.com/cnoon). - -#### Fixed -- `SessionDelegate` override closure documentation. - - Fixed by [Siemen Sikkema](https://github.com/siemensikkema) in Pull Request - [#448](https://github.com/Alamofire/Alamofire/pull/448). -- Some inaccurate documentation on several of the public `SessionDelegate` closures. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#456](https://github.com/Alamofire/Alamofire/pull/456). -- A deinit race condition where the task delegate queue could fail to `dispatch_release`. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#379](https://github.com/Alamofire/Alamofire/pull/379). -- `TaskDelegate` to only set `qualityOfService` for `NSOperationQueue` on iOS 8+. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#472](https://github.com/Alamofire/Alamofire/pull/472). -- Expectation order issue in the redirect tests. - - Fixed by [Christian Noon](https://github.com/cnoon). -- `DataTaskDelegate` behavior ensuring `NSProgress` values and `progress` override -closures are always updated and executed. - - Fixed by [Christian Noon](https://github.com/cnoon) in regards to Issue - [#407](https://github.com/Alamofire/Alamofire/pull/407). - -## [1.2.1](https://github.com/Alamofire/Alamofire/releases/tag/1.2.1) -Released on 2015-04-21. - -#### Added -- Redirect tests for the `SessionDelegate`. - - Added by [Jonathan Hersh](https://github.com/jhersh) in Pull Request - [#424](https://github.com/Alamofire/Alamofire/pull/424). -- TLS evaluation test case. - - Added by [Mattt Thompson](https://github.com/mattt). -- Additional guards to ensure unique task identifiers for upload and download tasks. - - Added by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#393](https://github.com/Alamofire/Alamofire/pull/393). - -#### Updated -- Required Xcode version to Xcode to 6.3 in the README. - - Updated by [Mattt Thompson](https://github.com/mattt). -- SSL validation to use default system validation by default. - - Updated by [Michael Thole](https://github.com/mthole) in Pull Request - [#394](https://github.com/Alamofire/Alamofire/pull/394). - -## [1.2.0](https://github.com/Alamofire/Alamofire/releases/tag/1.2.0) -Released on 2015-04-09. - -#### Added -- New `testURLParameterEncodeStringWithSlashKeyStringWithQuestionMarkValueParameter` -test. - - Added by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#370](https://github.com/Alamofire/Alamofire/pull/370). -- New `backgroundCompletionHandler` property to the `Manager` called when the -session background tasks finish. - - Added by [Christian Noon](https://github.com/cnoon) in Pull Request - [#317](https://github.com/Alamofire/Alamofire/pull/317). - -#### Updated -- `Request` computed property `progress` to no longer be an optional type. - - Updated by [Pitiphong Phongpattranont](https://github.com/pitiphong-p) in - Pull Request - [#404](https://github.com/Alamofire/Alamofire/pull/404). -- All logic to Swift 1.2. - - Updated by [Aron Cedercrantz](https://github.com/rastersize) and - [Mattt Thompson](https://github.com/mattt). -- The `responseString` serializer to respect server provided character encoding with -overrideable configuration, default string response serialization to ISO-8859-1, as -per the HTTP/1.1 specification. - - Updated by [Kyle Fuller](https://github.com/kylef) and - [Mattt Thompson](https://github.com/mattt) in Pull Request - [#359](https://github.com/Alamofire/Alamofire/pull/359) which also resolved Issue - [#358](https://github.com/Alamofire/Alamofire/pull/358). -- `SessionDelegate` methods to first call the override closures if set. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#317](https://github.com/Alamofire/Alamofire/pull/317). -- `SessionDelegate` and all override closures to a public ACL allowing for customization. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#317](https://github.com/Alamofire/Alamofire/pull/317). -- `SessionDelegate` class to `final`. - - Updated by [Mattt Thompson](https://github.com/mattt). -- `SessionDelegate` header documentation for method override properties. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Xcode project to set `APPLICATION_EXTENSION_API_ONLY` to `YES` for OS X target. - - Updated by [Mattt Thompson](https://github.com/mattt). - -#### Removed -- Ambiguous response serializer methods that collided with default parameters. - - Removed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#408](https://github.com/Alamofire/Alamofire/pull/408). -- `SessionDelegate` initializer and replaced with default property value. - - Removed by [Mattt Thompson](https://github.com/mattt). - -#### Fixed -- Async tests where asserts were potentially not being run by by moving -`expectation.fullfill()` to end of closures. - - Fixed by [Nate Cook](https://github.com/natecook1000) in Pull Request - [#420](https://github.com/Alamofire/Alamofire/pull/420). -- Small grammatical error in the ParameterEncoding section of the README. - - Fixed by [Aaron Brager](https://github.com/getaaron) in Pull Request - [#416](https://github.com/Alamofire/Alamofire/pull/416). -- Typo in a download test comment. - - Fixed by [Aaron Brager](https://github.com/getaaron) in Pull Request - [#413](https://github.com/Alamofire/Alamofire/pull/413). -- Signature mismatch in the `dataTaskDidBecomeDownloadTask` override closure. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#317](https://github.com/Alamofire/Alamofire/pull/317). -- Issue in the `SessionDelegate` where the `DataTaskDelegate` was not being called. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#317](https://github.com/Alamofire/Alamofire/pull/317). - ---- - -## [1.1.5](https://github.com/Alamofire/Alamofire/releases/tag/1.1.5) -Released on 2015-03-26. - -#### Added -- Convenience upload functions to the `Manager`. - - Added by [Olivier Bohrer](https://github.com/obohrer) in Pull Request - [#334](https://github.com/Alamofire/Alamofire/pull/334). -- Info to the README about Swift 1.2 support. - - Added by [Mattt Thompson](https://github.com/mattt). - -#### Updated -- All request / upload / download methods on `Manager` to match the top-level functions. - - Updated by [Mattt Thompson](https://github.com/mattt). -- The `testDownloadRequest` to no longer remove the downloaded file. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Ono XML response serializer example in the README. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Travis-CI settings to only build the master branch. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Code signing identities for the frameworks and targets to better support Carthage. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#400](https://github.com/Alamofire/Alamofire/pull/400). -- iOS deployment target to iOS 8.0 for iOS target and tests. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#401](https://github.com/Alamofire/Alamofire/pull/401). -- Legal characters to be escaped according to RFC 3986 Section 3.4. - - Updated by [Stephane Lizeray](https://github.com/slizeray) in Pull Request - [#370](https://github.com/Alamofire/Alamofire/pull/370). - -#### Fixed -- Travis-CI scheme issue, added podspec linting and added ENV variables. - - Fixed by [Jonathan Hersh](https://github.com/jhersh) in Pull Request - [#351](https://github.com/Alamofire/Alamofire/pull/351). -- Code sample in the README in the Manual Parameter Encoding section. - - Fixed by [Petr Korolev](https://github.com/skywinder) in Pull Request - [#381](https://github.com/Alamofire/Alamofire/pull/381). - -## [1.1.4](https://github.com/Alamofire/Alamofire/releases/tag/1.1.4) -Released on 2015-01-30. - -#### Added -- Podspec argument `requires_arc` to the podspec file. - - Added by [Mattt Thompson](https://github.com/mattt). -- Support for Travis-CI for automated testing purposes. - - Added by [Kyle Fuller](https://github.com/kylef) in Pull Request - [#279](https://github.com/Alamofire/Alamofire/pull/279). - -#### Updated -- Installation instructions in the README to include CocoaPods, Carthage and -Embedded Frameworks. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Travis-CI to use Xcode 6.1.1. - - Updated by [Mattt Thompson](https://github.com/mattt). -- The `download` method on `Manager` to use `Request.DownloadFileDestination` typealias. - - Updated by [Alexander Strakovich](https://github.com/astrabot) in Pull Request - [#318](https://github.com/Alamofire/Alamofire/pull/318). -- `RequestTests` to no longer delete all cookies in default session configuration. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Travis-CI yaml file to only build the active architecture. - - Updated by [Mattt Thompson](https://github.com/mattt). -- Deployment targets to iOS 7.0 and Mac OS X 10.9. - - Updated by [Mattt Thompson](https://github.com/mattt). - -#### Removed -- The `tearDown` method in the `AlamofireDownloadResponseTestCase`. - - Removed by [Mattt Thompson](https://github.com/mattt). - -#### Fixed -- Small formatting issue in the CocoaPods Podfile example in the README. - - Fixed by [rborkow](https://github.com/rborkow) in Pull Request - [#313](https://github.com/Alamofire/Alamofire/pull/313). -- Several issues with the iOS and OSX targets in the Xcode project. - - Fixed by [Mattt Thompson](https://github.com/mattt). -- The `testDownloadRequest` in `DownloadTests` by adding `.json` file extension. - - Fixed by [Martin Kavalar](https://github.com/mk) in Pull Request - [#302](https://github.com/Alamofire/Alamofire/pull/302). -- The `AlamofireRequestDebugDescriptionTestCase` on OSX. - - Fixed by [Mattt Thompson](https://github.com/mattt). -- Spec validation error with CocoaPods 0.36.0.beta-1 by disabling -b flags in `cURL` -debug on OSX. - - Fixed by [Mattt Thompson](https://github.com/mattt). -- Travis-CI build issue by adding suppport for an `iOS Example` scheme. - - Fixed by [Yasuharu Ozaki](https://github.com/yasuoza) in Pull Request - [#322](https://github.com/Alamofire/Alamofire/pull/322). - -## [1.1.3](https://github.com/Alamofire/Alamofire/releases/tag/1.1.3) -Released on 2015-01-09. - -#### Added -- Podspec file to support CocoaPods deployment. - - Added by [Marius Rackwitz](https://github.com/mrackwitz) in Pull Request - [#218](https://github.com/Alamofire/Alamofire/pull/218). -- Shared scheme to support Carthage deployments. - - Added by [Yosuke Ishikawa](https://github.com/ishkawa) in Pull Request - [#228](https://github.com/Alamofire/Alamofire/pull/228). -- New target for Alamofire OSX framework. - - Added by [Martin Kavalar](https://github.com/mk) in Pull Request - [#293](https://github.com/Alamofire/Alamofire/pull/293). - -#### Updated -- Upload and Download progress state to be updated before calling progress closure. - - Updated by [Alexander Strakovich](https://github.com/astrabot) in Pull Request - [#278](https://github.com/Alamofire/Alamofire/pull/278). - -#### Fixed -- Some casting code logic in the Generic Response Object Serialization example in -the README. - - Fixed by [Philip Heinser](https://github.com/philipheinser) in Pull Request - [#258](https://github.com/Alamofire/Alamofire/pull/258). -- Indentation formatting of the `responseString` parameter documentation. - - Fixed by [Ah.Miao](https://github.com/mrahmiao) in Pull Request - [#291](https://github.com/Alamofire/Alamofire/pull/291). - -## [1.1.2](https://github.com/Alamofire/Alamofire/releases/tag/1.1.2) -Released on 2014-12-21. - -#### Added -- POST request JSON response test. - - Added by [Mattt Thompson](https://github.com/mattt). - -#### Updated -- The response object example to use a failable initializer in the README. - - Updated by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#230](https://github.com/Alamofire/Alamofire/pull/230). -- Router example in the README by removing extraneous force unwrap. - - Updated by [Arnaud Mesureur](https://github.com/nsarno) in Pull Request - [#247](https://github.com/Alamofire/Alamofire/pull/247). -- Xcode project `APPLICATION_EXTENSION_API_ONLY` flag to `YES`. - - Updated by [Michael Latta](https://github.com/technomage) in Pull Request - [#273](https://github.com/Alamofire/Alamofire/pull/273). -- Default HTTP header creation by moving it into a public class method. - - Updated by [Christian Noon](https://github.com/cnoon) in Pull Request - [#261](https://github.com/Alamofire/Alamofire/pull/261). - -#### Fixed -- Upload stream method to set `HTTPBodyStream` for streamed request. - - Fixed by [Florent Vilmart](https://github.com/flovilmart) and - [Mattt Thompson](https://github.com/mattt) in Pull Request - [#241](https://github.com/Alamofire/Alamofire/pull/241). -- ParameterEncoding to compose percent-encoded query strings from -percent-encoded components. - - Fixed by [Oleh Sannikov](https://github.com/sunnycows) in Pull Request - [#249](https://github.com/Alamofire/Alamofire/pull/249). -- Serialization handling of NSData with 0 bytes. - - Fixed by [Mike Owens](https://github.com/mowens) in Pull Request - [#254](https://github.com/Alamofire/Alamofire/pull/254). -- Issue where `suggestedDownloadDestination` parameters were being ignored. - - Fixed by [Christian Noon](https://github.com/cnoon) in Pull Request - [#257](https://github.com/Alamofire/Alamofire/pull/257). -- Crash caused by `Manager` deinitialization and added documentation. - - Fixed by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#269](https://github.com/Alamofire/Alamofire/pull/269). - -## [1.1.1](https://github.com/Alamofire/Alamofire/releases/tag/1.1.1) -Released on 2014-11-20. - -#### Updated -- Dispatch-based synchronized access to subdelegates. - - Updated by [Mattt Thompson](https://github.com/mattt) in regards to Pull Request - [#175](https://github.com/Alamofire/Alamofire/pull/175). -- iOS 7 instructions in the README. - - Updated by [Mattt Thompson](https://github.com/mattt). -- CRUD example in the README to work on Xcode 6.1. - - Updated by [John Beynon](https://github.com/johnbeynon) in Pull Request - [#187](https://github.com/Alamofire/Alamofire/pull/187). -- The `cURL` example annotation in the README to pick up `bash` syntax highlighting. - - Updated by [Samuel E. Giddins](https://github.com/segiddins) in Pull Request - [#208](https://github.com/Alamofire/Alamofire/pull/208). - -#### Fixed -- Out-of-memory exception by replacing `stringByAddingPercentEncodingWithAllowedCharacters` -with `CFURLCreateStringByAddingPercentEscapes`. - - Fixed by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#206](https://github.com/Alamofire/Alamofire/pull/206). -- Several issues in the README examples where an NSURL initializer needs to be unwrapped. - - Fixed by [Mattt Thompson](https://github.com/mattt) in regards to Pull Request - [#213](https://github.com/Alamofire/Alamofire/pull/213). -- Possible exception when force unwrapping optional header properties. - - Fixed by [Mattt Thompson](https://github.com/mattt). -- Optional cookie entry in `cURL` output. - - Fixed by [Mattt Thompson](https://github.com/mattt) in regards to Issue - [#226](https://github.com/Alamofire/Alamofire/pull/226). -- Optional `textLabel` property on cells in the example app. - - Fixed by [Mattt Thompson](https://github.com/mattt). - -## [1.1.0](https://github.com/Alamofire/Alamofire/releases/tag/1.1.0) -Released on 2014-10-20. - -#### Updated -- Project to support Swift 1.1 and Xcode 6.1. - - Updated by [Aral Balkan](https://github.com/aral), - [Ross Kimes](https://github.com/rosskimes), - [Orta Therox](https://github.com/orta), - [Nico du Plessis](https://github.com/nduplessis) - and [Mattt Thompson](https://github.com/mattt). - ---- - -## [1.0.1](https://github.com/Alamofire/Alamofire/releases/tag/1.0.1) -Released on 2014-10-20. - -#### Added -- Tests for upload and download with progress. - - Added by [Mattt Thompson](https://github.com/mattt). -- Test for question marks in url encoded query. - - Added by [Mattt Thompson](https://github.com/mattt). -- The `NSURLSessionConfiguration` headers to `cURL` representation. - - Added by [Matthias Ryne Cheow](https://github.com/rynecheow) in Pull Request - [#140](https://github.com/Alamofire/Alamofire/pull/140). -- Parameter encoding tests for key/value pairs containing spaces. - - Added by [Mattt Thompson](https://github.com/mattt). -- Percent character encoding for the `+` character. - - Added by [Niels van Hoorn](https://github.com/nvh) in Pull Request - [#167](https://github.com/Alamofire/Alamofire/pull/167). -- Escaping for quotes to support JSON in `cURL` commands. - - Added by [John Gibb](https://github.com/johngibb) in Pull Request - [#178](https://github.com/Alamofire/Alamofire/pull/178). -- The `request` method to the `Manager` bringing it more inline with the top-level methods. - - Added by Brian Smith. - -#### Fixed -- Parameter encoding of ampersands and escaping of characters. - - Fixed by [Mattt Thompson](https://github.com/mattt) in regards to Issues - [#146](https://github.com/Alamofire/Alamofire/pull/146) and - [#162](https://github.com/Alamofire/Alamofire/pull/162). -- Parameter encoding of `HTTPBody` from occurring twice. - - Fixed by Yuri in Pull Request - [#153](https://github.com/Alamofire/Alamofire/pull/153). -- Extraneous dispatch to background by using weak reference for delegate in response. - - Fixed by [Mattt Thompson](https://github.com/mattt). -- Response handler threading issue by adding a `subdelegateQueue` to the `SessionDelegate`. - - Fixed by [Essan Parto](https://github.com/parto) in Pull Request - [#171](https://github.com/Alamofire/Alamofire/pull/171). -- Challenge issue where basic auth credentials were not being unwrapped. - - Fixed by [Mattt Thompson](https://github.com/mattt). - -## [1.0.0](https://github.com/Alamofire/Alamofire/releases/tag/1.0.0) -Released on 2014-09-25. - -#### Added -- Initial release of Alamofire. - - Added by [Mattt Thompson](https://github.com/mattt). diff --git a/Lesson12/Carthage/Checkouts/Alamofire/CONTRIBUTING.md b/Lesson12/Carthage/Checkouts/Alamofire/CONTRIBUTING.md deleted file mode 100644 index df90349..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/CONTRIBUTING.md +++ /dev/null @@ -1,95 +0,0 @@ -# Contributing Guidelines - -This document contains information and guidelines about contributing to this project. -Please read it before you start participating. - -**Topics** - -* [Asking Questions](#asking-questions) -* [Reporting Security Issues](#reporting-security-issues) -* [Reporting Issues](#reporting-other-issues) -* [Developers Certificate of Origin](#developers-certificate-of-origin) -* [Code of Conduct](#code-of-conduct) - -## Asking Questions - -We don't use GitHub as a support forum. -For any usage questions that are not specific to the project itself, -please ask on [Stack Overflow](https://stackoverflow.com) instead. -By doing so, you'll be more likely to quickly solve your problem, -and you'll allow anyone else with the same question to find the answer. -This also allows maintainers to focus on improving the project for others. - -## Reporting Security Issues - -The Alamofire Software Foundation takes security seriously. -If you discover a security issue, please bring it to our attention right away! - -Please **DO NOT** file a public issue, -instead send your report privately to . -This will help ensure that any vulnerabilities that _are_ found -can be [disclosed responsibly](https://en.wikipedia.org/wiki/Responsible_disclosure) -to any affected parties. - -## Reporting Other Issues - -A great way to contribute to the project -is to send a detailed issue when you encounter a problem. -We always appreciate a well-written, thorough bug report. - -Check that the project issues database -doesn't already include that problem or suggestion before submitting an issue. -If you find a match, add a quick "+1" or "I have this problem too." -Doing this helps prioritize the most common problems and requests. - -When reporting issues, please include the following: - -* The version of Xcode you're using -* The version of iOS or macOS you're targeting -* The full output of any stack trace or compiler error -* A code snippet that reproduces the described behavior, if applicable -* Any other details that would be useful in understanding the problem - -This information will help us review and fix your issue faster. - -## Triage Issues [![Open Source Helpers](https://www.codetriage.com/alamofire/alamofire/badges/users.svg)](https://www.codetriage.com/alamofire/alamofire) - -You can triage issues which may include reproducing bug reports or asking for vital information, such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to alamofire on CodeTriage](https://www.codetriage.com/alamofire/alamofire). - -## Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -- (a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -- (b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -- (c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -- (d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - -## Code of Conduct - -The Code of Conduct governs how we behave in public or in private -whenever the project will be judged by our actions. -We expect it to be honored by everyone who contributes to this project. - -See [CONDUCT.md](https://github.com/Alamofire/Foundation/blob/master/CONDUCT.md) for details. - ---- - -*Some of the ideas and wording for the statements above were based on work by the [Docker](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) and [Linux](https://elinux.org/Developer_Certificate_Of_Origin) communities. We commend them for their efforts to facilitate collaboration in their projects.* diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/AdvancedUsage.md b/Lesson12/Carthage/Checkouts/Alamofire/Documentation/AdvancedUsage.md deleted file mode 100644 index f68fa70..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/AdvancedUsage.md +++ /dev/null @@ -1,953 +0,0 @@ -## Advanced Usage - -Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. - -**Recommended Reading** - -- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) -- [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) -- [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) -- [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) - -### Session Manager - -Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. - -As such, the following two statements are equivalent: - -```swift -Alamofire.request("https://httpbin.org/get") -``` - -```swift -let sessionManager = Alamofire.SessionManager.default -sessionManager.request("https://httpbin.org/get") -``` - -Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). - -#### Creating a Session Manager with Default Configuration - -```swift -let configuration = URLSessionConfiguration.default -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Creating a Session Manager with Background Configuration - -```swift -let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Creating a Session Manager with Ephemeral Configuration - -```swift -let configuration = URLSessionConfiguration.ephemeral -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -#### Modifying the Session Configuration - -```swift -var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders -defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" - -let configuration = URLSessionConfiguration.default -configuration.httpAdditionalHeaders = defaultHeaders - -let sessionManager = Alamofire.SessionManager(configuration: configuration) -``` - -> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. - -### Session Delegate - -By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. - -#### Override Closures - -The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: - -```swift -/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. -open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - -/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. -open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? - -/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. -open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - -/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. -open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? -``` - -The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. - -```swift -let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) -let delegate: Alamofire.SessionDelegate = sessionManager.delegate - -delegate.taskWillPerformHTTPRedirection = { session, task, response, request in - var finalRequest = request - - if - let originalRequest = task.originalRequest, - let urlString = originalRequest.url?.urlString, - urlString.contains("apple.com") - { - finalRequest = originalRequest - } - - return finalRequest -} -``` - -#### Subclassing - -Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. - -```swift -class LoggingSessionDelegate: SessionDelegate { - override func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) - { - print("URLSession will perform HTTP redirection to request: \(request)") - - super.urlSession( - session, - task: task, - willPerformHTTPRedirection: response, - newRequest: request, - completionHandler: completionHandler - ) - } -} -``` - -Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. - -> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. - -### Request - -The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. - -Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. - -Requests can be suspended, resumed and cancelled: - -- `suspend()`: Suspends the underlying task and dispatch queue. -- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. -- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. - -### Routing Requests - -As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. - -#### URLConvertible - -Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: - -```swift -let urlString = "https://httpbin.org/post" -Alamofire.request(urlString, method: .post) - -let url = URL(string: urlString)! -Alamofire.request(url, method: .post) - -let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! -Alamofire.request(urlComponents, method: .post) -``` - -Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. - -##### Type-Safe Routing - -```swift -extension User: URLConvertible { - static let baseURLString = "https://example.com" - - func asURL() throws -> URL { - let urlString = User.baseURLString + "/users/\(username)/" - return try urlString.asURL() - } -} -``` - -```swift -let user = User(username: "mattt") -Alamofire.request(user) // https://example.com/users/mattt -``` - -#### URLRequestConvertible - -Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): - -```swift -let url = URL(string: "https://httpbin.org/post")! -var urlRequest = URLRequest(url: url) -urlRequest.httpMethod = "POST" - -let parameters = ["foo": "bar"] - -do { - urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) -} catch { - // No-op -} - -urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - -Alamofire.request(urlRequest) -``` - -Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. - -##### API Parameter Abstraction - -```swift -enum Router: URLRequestConvertible { - case search(query: String, page: Int) - - static let baseURLString = "https://example.com" - static let perPage = 50 - - // MARK: URLRequestConvertible - - func asURLRequest() throws -> URLRequest { - let result: (path: String, parameters: Parameters) = { - switch self { - case let .search(query, page) where page > 0: - return ("/search", ["q": query, "offset": Router.perPage * page]) - case let .search(query, _): - return ("/search", ["q": query]) - } - }() - - let url = try Router.baseURLString.asURL() - let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) - - return try URLEncoding.default.encode(urlRequest, with: result.parameters) - } -} -``` - -```swift -Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 -``` - -##### CRUD & Authorization - -```swift -import Alamofire - -enum Router: URLRequestConvertible { - case createUser(parameters: Parameters) - case readUser(username: String) - case updateUser(username: String, parameters: Parameters) - case destroyUser(username: String) - - static let baseURLString = "https://example.com" - - var method: HTTPMethod { - switch self { - case .createUser: - return .post - case .readUser: - return .get - case .updateUser: - return .put - case .destroyUser: - return .delete - } - } - - var path: String { - switch self { - case .createUser: - return "/users" - case .readUser(let username): - return "/users/\(username)" - case .updateUser(let username, _): - return "/users/\(username)" - case .destroyUser(let username): - return "/users/\(username)" - } - } - - // MARK: URLRequestConvertible - - func asURLRequest() throws -> URLRequest { - let url = try Router.baseURLString.asURL() - - var urlRequest = URLRequest(url: url.appendingPathComponent(path)) - urlRequest.httpMethod = method.rawValue - - switch self { - case .createUser(let parameters): - urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) - case .updateUser(_, let parameters): - urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) - default: - break - } - - return urlRequest - } -} -``` - -```swift -Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt -``` - -### Adapting and Retrying Requests - -Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. - -The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. - -#### RequestAdapter - -The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. - -```swift -class AccessTokenAdapter: RequestAdapter { - private let accessToken: String - - init(accessToken: String) { - self.accessToken = accessToken - } - - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - var urlRequest = urlRequest - - if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { - urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") - } - - return urlRequest - } -} -``` - -```swift -let sessionManager = SessionManager() -sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") - -sessionManager.request("https://httpbin.org/get") -``` - -#### RequestRetrier - -The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. - -> **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. - -> To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. - -```swift -class OAuth2Handler: RequestAdapter, RequestRetrier { - private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void - - private let sessionManager: SessionManager = { - let configuration = URLSessionConfiguration.default - configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders - - return SessionManager(configuration: configuration) - }() - - private let lock = NSLock() - - private var clientID: String - private var baseURLString: String - private var accessToken: String - private var refreshToken: String - - private var isRefreshing = false - private var requestsToRetry: [RequestRetryCompletion] = [] - - // MARK: - Initialization - - public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { - self.clientID = clientID - self.baseURLString = baseURLString - self.accessToken = accessToken - self.refreshToken = refreshToken - } - - // MARK: - RequestAdapter - - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { - var urlRequest = urlRequest - urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") - return urlRequest - } - - return urlRequest - } - - // MARK: - RequestRetrier - - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { - lock.lock() ; defer { lock.unlock() } - - if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { - requestsToRetry.append(completion) - - if !isRefreshing { - refreshTokens { [weak self] succeeded, accessToken, refreshToken in - guard let strongSelf = self else { return } - - strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } - - if let accessToken = accessToken, let refreshToken = refreshToken { - strongSelf.accessToken = accessToken - strongSelf.refreshToken = refreshToken - } - - strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } - strongSelf.requestsToRetry.removeAll() - } - } - } else { - completion(false, 0.0) - } - } - - // MARK: - Private - Refresh Tokens - - private func refreshTokens(completion: @escaping RefreshCompletion) { - guard !isRefreshing else { return } - - isRefreshing = true - - let urlString = "\(baseURLString)/oauth2/token" - - let parameters: [String: Any] = [ - "access_token": accessToken, - "refresh_token": refreshToken, - "client_id": clientID, - "grant_type": "refresh_token" - ] - - sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) - .responseJSON { [weak self] response in - guard let strongSelf = self else { return } - - if - let json = response.result.value as? [String: Any], - let accessToken = json["access_token"] as? String, - let refreshToken = json["refresh_token"] as? String - { - completion(true, accessToken, refreshToken) - } else { - completion(false, nil, nil) - } - - strongSelf.isRefreshing = false - } - } -} -``` - -```swift -let baseURLString = "https://some.domain-behind-oauth2.com" - -let oauthHandler = OAuth2Handler( - clientID: "12345678", - baseURLString: baseURLString, - accessToken: "abcd1234", - refreshToken: "ef56789a" -) - -let sessionManager = SessionManager() -sessionManager.adapter = oauthHandler -sessionManager.retrier = oauthHandler - -let urlString = "\(baseURLString)/some/endpoint" - -sessionManager.request(urlString).validate().responseJSON { response in - debugPrint(response) -} -``` - -Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. - -> If you needed them to execute in the same order they were created, you could sort them by their task identifiers. - -The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. - -Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. - -### Custom Response Serialization - -Alamofire provides built-in response serialization for data, strings, JSON, and property lists: - -```swift -Alamofire.request(...).responseData { (resp: DataResponse) in ... } -Alamofire.request(...).responseString { (resp: DataResponse) in ... } -Alamofire.request(...).responseJSON { (resp: DataResponse) in ... } -Alamofire.request(...).responsePropertyList { (resp: DataResponse) in ... } -``` - -Those responses wrap deserialized *values* (Data, String, Any) or *errors* (network, validation errors), as well as *meta-data* (URL request, HTTP headers, status code, [metrics](#statistical-metrics), ...). - -You have several ways to customize all of those response elements: - -- [Response Mapping](#response-mapping) -- [Handling Errors](#handling-errors) -- [Creating a Custom Response Serializer](#creating-a-custom-response-serializer) -- [Generic Response Object Serialization](#generic-response-object-serialization) - -#### Response Mapping - -Response mapping is the simplest way to produce customized responses. It transforms the value of a response, while preserving eventual errors and meta-data. For example, you can turn a json response `DataResponse` into a response that holds an application model, such as `DataResponse`. You perform response mapping with the `DataResponse.map` method: - -```swift -Alamofire.request("https://example.com/users/mattt").responseJSON { (response: DataResponse) in - let userResponse = response.map { json in - // We assume an existing User(json: Any) initializer - return User(json: json) - } - - // Process userResponse, of type DataResponse: - if let user = userResponse.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -When the transformation may throw an error, use `flatMap` instead: - -```swift -Alamofire.request("https://example.com/users/mattt").responseJSON { response in - let userResponse = response.flatMap { json in - try User(json: json) - } -} -``` - -Response mapping is a good fit for your custom completion handlers: - -```swift -@discardableResult -func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { - return Alamofire.request("https://example.com/users/mattt").responseJSON { response in - let userResponse = response.flatMap { json in - try User(json: json) - } - - completionHandler(userResponse) - } -} - -loadUser { response in - if let user = response.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -When the map/flatMap closure may process a big amount of data, make sure you execute it outside of the main thread: - -```swift -@discardableResult -func loadUser(completionHandler: @escaping (DataResponse) -> Void) -> Alamofire.DataRequest { - let utilityQueue = DispatchQueue.global(qos: .utility) - - return Alamofire.request("https://example.com/users/mattt").responseJSON(queue: utilityQueue) { response in - let userResponse = response.flatMap { json in - try User(json: json) - } - - DispatchQueue.main.async { - completionHandler(userResponse) - } - } -} -``` - -`map` and `flatMap` are also available for [download responses](#downloading-data-to-a-file). - -#### Handling Errors - -Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. - -For example, here's a simple `BackendError` enum which will be used in later examples: - -```swift -enum BackendError: Error { - case network(error: Error) // Capture any underlying Error from the URLSession API - case dataSerialization(error: Error) - case jsonSerialization(error: Error) - case xmlSerialization(error: Error) - case objectSerialization(reason: String) -} -``` - -#### Creating a Custom Response Serializer - -Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. - -For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: - -```swift -extension DataRequest { - static func xmlResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { request, response, data, error in - // Pass through any underlying URLSession error to the .network case. - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has - // already been handled. - let result = Request.serializeResponseData(response: response, data: data, error: nil) - - guard case let .success(validData) = result else { - return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) - } - - do { - let xml = try ONOXMLDocument(data: validData) - return .success(xml) - } catch { - return .failure(BackendError.xmlSerialization(error: error)) - } - } - } - - @discardableResult - func responseXMLDocument( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - return response( - queue: queue, - responseSerializer: DataRequest.xmlResponseSerializer(), - completionHandler: completionHandler - ) - } -} -``` - -#### Generic Response Object Serialization - -Generics can be used to provide automatic, type-safe response object serialization. - -```swift -protocol ResponseObjectSerializable { - init?(response: HTTPURLResponse, representation: Any) -} - -extension DataRequest { - func responseObject( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self - { - let responseSerializer = DataResponseSerializer { request, response, data, error in - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) - let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) - - guard case let .success(jsonObject) = result else { - return .failure(BackendError.jsonSerialization(error: result.error!)) - } - - guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { - return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) - } - - return .success(responseObject) - } - - return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -struct User: ResponseObjectSerializable, CustomStringConvertible { - let username: String - let name: String - - var description: String { - return "User: { username: \(username), name: \(name) }" - } - - init?(response: HTTPURLResponse, representation: Any) { - guard - let username = response.url?.lastPathComponent, - let representation = representation as? [String: Any], - let name = representation["name"] as? String - else { return nil } - - self.username = username - self.name = name - } -} -``` - -```swift -Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in - debugPrint(response) - - if let user = response.result.value { - print("User: { username: \(user.username), name: \(user.name) }") - } -} -``` - -The same approach can also be used to handle endpoints that return a representation of a collection of objects: - -```swift -protocol ResponseCollectionSerializable { - static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] -} - -extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { - static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { - var collection: [Self] = [] - - if let representation = representation as? [[String: Any]] { - for itemRepresentation in representation { - if let item = Self(response: response, representation: itemRepresentation) { - collection.append(item) - } - } - } - - return collection - } -} -``` - -```swift -extension DataRequest { - @discardableResult - func responseCollection( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self - { - let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in - guard error == nil else { return .failure(BackendError.network(error: error!)) } - - let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) - let result = jsonSerializer.serializeResponse(request, response, data, nil) - - guard case let .success(jsonObject) = result else { - return .failure(BackendError.jsonSerialization(error: result.error!)) - } - - guard let response = response else { - let reason = "Response collection could not be serialized due to nil response." - return .failure(BackendError.objectSerialization(reason: reason)) - } - - return .success(T.collection(from: response, withRepresentation: jsonObject)) - } - - return response(responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} -``` - -```swift -struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { - let username: String - let name: String - - var description: String { - return "User: { username: \(username), name: \(name) }" - } - - init?(response: HTTPURLResponse, representation: Any) { - guard - let username = response.url?.lastPathComponent, - let representation = representation as? [String: Any], - let name = representation["name"] as? String - else { return nil } - - self.username = username - self.name = name - } -} -``` - -```swift -Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in - debugPrint(response) - - if let users = response.result.value { - users.forEach { print("- \($0)") } - } -} -``` - -### Security - -Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. - -#### ServerTrustPolicy - -The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. - -```swift -let serverTrustPolicy = ServerTrustPolicy.pinCertificates( - certificates: ServerTrustPolicy.certificates(), - validateCertificateChain: true, - validateHost: true -) -``` - -There are many different cases of server trust evaluation giving you complete control over the validation process: - -* `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. -* `pinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. -* `pinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. -* `disableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. -* `customEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. - -#### Server Trust Policy Manager - -The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. - -```swift -let serverTrustPolicies: [String: ServerTrustPolicy] = [ - "test.example.com": .pinCertificates( - certificates: ServerTrustPolicy.certificates(), - validateCertificateChain: true, - validateHost: true - ), - "insecure.expired-apis.com": .disableEvaluation -] - -let sessionManager = SessionManager( - serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) -) -``` - -> Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. - -These server trust policies will result in the following behavior: - -- `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: - - Certificate chain MUST be valid. - - Certificate chain MUST include one of the pinned certificates. - - Challenge host MUST match the host in the certificate chain's leaf certificate. -- `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. -- All other hosts will use the default evaluation provided by Apple. - -##### Subclassing Server Trust Policy Manager - -If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. - -```swift -class CustomServerTrustPolicyManager: ServerTrustPolicyManager { - override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { - var policy: ServerTrustPolicy? - - // Implement your custom domain matching behavior... - - return policy - } -} -``` - -#### Validating the Host - -The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. - -> It is recommended that `validateHost` always be set to `true` in production environments. - -#### Validating the Certificate Chain - -Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. - -There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. - -> It is recommended that `validateCertificateChain` always be set to `true` in production environments. - -#### App Transport Security - -With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. - -If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. - -```xml - - NSAppTransportSecurity - - NSExceptionDomains - - example.com - - NSExceptionAllowsInsecureHTTPLoads - - NSExceptionRequiresForwardSecrecy - - NSIncludesSubdomains - - - NSTemporaryExceptionMinimumTLSVersion - TLSv1.2 - - - - -``` - -Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. - -> It is recommended to always use valid certificates in production environments. - -#### Using Self-Signed Certificates with Local Networking - -If you are attempting to connect to a server running on your localhost, and you are using self-signed certificates, you will need to add the following to your `Info.plist`. - -```xml - - NSAppTransportSecurity - - NSAllowsLocalNetworking - - - -``` - -According to [Apple documentation](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35), setting `NSAllowsLocalNetworking` to `YES` allows loading of local resources without disabling ATS for the rest of your app. - -### Network Reachability - -The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. - -```swift -let manager = NetworkReachabilityManager(host: "www.apple.com") - -manager?.listener = { status in - print("Network Status Changed: \(status)") -} - -manager?.startListening() -``` - -> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. -> Also, do not include the scheme in the `host` string or reachability won't function correctly. - -There are some important things to remember when using network reachability to determine what to do next. - -- **Do NOT** use Reachability to determine if a network request should be sent. - - You should **ALWAYS** send it. -- When Reachability is restored, use the event to retry failed network requests. - - Even though the network requests may still fail, this is a good moment to retry them. -- The network reachability status can be useful for determining why a network request may have failed. - - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 2.0 Migration Guide.md b/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 2.0 Migration Guide.md deleted file mode 100644 index 5716906..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 2.0 Migration Guide.md +++ /dev/null @@ -1,202 +0,0 @@ -# Alamofire 2.0 Migration Guide - -Alamofire 2.0 is the latest major release of Alamofire, an HTTP networking library for iOS, Mac OS X and watchOS written in Swift. As a major release, following Semantic Versioning conventions, 2.0 introduces several API-breaking changes that one should be aware of. - -This guide is provided in order to ease the transition of existing applications using Alamofire 1.x to the latest APIs, as well as explain the design and structure of new and changed functionality. - -## New Requirements - -Alamofire 2.0 officially supports iOS 8+, Mac OS X 10.9+, Xcode 7 and Swift 2.0. If you'd like to use Alamofire in a project targeting iOS 7 and Swift 1.x, use the latest tagged 1.x release. - ---- - -## Breaking API Changes - -### Swift 2.0 - -The biggest change between Alamofire 1.x and Alamofire 2.0 is Swift 2.0. Swift 2 brought many new features to take advantage of such as error handling, protocol extensions and availability checking. Other new features such as `guard` and `defer` do not affect the public APIs, but allowed us to create much cleaner implementations of the same logic. All of the source files, test logic and example code has been updated to reflect the latest Swift 2.0 paradigms. - -> It is not possible to use Alamofire 2.0 without Swift 2.0. - -### Response Serializers - -The most significant logic change made to Alamofire 2.0 is its new response serialization system leveraging `Result` types. Previously in Alamofire 1.x, each response serializer used the same completion handler signature: - -```swift -public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self { - return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler) -} -``` - -Alamofire 2.0 has redesigned the entire response serialization process to make it much easier to access the original server data without serialization, or serialize the response into a non-optional `Result` type defining whether the `Request` was successful. - -#### No Response Serialization - -The first `response` serializer is non-generic and does not process the server data in any way. It merely forwards on the accumulated information from the `NSURLSessionDelegate` callbacks. - -```swift -public func response( - queue queue: dispatch_queue_t? = nil, - completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, ErrorType?) -> Void) - -> Self -{ - delegate.queue.addOperationWithBlock { - dispatch_async(queue ?? dispatch_get_main_queue()) { - completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) - } - } - - return self -} -``` - -Another important note of this change is the return type of `data` is now an `NSData` type. You no longer need to cast the `data` parameter from an `AnyObject?` to an `NSData?`. - -#### Generic Response Serializers - -The second, more powerful response serializer leverages generics along with a `Result` type to eliminate the case of the dreaded double optional. - -```swift -public func response( - queue queue: dispatch_queue_t? = nil, - responseSerializer: T, - completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result) -> Void) - -> Self -{ - delegate.queue.addOperationWithBlock { - let result: Result = { - if let error = self.delegate.error { - return .Failure(self.delegate.data, error) - } else { - return responseSerializer.serializeResponse(self.request, self.response, self.delegate.data) - } - }() - - dispatch_async(queue ?? dispatch_get_main_queue()) { - completionHandler(self.request, self.response, result) - } - } - - return self -} -``` - -##### Response Data - -```swift -Alamofire.request(.GET, "http://httpbin.org/get") - .responseData { _, _, result in - print("Success: \(result.isSuccess)") - print("Response: \(result)") - } -``` - -##### Response String - -```swift -Alamofire.request(.GET, "http://httpbin.org/get") - .responseString { _, _, result in - print("Success: \(result.isSuccess)") - print("Response String: \(result.value)") - } -``` - -##### Response JSON - -```swift -Alamofire.request(.GET, "http://httpbin.org/get") - .responseJSON { _, _, result in - print(result) - debugPrint(result) - } -``` - -#### Result Types - -The `Result` enumeration was added to handle the case of the double optional return type. Previously, the return value and error were both optionals. Checking if one was `nil` did not ensure the other was also not `nil`. This case has been blogged about many times and can be solved by a `Result` type. Alamofire 2.0 brings a `Result` type to the response serializers to make it much easier to handle success and failure cases. - -```swift -public enum Result { - case Success(Value) - case Failure(NSData?, ErrorType) -} -``` - -There are also many other convenience computed properties to make accessing the data inside easy. The `Result` type also conforms to the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to make it easier to debug. - -#### Error Types - -While Alamofire still only generates `NSError` objects, all `Result` types have been converted to store `ErrorType` objects to allow custom response serializer implementations to use any `ErrorType` they wish. This also includes the `ValidationResult` and `MultipartFormDataEncodingResult` types as well. - -### URLRequestConvertible - -In order to make it easier to deal with non-common scenarios, the `URLRequestConvertible` protocol now returns an `NSMutableURLRequest`. Alamofire 2.0 makes it much easier to customize the URL request after is has been encoded. This should only affect a small amount of users. - -```swift -public protocol URLRequestConvertible { - var URLRequest: NSMutableURLRequest { get } -} -``` - -### Multipart Form Data - -Encoding `MultipartFormData` previous returned an `EncodingResult` to encapsulate any possible errors that occurred during encoding. Alamofire 2.0 uses the new Swift 2.0 error handling instead making it easier to use. This change is mostly encapsulated internally and should only affect a very small subset of users. - ---- - -## Updated ACLs and New Features - -### Parameter Encoding - -#### ACL Updates - -The `ParameterEncoding` enumeration implementation was previously hidden behind `internal` and `private` ACLs. Alamofire 2.0 opens up the `queryComponents` and `escape` methods to make it much easier to implement `.Custom` cases. - -#### Encoding in the URL - -In the previous versions of Alamofire, `.URL` encoding would automatically append the query string to either the URL or HTTP body depending on which HTTP method was set in the `NSURLRequest`. While this satisfies the majority of common use cases, it made it quite difficult to append query string parameter to a URL for HTTP methods such as `PUT` and `POST`. In Alamofire 2.0, we've added a second URL encoding case, `.URLEncodedInURL`, that always appends the query string to the URL regardless of HTTP method. - -### Server Trust Policies - -In Alamofire 1.x, the `ServerTrustPolicyManager` methods were internal making it impossible to implement any custom domain matching behavior. Alamofire 2.0 opens up the internals with a `public` ACL allowing more flexible server trust policy matching behavior (i.e. wildcarded domains) through subclassing. - -```swift -class CustomServerTrustPolicyManager: ServerTrustPolicyManager { - override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { - var policy: ServerTrustPolicy? - - // Implement your custom domain matching behavior... - - return policy - } -} -``` - -### Download Requests - -The global and `Manager` download APIs now support `parameters` and `encoding` parameters to better support dynamic payloads used in background sessions. Constructing a `download` request is now the same as constructing a `data` request with the addition of a `destination` parameter. - -```swift -public func download( - method: Method, - _ URLString: URLStringConvertible, - parameters: [String: AnyObject]? = nil, - encoding: ParameterEncoding = .URL, - headers: [String: String]? = nil, - destination: Request.DownloadFileDestination) - -> Request -{ - return Manager.sharedInstance.download( - method, - URLString, - parameters: parameters, - encoding: encoding, - headers: headers, - destination: destination - ) -} -``` - -### Stream Tasks - -Alamofire 2.0 adds support for creating `NSURLSessionStreamTask` tasks for iOS 9 and OS X 10.11. It also extends the `SessionDelegate` to support all the new `NSURLSessionStreamDelegate` APIs. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 3.0 Migration Guide.md b/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 3.0 Migration Guide.md deleted file mode 100644 index 38736fc..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 3.0 Migration Guide.md +++ /dev/null @@ -1,186 +0,0 @@ -# Alamofire 3.0 Migration Guide - -Alamofire 3.0 is the latest major release of Alamofire, an HTTP networking library for iOS, Mac OS X and watchOS written in Swift. As a major release, following Semantic Versioning conventions, 3.0 introduces several API-breaking changes that one should be aware of. - -This guide is provided in order to ease the transition of existing applications using Alamofire 2.x to the latest APIs, as well as explain the design and structure of new and changed functionality. - -## Requirements - -Alamofire 3.0 officially supports iOS 8+, Mac OS X 10.9+, watchOS 2.0, Xcode 7 and Swift 2.0. If you'd like to use Alamofire in a project targeting iOS 7 and Swift 1.x, use the latest tagged 1.x release. - -## Reasons for Bumping to 3.0 - -The [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) (ASF) tries to do everything possible to avoid MAJOR version bumps. We realize the challenges involved with migrating large projects from one MAJOR version to another. With that said, we also want to make sure we're always producing the highest quality APIs and features possible. - -After releasing Alamofire 2.0, it became clear that the response serialization system still had some room for improvement. After much debate, we decided to strictly follow semver and move forward with all the core logic changes becoming Alamofire 3.0. We've also made some fairly significant changes that should give us more flexibility moving forward to help avoid the need for MAJOR version bumps to maintain backwards compatibility. - -## Benefits of Upgrading - -The benefits of upgrading can be summarized as follows: - -* No more casting a response serializer `error` from an `ErrorType` to an `NSError`. -* Original server data is now ALWAYS returned in all response serializers regardless of whether the result was a `.Success` or `.Failure`. -* Custom response serializers are now ALWAYS called regardless of whether an `error` occurred. -* Custom response serializers are now passed in the `error` allowing you to switch between different parsing schemes if necessary. -* Custom response serializers can now wrap up any Alamofire `NSError` into a `CustomError` type of your choosing. -* `Manager` initialization can now accept custom `NSURLSession` or `SessionDelegate` objects using dependency injection. - ---- - -## Breaking API Changes - -Alamofire 3.0 contains some breaking API changes to the foundational classes supporting the response serialization system. It is important to understand how these changes affect the common usage patterns. - -### Result Type - -The `Result` type was introduced in Alamofire 2.0 as a single generic parameter with the following signature: - -```swift -public enum Result { - case Success(Value) - case Failure(NSData?, ErrorType) -} -``` - -While this was a significant improvement on the behavior of Alamofire 1.0, there was still room for improvement. By defining the `.Failure` case to take an `ErrorType`, all consumers needed to cast the `ErrorType` to some concrete object such as an `NSError` before being able to interact with it. This was certainly not ideal. Additionally, by only allowing the `NSData?` from the server to be appended in a `.Failure` case, it was not possible to access the original server data in a `.Success` case. - -In Alamofire 3.0, the `Result` type has been redesigned to be a double generic type that does not store the `NSData?` in the `.Failure` case. - -```swift -public enum Result { - case Success(Value) - case Failure(Error) -} -``` - -These changes allow Alamofire to return the original server data in both cases. It also removes the requirement of having to cast the `ErrorType` when working with the `.Failure` case error object. - -### Response - -In order to avoid constantly having to change the response serializer completion closure signatures, Alamofire 3.0 introduces a `Response` struct. All response serializers (with the exception of `response`) return a generic `Response` struct. - -```swift -public struct Response { - /// The URL request sent to the server. - public let request: NSURLRequest? - - /// The server's response to the URL request. - public let response: NSHTTPURLResponse? - - /// The data returned by the server. - public let data: NSData? - - /// The result of response serialization. - public let result: Result -} -``` - -This unifies the signature of all response serializer completion closures by only needing to specify a single parameter rather than three or four. If another major release of Alamofire needs to modify the signature, thankfully the number of parameters in all response serializers will NOT need to change. Given the fact that the Swift compiler can present some fairly misleading compiler errors when the arguments are not correct, this should help alleviate some painful updates between MAJOR version bumps of Alamofire. - -### Response Serializers - -The biggest change in Alamofire 3.0 are the response serializers. They are now powered by the new `Response` struct and updated `Result` type. These two generic classes make it VERY easy to interact with the response serializers in a consistent, type-safe manner. - -```swift -Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) - .responseJSON { response in - debugPrint(response) // prints detailed description of all response properties - - print(response.request) // original URL request - print(response.response) // URL response - print(response.data) // server data - print(response.result) // result of response serialization - - if let JSON = response.result.value { - print("JSON: \(JSON)") - } - } -``` - -Besides the single response parameter in the completion closure, the other major callouts are that the original server data is always available whether the `Result` was a `.Success` or `.Failure`. Additionally, both the `value` and `error` of the `Result` type are strongly typed objects thanks to the power of generics. All default response serializer errors will be an `NSError` type. Custom response serializers can specify any custom `ErrorType`. - -#### Response Serializer Type - -For those wishing to create custom response serializer types, you'll need to familiarize yourself with the new `ResponseSerializerType` protocol and generic `ResponseSerializer` struct. - -```swift -public protocol ResponseSerializerType { - /// The type of serialized object to be created by this `ResponseSerializerType`. - typealias SerializedObject - - /// The type of error to be created by this `ResponseSerializer` if serialization fails. - typealias ErrorObject: ErrorType - - /** - A closure used by response handlers that takes a request, response, data and error and returns a result. - */ - var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } -} -``` - -All the possible information about the `Request` is now passed into the `serializeResponse` closure. In Alamofire 3.0, the `serializeResponse` closure is ALWAYS called whether an error occurred or not. This is for several reasons. - -1. Passing the error into the response serializer allows the implementation to switch parsing schemes based on what error occurred. For example, some APIs will return different payload schemas when certain errors occur. The new design allows you to switch on the error type and use different parsing logic. -2. Any error produced by Alamofire will always be an `NSError`. If your custom response serializer returns `CustomError` types, then the `NSError` returned by Alamofire must be converted into a `CustomError` type. This makes it MUCH easier to wrap Alamofire errors in your own `CustomError` type objects. - > This is also required for all the generics logic to work properly. - -### Validation Result - -The `ValidationResult` enumeration in Alamofire 3.0 has been updated to take an `NSError` in the `.Failure` case. The reasoning for this change is that all Alamofire errors generated need to be `NSError` types. If not, it introduces the need to cast all error objects coming from Alamofire at the response serializer level. - -```swift -public enum ValidationResult { - case Success - case Failure(NSError) -} -``` - -> If you are extending the `Request` type in any way that can produce an error, that error always needs to be of type `NSError`. If you'd like to wrap the error into a `CustomError` type, it should be wrapped in a custom response serializer implementation. - ---- - -## New Features - -### Dependency Injection - -Alamofire 3.0 leverages [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) to allow some powerful new customizations to take place for the URL session and delegate. - -#### Session Delegate - -In previous versions of Alamofire, the `SessionDelegate` was automatically created by the `Manager` instance. While this is convenient, it can be problematic for background sessions. One may need to hook up the task override closures before instantiating the URL session. Otherwise the URL session delegate could be called before the task override closures are able to be set. - -In Alamofire 3.0, the `Manager` initializer adds the ability to provide a custom `SessionDelegate` object with the task override closures already set using dependency injection. This greatly increases the flexibility of Alamofire in regards to background sessions. - -```swift -public init( - configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), - delegate: SessionDelegate = SessionDelegate(), - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) -{ - self.delegate = delegate - self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) -} -``` - -#### URL Session - -Alamofire 3.0 also adds the ability to use dependency injection to provide a custom `NSURLSession` to the `Manager` instance. This provides complete control over the URL session initialization if you need it allowing `NSURLSession` subclasses for various kinds of testing and DVR implementations. - -```swift -public init?( - session: NSURLSession, - delegate: SessionDelegate, - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) -{ - self.delegate = delegate - self.session = session - - guard delegate === session.delegate else { return nil } - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) -} -``` - -> We're very excited to see what the community comes up with given these new possibilities with Alamofire 3.0. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 4.0 Migration Guide.md b/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 4.0 Migration Guide.md deleted file mode 100644 index 2902dc6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Alamofire 4.0 Migration Guide.md +++ /dev/null @@ -1,930 +0,0 @@ -# Alamofire 4.0 Migration Guide - -Alamofire 4.0 is the latest major release of Alamofire, an HTTP networking library for iOS, tvOS, macOS and watchOS written in Swift. As a major release, following Semantic Versioning conventions, 4.0 introduces API-breaking changes. - -This guide is provided in order to ease the transition of existing applications using Alamofire 3.x to the latest APIs, as well as explain the design and structure of new and updated functionality. - -- [Requirements](#requirements) -- [Benefits of Upgrading](#benefits-of-upgrading) -- [Breaking API Changes](#breaking-api-changes) - - [Namespace Changes](#namespace-changes) - - [Making Requests](#making-requests) - - [URLStringConvertible](#urlstringconvertible) - - [URLRequestConvertible](#urlrequestconvertible) -- [New Features](#new-features) - - [Request Adapter](#request-adapter) - - [Request Retrier](#request-retrier) - - [Task Metrics](#task-metrics) -- [Updated Features](#updated-features) - - [Errors](#errors) - - [Parameter Encoding Protocol](#parameter-encoding-protocol) - - [Request Subclasses](#request-subclasses) - - [Response Validation](#response-validation) - - [Response Serializers](#response-serializers) - -## Requirements - -- iOS 8.0+, macOS 10.10.0+, tvOS 9.0+ and watchOS 2.0+ -- Xcode 8.1+ -- Swift 3.0+ - -For those of you that would like to use Alamofire on macOS 10.9, please use the latest tagged 3.x release which supports both Swift 2.2 and 2.3. - -## Benefits of Upgrading - -- **Complete Swift 3 Compatibility:** includes the full adoption of the new [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). -- **New Error System:** uses a new `AFError` type to adhere to the new pattern proposed in [SE-0112](https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md). -- **New RequestAdapter Protocol:** allows inspection and adaptation of every `URLRequest` before instantiating a `Request` allowing for easy modification of properties like the `Authorization` header. -- **New RequestRetrier Protocol:** allows you to inspect and retry any failed `Request` if necessary allowing you to build custom authentication solutions (OAuth1, OAuth2, xAuth, Basic Auth, etc.) around a set of requests. -- **New Parameter Encoding Protocol:** replaces the `ParameterEncoding` enumeration allowing for easier extension and customization and also throws errors on failure instead of returning a tuple. -- **New Request Types:** include `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` that implement specialized progress, validation and serialization APIs and behaviors per `Request` type. -- **New Progress APIs:** include `downloadProgress` and `uploadProgress` APIs supporting both `Progress` and `Int64` types and called on a specified dispatch queue defaulting to `.main`. -- **Enhanced Response Validation:** now includes the `data` or `temporaryURL` and `destinationURL` allowing inline closures to parse the server data for error messages if validation failed. -- **New Download Destinations:** allow you to have full control over the move operation on the file system by disabling it, removing a previous file and creating intermediate directories. -- **New Response Types:** unify response API signatures and expose `temporaryURL` and `downloadURL` properties for downloads and the all new task metrics on newer platforms. - ---- - -## Breaking API Changes - -Alamofire 4 has fully adopted all the new Swift 3 changes and conventions, including the new [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). Because of this, almost every API in Alamofire has been modified in some way. We can't possibly document every single change, so we're going to attempt to identify the most common APIs and how they have changed to help you through those sometimes less than helpful compiler errors. - -### Namespace Changes - -Some of the common classes have been moved into the global namespace to make them a bit easier to work with and to make them first class types. - -- `Manager` is now `SessionManager` -- `Request.TaskDelegate` is now `TaskDelegate` -- `Request.DataTaskDelegate` is now `DataTaskDelegate` -- `Request.DownloadTaskDelegate` is now `DownloadTaskDelegate` -- `Request.UploadTaskDelegate` is now `UploadTaskDelegate` - -We've also reorganized the file structure and organization patterns significantly to make it easier to follow the code. We hope that this will encourage more users to get to know the internal structure and implementation of Alamofire. Knowledge is power. - -### Making Requests - -Since making requests is certainly the most common operation in Alamofire, here are some examples of Alamofire 3.x requests compared to their new equivalents in Alamofire 4. - -#### Data Request - Simple with URL string - -```swift -// Alamofire 3 -Alamofire.request(.GET, urlString).response { request, response, data, error in - print(request) - print(response) - print(data) - print(error) -} - -// Alamofire 4 -Alamofire.request(urlString).response { response in // method defaults to `.get` - debugPrint(response) -} -``` - -#### Data Request - Complex with URL string - -```swift -// Alamofire 3 -let parameters: [String: AnyObject] = ["foo": "bar"] - -Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON) - .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in - print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)") - } - .validate { request, response in - // Custom evaluation closure (no access to server data) - return .success - } - .responseJSON { response in - debugPrint(response) - } - -// Alamofire 4 -let parameters: Parameters = ["foo": "bar"] - -Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default) - .downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in - print("Progress: \(progress.fractionCompleted)") - } - .validate { request, response, data in - // Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary) - return .success - } - .responseJSON { response in - debugPrint(response) - } -``` - -#### Download Request - Simple with URL string - -```swift -// Alamofire 3 -let destination = DownloadRequest.suggestedDownloadDestination() - -Alamofire.download(.GET, urlString, destination: destination).response { request, response, data, error in - // What is fileURL...not easy to get - print(request) - print(response) - print(data) - print(error) -} - -// Alamofire 4 -let destination = DownloadRequest.suggestedDownloadDestination() - -Alamofire.download(urlString, to: destination).response { response in // method defaults to `.get` - print(response.request) - print(response.response) - print(response.temporaryURL) - print(response.destinationURL) - print(response.error) -} -``` - -#### Download Request - Simple with URL request - -```swift -// Alamofire 3 -let destination = DownloadRequest.suggestedDownloadDestination() - -Alamofire.download(urlRequest, destination: destination).validate().responseData { response in - // What is fileURL...not easy to get - debugPrint(response) -} - -// Alamofire 4 -Alamofire.download(urlRequest, to: destination).validate().responseData { response in - debugPrint(response) - print(response.temporaryURL) - print(response.destinationURL) -} -``` - -#### Download Request - Complex with URL string - -```swift -// Alamofire 3 -let fileURL: NSURL -let destination: Request.DownloadFileDestination = { _, _ in fileURL } -let parameters: [String: AnyObject] = ["foo": "bar"] - -Alamofire.download(.GET, urlString, parameters: parameters, encoding: .JSON, to: destination) - .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in - print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)") - } - .validate { request, response in - // Custom evaluation implementation (no access to temporary or destination URLs) - return .success - } - .responseJSON { response in - print(fileURL) // Only accessible if captured in closure scope, not ideal - debugPrint(response) - } - -// Alamofire 4 -let fileURL: URL -let destination: DownloadRequest.DownloadFileDestination = { _, _ in - return (fileURL, [.createIntermediateDirectories, .removePreviousFile]) -} -let parameters: Parameters = ["foo": "bar"] - -Alamofire.download(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, to: destination) - .downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in - print("Progress: \(progress.fractionCompleted)") - } - .validate { request, response, temporaryURL, destinationURL in - // Custom evaluation closure now includes file URLs (allows you to parse out error messages if necessary) - return .success - } - .responseJSON { response in - debugPrint(response) - print(response.temporaryURL) - print(response.destinationURL) - } -``` - -#### Upload Request - Simple with URL string - -```swift -// Alamofire 3 -Alamofire.upload(.POST, urlString, data: data).response { request, response, data, error in - print(request) - print(response) - print(data) - print(error) -} - -// Alamofire 4 -Alamofire.upload(data, to: urlString).response { response in // method defaults to `.post` - debugPrint(response) -} -``` - -#### Upload Request - Simple with URL request - -```swift -// Alamofire 3 -Alamofire.upload(urlRequest, file: fileURL).validate().responseData { response in - debugPrint(response) -} - -// Alamofire 4 -Alamofire.upload(fileURL, with: urlRequest).validate().responseData { response in - debugPrint(response) -} -``` - -#### Upload Request - Complex with URL string - -```swift -// Alamofire 3 -Alamofire.upload(.PUT, urlString, file: fileURL) - .progress { bytes, totalBytes, totalBytesExpected in - // Are these for upload or for downloading the response? - print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)") - } - .validate { request, response in - // Custom evaluation implementation (no access to server data) - return .success - } - .responseJSON { response in - debugPrint(response) - } - -// Alamofire 4 -Alamofire.upload(fileURL, to: urlString, method: .put) - .uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in - print("Upload Progress: \(progress.fractionCompleted)") - } - .downloadProgress { progress in // called on main queue by default - print("Download Progress: \(progress.fractionCompleted)") - } - .validate { request, response, data in - // Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary) - return .success - } - .responseJSON { response in - debugPrint(response) - } -``` - -As you can see, there are many breaking API changes, but the common APIs still adhere to the original design goals of being able to make complex requests through a single line of code in a concise, well defined manner. - -### URLStringConvertible - -There are two changes to the `URLStringConvertible` protocol that are worth noting. - -#### URLConvertible - -The first MAJOR change worth noting on the `URLStringConvertible` is that it has been renamed to `URLConvertible`. In Alamofire 3.x, the `URLStringConvertible` was defined as: - -```swift -public protocol URLStringConvertible { - var URLString: String { get } -} -``` - -Now in Alamofire 4, the `URLConvertible` protocol is defined as: - -```swift -public protocol URLConvertible { - func asURL() throws -> URL -} -``` - -As you can see, the `URLString` property is completely gone and replaced by a new `asURL` method that throws. To explain, let's first backup. - -A VERY common problem in Alamofire is that users forget to percent escape their URL strings and Alamofire will crash. Up until now, we (the Alamofire team) have taken the stance that this is how Alamofire is designed and your URLs need to conform to [RFC 2396](https://tools.ietf.org/html/rfc2396). This is certainly not ideal for the community because we all would rather have Alamofire tell us that our URL was invalid rather than having it crash. - -Now, back to the new `URLConvertible` protocol. The reason Alamofire was not previously able to safely handle invalid URL strings was, in fact, due to the lack of safety on `URLStringConvertible`. It's not possible for Alamofire to know how to intelligently make an invalid URL string valid. Therefore, if the `URL` is unable to be created from the `URLConvertible`, an `AFError.invalidURL` error is thrown. - -This change (along with many others) allows Alamofire to safely handle invalid URLs and report the error back in the response handlers. - -#### URLRequest Conformance - -The `URLRequest` no longer conforms to the `URLStringConvertible`, now `URLConvertible` protocol. This was always a bit of a stretch in the previous versions of Alamofire and wasn't really necessary. It also had a high potential to introduce ambiguity into many Alamofire APIs. Because of these reasons, `URLRequest` no longer conforms to `URLStringConvertible` (now `URLConvertible`). - -What this means in code is that you can no longer do the following: - -```swift -let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) -let urlString = urlRequest.urlString -``` - -Instead, in Alamofire 4, you now have to do the following: - -```swift -let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) -let urlString = urlRequest.url?.absoluteString -``` - -> See [PR-1505](https://github.com/Alamofire/Alamofire/pull/1505) for more info. - -### URLRequestConvertible - -The `URLRequestConvertible` was susceptible to the same safety issues concerns as the `URLStringConvertible` in Alamofire 3.x. In Alamofire 3, the `URLRequestConvertible` was: - -```swift -public protocol URLRequestConvertible { - var URLRequest: URLRequest { get } -} -``` - -Now, in Alamofire 4, it is: - -```swift -public protocol URLRequestConvertible { - func asURLRequest() throws -> URLRequest -} -``` - -As you can see, the `URLRequest` property has been replaced by an `asURLRequest` method that throws when encountering an error generating the `URLRequest`. - -The most likely place this will affect your code is in the `Router` design pattern. If you have a `Router`, it's going to have to change, but for the better! You will now implement the `asURLRequest` method instead of the property which gives you the ability to throw an error if necessary. You no longer have to force unwrap unsafe data or parameters or wrap `ParameterEncoding` in a do-catch. Any error encountered in a `Router` can now be automatically handled by Alamofire. - -> See [PR-1505](https://github.com/Alamofire/Alamofire/pull/1505) for more info. - ---- - -## New Features - -### Request Adapter - -The `RequestAdapter` protocol is a completely new feature in Alamofire 4. - -```swift -public protocol RequestAdapter { - func adapt(_ urlRequest: URLRequest) throws -> URLRequest -} -``` - -It allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. - -```swift -class AccessTokenAdapter: RequestAdapter { - private let accessToken: String - - init(accessToken: String) { - self.accessToken = accessToken - } - - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - var urlRequest = urlRequest - - if urlRequest.urlString.hasPrefix("https://httpbin.org") { - urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") - } - - return urlRequest - } -} - -let sessionManager = SessionManager() -sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") - -sessionManager.request("https://httpbin.org/get") -``` - -If an `Error` occurs during the adaptation process, it should be thrown and will be delivered in the response handler of the `Request`. - -> See [PR-1450](https://github.com/Alamofire/Alamofire/pull/1450) for more info. - -### Request Retrier - -The `RequestRetrier` is another brand new Alamofire 4 protocol. - -```swift -public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void - -public protocol RequestRetrier { - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) -} -``` - -It allows a `Request` that encountered an `Error` while being executed to be retried with an optional delay if specified. - -```swift -class OAuth2Handler: RequestAdapter, RequestRetrier { - public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: RequestRetryCompletion) { - if let response = request.task.response as? HTTPURLResponse, response.statusCode == 401 { - completion(true, 1.0) // retry after 1 second - } else { - completion(false, 0.0) // don't retry - } - } -} - -let sessionManager = SessionManager() -sessionManager.retrier = OAuth2Handler() - -sessionManager.request(urlString).responseJSON { response in - debugPrint(response) -} -``` - -The retrier allows you to inspect the `Request` after it has completed and run all `Validation` closures to determine whether it should be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. For more information and examples on this topic, please refer to the README. - -> See [PR-1391](https://github.com/Alamofire/Alamofire/pull/1391) and [PR-1450](https://github.com/Alamofire/Alamofire/pull/1450) for more info. - -### Task Metrics - -In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to Alamofire's `Timeline`, but provide many more statistics that Alamofire was unable to compute. We're really excited about these APIs and have exposed them on each `Response` type meaning they couldn't be easier to use. - -```swift -Alamofire.request(urlString).response { response in - debugPrint(response.metrics) -} -``` - -It's important to note that these APIs are only available on iOS and tvOS 10+ and macOS 10.12+. Therefore, depending on your deployment target, you may need to use these inside availability checks: - -```swift -Alamofire.request(urlString).response { response in - if #available(iOS 10.0, *) { - debugPrint(response.metrics) - } -} -``` - -> See [PR-1492](https://github.com/Alamofire/Alamofire/pull/1492) for more info. - ---- - -## Updated Features - -Alamofire 4 contains many new features and enhancements on existing ones. This section is designed to give a brief overview of the features and demonstrate their uses. For more information on each each, please refer to the linked pull request. - -### Errors - -Alamofire 4 contains a completely new error system that adopts the new pattern proposed in [SE-0112](https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md). At the heart of the new error system is `AFError`, a new `Error` type enumeration backed by five main cases. - -- `.invalidURL(url: URLConvertible)` - Returned when a `URLConvertible` type fails to create a valid `URL`. -- `.parameterEncodingFailed(reason: ParameterEncodingFailureReason)` - Returned when a parameter encoding object throws an error during the encoding process. -- `.multipartEncodingFailed(reason: MultipartEncodingFailureReason)` - Returned when some step in the multipart encoding process fails. -- `.responseValidationFailed(reason: ResponseValidationFailureReason)` - Returned when a `validate()` call fails. -- `.responseSerializationFailed(reason: ResponseSerializationFailureReason)` - Returned when a response serializer encounters an error in the serialization process. - -Each case contains a specific failure reason which is another nested enumeration with multiple cases that contain additional information about the exact type of error that occurred. What this ultimately means is that is is much easier in Alamofire to identify where an error came from and what to do about it. - -```swift -Alamofire.request(urlString).responseJSON { response in - guard case let .failure(error) = response.result else { return } - - if let error = error as? AFError { - switch error { - case .invalidURL(let url): - print("Invalid URL: \(url) - \(error.localizedDescription)") - case .parameterEncodingFailed(let reason): - print("Parameter encoding failed: \(error.localizedDescription)") - print("Failure Reason: \(reason)") - case .multipartEncodingFailed(let reason): - print("Multipart encoding failed: \(error.localizedDescription)") - print("Failure Reason: \(reason)") - case .responseValidationFailed(let reason): - print("Response validation failed: \(error.localizedDescription)") - print("Failure Reason: \(reason)") - - switch reason { - case .dataFileNil, .dataFileReadFailed: - print("Downloaded file could not be read") - case .missingContentType(let acceptableContentTypes): - print("Content Type Missing: \(acceptableContentTypes)") - case .unacceptableContentType(let acceptableContentTypes, let responseContentType): - print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)") - case .unacceptableStatusCode(let code): - print("Response status code was unacceptable: \(code)") - } - case .responseSerializationFailed(let reason): - print("Response serialization failed: \(error.localizedDescription)") - print("Failure Reason: \(reason)") - } - - print("Underlying error: \(error.underlyingError)") - } else if let error = error as? URLError { - print("URLError occurred: \(error)") - } else { - print("Unknown error: \(error)") - } -} -``` - -This new design allows you to drill down into errors as deep as you may need to in order to figure out the best way to proceed. It also frees developers from the burden of having to deal with `NSError` types everywhere. By switching to our own custom `Error` type in Alamofire, we've been able to simplify the `Result` and `Response` generic types to only require a single generic parameter. This simplifies the response serialization logic. - -> See [PR-1419](https://github.com/Alamofire/Alamofire/pull/1419) for more info. - -### Parameter Encoding Protocol - -The `ParameterEncoding` enumeration has served us well for over two years at this point. However, it had some limitations that we wanted to address in Alamofire 4. - -- The `.url` case has always been a bit confusing since it selects a destination based on the HTTP method. -- The `.urlEncodedInURL` case has always been an eye sore to work around the behavior of the `.url` case. -- `.JSON` and `.PropertyList` encoding could not accept formatting or writing options. -- The `.Custom` encoding was a bit difficult for users to get the hang of. - -Because of these reasons, we decided to eliminate the enumeration altogether in Alamofire 4! Now, `ParameterEncoding` is a protocol backed by three concrete `URLEncoding`, `JSONEncoding` and `PropertyList` encoding structs with a new `Parameters` typealias for creating your parameter dictionaries. - -```swift -public typealias Parameters = [String: Any] - -public protocol ParameterEncoding { - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest -} -``` - -#### URL Encoding - -The new `URLEncoding` struct contains a `Destination` enumeration supporting three types of destinations: - -- `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. -- `.queryString` - Sets or appends encoded query string result to existing query string. -- `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. - -These destinations make it much easier to control where the parameters are encoded onto the `URLRequest`. Creating requests still uses the same signature as before in regards to parameter encoding and also has the same default behavior. - -```swift -let parameters: Parameters = ["foo": "bar"] - -Alamofire.request(urlString, parameters: parameters) // Encoding => URLEncoding(destination: .methodDependent) -Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding(destination: .queryString)) -Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding(destination: .httpBody)) - -// Static convenience properties (we'd like to encourage everyone to use this more concise form) -Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.default) -Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.queryString) -Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.httpBody) -``` - -#### JSON Encoding - -The new `JSONEncoding` struct exposes the ability to customize the JSON writing options. - -```swift -let parameters: Parameters = ["foo": "bar"] - -Alamofire.request(urlString, parameters: parameters, encoding: JSONEncoding(options: [])) -Alamofire.request(urlString, parameters: parameters, encoding: JSONEncoding(options: .prettyPrinted)) - -// Static convenience properties (we'd like to encourage everyone to use this more concise form) -Alamofire.request(urlString, parameters: parameters, encoding: JSONEncoding.default) -Alamofire.request(urlString, parameters: parameters, encoding: JSONEncoding.prettyPrinted) -``` - -#### Property List Encoding - -The new `PropertyListEncoding` struct allows customizing the plist format and write options. - -```swift -let parameters: Parameters = ["foo": "bar"] - -Alamofire.request(urlString, parameters: parameters, encoding: PropertyListEncoding(format: .xml, options: 0)) -Alamofire.request(urlString, parameters: parameters, encoding: PropertyListEncoding(format: .binary, options: 0)) - -// Static convenience properties (we'd like to encourage everyone to use this more concise form) -Alamofire.request(urlString, parameters: parameters, encoding: PropertyListEncoding.xml) -Alamofire.request(urlString, parameters: parameters, encoding: PropertyListEncoding.binary) -``` - -#### Custom Encoding - -Creating a custom custom `ParameterEncoding` is now as simple as implementing the protocol. For more examples on how to do this, please refer to the README. - -> See [PR-1465](https://github.com/Alamofire/Alamofire/pull/1465) for more info. - -### Request Subclasses - -In Alamofire 4, the `request`, `download`, `upload` and `stream` APIs no longer return a `Request`. Instead, they return a specific type of `Request` subclass. There were several motivating factors and community questions that led us to making this change: - -- **Progress:** The behavior of the `progress` method was confusing for upload requests. - - What does `progress` report on an upload `Request`? The progress of the upload? The progress of the response download? - - If it reports both, how do you know if or when it switches? -- **Response Serializers:** The response serializers were designed for data and upload requests, not download or stream requests. - - How do you access the fileURL when a download is complete? - - What would `responseData`, `responseString` or `responseJSON` do for a download request? Stream request? - -At a high level, Alamofire 4 now has four `Request` subclasses that each support their own custom chained APIs. This allows each subclass to create extensions tailored to that specific type of request. - -```swift -open class Request { - // Contains common properties, authentication and state methods as well as - // CustomStringConvertible and CustomDebugStringConvertible conformance -} - -open class DataRequest: Request { - // Contains stream (not to be confused with StreamRequest) and download progress methods. -} - -open class DownloadRequest: Request { - // Contains download destination and options, resume data and download progress methods. -} - -open class UploadRequest: DataRequest { - // Inherits all DataRequest APIs and also contains upload progress methods. -} - -open class StreamRequest: Request { - // Only inherits Request APIs, there are no other custom APIs at this time. -} -``` - -By making this split, Alamofire 4 was able to create customized chaining APIs for each type of `Request`. This opened up all sorts of possibilities, but let's take a moment to focus on what this change means in terms of progress reporting and download destinations. - -> See [PR-1455](https://github.com/Alamofire/Alamofire/pull/1455) for more info. - -#### Download and Upload Progress - -The progress reporting system for data, download and upload requests has been completely redesigned. Each request type contains progress APIs for executing a closure during each progress update by returning the underlying `Progress` instance. The closure will be called on the specified queue that defaults to main. - -**Data Request Progress** - -```swift -Alamofire.request(urlString) - .downloadProgress { progress in - // Called on main dispatch queue by default - print("Download progress: \(progress.fractionCompleted)") - } - .responseJSON { response in - debugPrint(response) - } -``` - -**Download Request Progress** - -```swift -Alamofire.download(urlString, to: destination) - .downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in - // Called on utility dispatch queue - print("Download progress: \(progress.fractionCompleted)") - } - .responseJSON { response in - debugPrint(response) - } -``` - -**Upload Request Progress** - -```swift -Alamofire.upload(data, to: urlString, withMethod: .post) - .uploadProgress { progress in - // Called on main dispatch queue by default - print("Upload progress: \(progress.fractionCompleted)") - } - .downloadProgress { progress in - // Called on main dispatch queue by default - print("Download progress: \(progress.fractionCompleted)") - } - .responseData { response in - debugPrint(response) - } -``` - -It's now easy to differentiate between upload and download progress for upload requests. - -> See [PR-1455](https://github.com/Alamofire/Alamofire/pull/1455) for more info. - -#### Download File Destinations - -In Alamofire 3.x, successful download requests would always move the temporary file to a final destination URL provided by the `destination` closure. While this was a nice convenience, it had several limitations: - -- `Forced` - The API forces you to provide a destination closure to move the file even if you have a valid use case for not moving it. -- `Limiting` - There was no way to adjust the file system prior to moving the file. - - What if you need to delete a pre-existing file at the destination URL before moving the temporary file? - - What if you need to create intermediate directories to the destination URL before moving the temporary file? - -These limitations led to several enhancements in Alamofire 4. The first of which is the optionality of the destination closure. Now, by default, the `destination` closure is `nil` which means the file is not moved anywhere on the file system and the temporary URL is returned. - -```swift -Alamofire.download(urlString).responseData { response in - print("Temporary URL: \(response.temporaryURL)") -} -``` - -> We'll cover the `DownloadResponse` type in more detail in the [Response Serializers](#response-serializers) section. - -#### Download Options - -The other major change made was to add download options to the destination closure allowing more file system control over the move operation. To accomplish this, the `DownloadOptions` type was created and added to the `DownloadFileDestination` closure. - -```swift -public typealias DownloadFileDestination = ( - _ temporaryURL: URL, - _ response: HTTPURLResponse) - -> (destinationURL: URL, options: DownloadOptions) -``` - -The two currently supported `DownloadOptions` are: - -- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. -- `.removePreviousFile` - Removes a previous file from the destination URL if specified. - -They can then be used as follows: - -```swift -let destination: DownloadRequest.DownloadFileDestination = { _, _ in - return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) -} - -Alamofire.download(urlString, to: destination).response { response in - debugPrint(response) -} -``` - -If an error occurs during the file system operations, the `error` on the `DownloadResponse` will be of type `URLError`. - -> See [PR-1462](https://github.com/Alamofire/Alamofire/pull/1462) for more info. - -### Response Validation - -There were several opportunity areas for improving the response validation system in Alamofire 4. These areas included: - -- Exposing the underlying `data` to the `Validation` closure. -- Custom validation between different `Request` subclasses types allowing `temporaryURL` and `destinationURL` to be exposed for download requests. - -By creating `Request` subclasses, the validation closure typealias and request APIs were able to be tailored to each request type. - -#### Data Request - -The `Validation` closure exposed on the `DataRequest` (inherited by `UploadRequest`) is now as follows: - -```swift -extension DataRequest { - public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult -} -``` - -By exposing the `Data?` property directly in the closure, you no longer have to write an extension on `Request` to access it. Now you can do something like this: - -```swift -Alamofire.request(urlString) - .validate { request, response, data in - guard let data = data else { return .failure(customError) } - - // 1) Validate the response to make sure everything looks good - // 2) If validation fails, you can now parse the error message out of the - // data if necessary and add that to your custom error if you wish. - - return .success - } - .response { response in - debugPrint(response) - } -``` - -#### Download Request - -The `Validation` closure on the `DownloadRequest` is very similar to the `DataRequest` API, but tailored more to downloads. - -```swift -extension DownloadRequest { - public typealias Validation = ( - _ request: URLRequest?, - _ response: HTTPURLResponse, - _ temporaryURL: URL?, - _ destinationURL: URL?) - -> ValidationResult -} -``` - -The `temporaryURL` and `destinationURL` parameters now allow you access the data returned by the server directly in an inline closure. This allows you to inspect the data inside the file if you've determined you need to in order to create a custom error. - -```swift -Alamofire.download(urlString) - .validate { request, response, temporaryURL, destinationURL in - guard let fileURL = temporaryURL else { return .failure(customError) } - - do { - let _ = try Data(contentsOf: fileURL) - return .success - } catch { - return .failure(customError) - } - } - .response { response in - debugPrint(response) - } -``` - -By exposing the underlying server data directly to the inline closures, error messages embedded in those responses can be parsed out inside the `Validation` closure to create a custom error including the server error message. If the payload is the same schema as used in a response serializer closure, the response serializer could be called to parse out the error message rather than duplicating the logic. For an example of how to do this, please refer to the README. - -> See [PR-1461](https://github.com/Alamofire/Alamofire/pull/1461) for more info. - -### Response Serializers - -The response serialization system in Alamofire 3.x had several pretty severe limitations: - -- Response serialization APIs could be applied to download and stream requests but resulted in undefined behavior. - - How do you access the fileURL when a download is complete? - - What would `responseData`, `responseString` or `responseJSON` do when chained onto a download request? A stream request? -- The `response` API returned 4 parameters instead of an encapsulating `Response` type. - - The biggest issue here is that any change to that API could not be done in a backwards compatible manner. - - Created confusion when switching between the serialized and unserialized APIs which led to difficult to debug compiler errors. - -As you can see, there were some very strong limitations to this system in Alamofire 3.x. Therefore, in Alamofire 4, the `Request` type was first broken down into subclasses, which opened up the opportunity to create customized response serializers and APIs for specific types of requests. Before getting to far into response serializers, we should first walk through the new `Response` types. - -#### Default Data Response - -The `DefaultDataResponse` represents an unserialized server response. There's no Alamofire processing that happens, it just collects all the response information from the `SessionDelegate` APIs and returns it in a simple struct. - -```swift -public struct DefaultDataResponse { - public let request: URLRequest? - public let response: HTTPURLResponse? - public let data: Data? - public let error: Error? - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -} -``` - -This is the type of response you will get back from the `DataRequest.response` API. - -```swift -Alamofire.request(urlString).response { response in - debugPrint(response) -} - -Alamofire.upload(file, to: urlString).response { response in - debugPrint(response) -} -``` - -#### Data Response - -The generic `DataResponse` type is the same as the generic `Response` in Alamofire 3.x, but refactored and contains the new `metrics` property. - -```swift -public struct DataResponse { - public let request: URLRequest? - public let response: HTTPURLResponse? - public let data: Data? - public let result: Result - public let timeline: Timeline - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -} -``` - -You still have access to the same response serialization APIs as before on the `DataRequest` and `UploadRequest` types. - -```swift -Alamofire.request(urlString).responseJSON { response in - debugPrint(response) - print(response.result.isSuccess) -} - -Alamofire.upload(fileURL, to: urlString).responseData { response in - debugPrint(response) - print(response.result.isSuccess) -} -``` - -#### Default Download Response - -Since downloads work differently than data and upload requests, Alamofire 4 contains custom download `Response` types tailored to their behavior. The `DefaultDownloadResponse` type represents an unserialized server response for a `DownloadRequest` that collects all the `SessionDelegate` information into a simple struct. - -```swift -public struct DefaultDownloadResponse { - public let request: URLRequest? - public let response: HTTPURLResponse? - public let temporaryURL: URL? - public let destinationURL: URL? - public let resumeData: Data? - public let error: Error? - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -} -``` - -The `DefaultDownloadResponse` type is returned when using the new `DownloadRequest.response` API. - -```swift -Alamofire.download(urlString).response { response in - debugPrint(response) - print(response.temporaryURL) -} -``` - -#### Download Response - -The new generic `DownloadResponse` type is similar to the generic `DataResponse` type, but contains information tailored to download requests. The `DownloadResponse` type is returned when one of four new APIs exposed on the `DownloadRequest` type. These new APIs match the `DataRequest` ones, and provide the same functionality by loading the data from the underlying temporary or destination URL. - -```swift -Alamofire.download(urlString, to: destination) - .responseData { response in - debugPrint(response) - } - .responseString { response in - debugPrint(response) - } - .responseJSON { response in - debugPrint(response) - } - .responsePropertyList { response in - debugPrint(response) - } -``` - -These new response serialization APIs make it MUCH easier to download a request to a file and serialize the response all in a single call. - -#### Custom Response Serializers - -If you have created your own custom response serializers, you may want to extend support across both data and download requests similar to what we've done with the Alamofire response serializers. If you do decide to do this, take a close look at how Alamofire shares the response serializer implementation between both request types by moving the implementation to the `Request`. This allowed us to DRY up our logic to avoid duplication between types. - -> See [PR-1457](https://github.com/Alamofire/Alamofire/pull/1457) for more info. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Usage.md b/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Usage.md deleted file mode 100644 index 308b541..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Documentation/Usage.md +++ /dev/null @@ -1,844 +0,0 @@ -- [Using Alamofire](#using-alamofire) - * [Introduction](#introduction) - - [Aside: The `AF` Namespace](#aside--the--af--namespace) - * [Making Requests](#making-requests) - + [HTTP Methods](#http-methods) - + [Request Parameters and Parameter Encoders](#request-parameters-and-parameter-encoders) - - [`URLEncodedFormParameterEncoder`](#-urlencodedformparameterencoder-) - * [GET Request With URL-Encoded Parameters](#get-request-with-url-encoded-parameters) - * [POST Request With URL-Encoded Parameters](#post-request-with-url-encoded-parameters) - * [Configuring the Sorting of Encoded Parameters](#configuring-the-sorting-of-encoded-parameters) - * [Configuring the Encoding of `Array` Parameters](#configuring-the-encoding-of--array--parameters) - * [Configuring the Encoding of `Bool` Parameters](#configuring-the-encoding-of--bool--parameters) - * [Configuring the Encoding of `Data` Parameters](#configuring-the-encoding-of--data--parameters) - * [Configuring the Encoding of `Date` Parameters](#configuring-the-encoding-of--date--parameters) - * [Configuring the Encoding of Coding Keys](#configuring-the-encoding-of-coding-keys) - * [Configuring the Encoding of Spaces](#configuring-the-encoding-of-spaces) - - [`JSONParameterEncoder`](#-jsonparameterencoder-) - * [POST Request with JSON-Encoded Parameters](#post-request-with-json-encoded-parameters) - * [Configuring a Custom `JSONEncoder`](#configuring-a-custom--jsonencoder-) - * [Manual Parameter Encoding of a `URLRequest`](#manual-parameter-encoding-of-a--urlrequest-) - + [HTTP Headers](#http-headers) - + [Response Validation](#response-validation) - - [Automatic Validation](#automatic-validation) - - [Manual Validation](#manual-validation) - + [Response Handling](#response-handling) - - [Response Handler](#response-handler) - - [Response Data Handler](#response-data-handler) - - [Response String Handler](#response-string-handler) - - [Response JSON Handler](#response-json-handler) - - [Response `Decodable` Handler](#response--decodable--handler) - - [Chained Response Handlers](#chained-response-handlers) - - [Response Handler Queue](#response-handler-queue) - + [Response Caching](#response-caching) - + [Authentication](#authentication) - - [HTTP Basic Authentication](#http-basic-authentication) - - [Authentication with `URLCredential`](#authentication-with--urlcredential-) - - [Manual Authentication](#manual-authentication) - + [Downloading Data to a File](#downloading-data-to-a-file) - - [Download File Destination](#download-file-destination) - - [Download Progress](#download-progress) - - [Canceling and Resuming a Download](#canceling-and-resuming-a-download) - + [Uploading Data to a Server](#uploading-data-to-a-server) - - [Uploading Data](#uploading-data) - - [Uploading a File](#uploading-a-file) - - [Uploading Multipart Form Data](#uploading-multipart-form-data) - - [Upload Progress](#upload-progress) - + [Statistical Metrics](#statistical-metrics) - - [`URLSessionTaskMetrics`](#-urlsessiontaskmetrics-) - + [cURL Command Output](#curl-command-output) - -# Using Alamofire - -## Introduction -Alamofire provides an elegant and composable interface to HTTP network requests. It does not implement its own HTTP networking functionality. Instead it builds on top of Apple's [URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system/) provided by the Foundation framework. At the core of the system is [`URLSession`](https://developer.apple.com/documentation/foundation/urlsession) and the [`URLSessionTask`](https://developer.apple.com/documentation/foundation/urlsessiontask) subclasses. Alamofire wraps these APIs, and many others, in an easier to use interface and provides a variety of functionality necessary for modern application development using HTTP networking. However, it's important to know where many of Alamofire's core behaviors come from, so familiarity with the URL Loading System is important. Ultimately, the networking features of Alamofire are limited by the capabilities of that system, and the behaviors and best practices should always be remembered and observed. - -Additionally, networking in Alamofire (and the URL Loading System in general) is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. - -#### Aside: The `AF` Namespace -Previous versions of Alamofire's documentation used examples like `Alamofire.request()`. This API, while it appeared to require the `Alamofire` prefix, in fact worked fine without it. The `request` method and other functions were available globally in any file with `import Alamofire`. Starting in Alamofire 5, this functionality has been moved out of the global [namespace](https://en.wikipedia.org/wiki/Namespace) and into the `AF` enum, which acts as a namespace. This allows Alamofire to offer the same convenience functionality while not having to pollute the global namespace every time Alamofire is used. Similarly, types extended by Alamofire will use an `af` property extension to separate the functionality Alamofire adds from other extensions. - -## Making Requests -Alamofire provides a variety of convenience methods for making HTTP requests. At the simplest, just provide a `String` that can be converted into a `URL`: - -```swift -AF.request("https://httpbin.org/get").response { response in - debugPrint(response) -} -``` - -> All examples require `import Alamofire` somewhere in the source file. - -This is actually one form of the two top-level APIs on Alamofire's `Session` type for making requests. Its full definition looks like this: - -```swift -open func request(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil) -> DataRequest -``` -This method creates a `DataRequest` while allowing the composition of requests from individual components, such as the `method` and `headers`, while also allowing per-request `RequestInterceptor`s and `Encodable` parameters. - -> There are additional methods that allow you to make requests using `Parameters` dictionaries and `ParameterEncoding` types. This API is no longer recommended and will eventually be deprecated and removed from Alamofire. - -The second version of this API is much simpler: - -```swift -open func request(_ urlRequest: URLRequestConvertible, - interceptor: RequestInterceptor? = nil) -> DataRequest -``` - -This method creates a `DataRequest` for any type conforming to Alamofire's `URLRequestConvertible` protocol. All of the different parameters from the previous version are encapsulated in that value, which can give rise to very powerful abstractions. This is discussed in our [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) documentation. - -### HTTP Methods - -The `HTTPMethod` type lists the HTTP methods defined in [RFC 7231 §4.3](https://tools.ietf.org/html/rfc7231#section-4.3): - -```swift -public struct HTTPMethod: RawRepresentable, Equatable, Hashable { - public static let connect = HTTPMethod(rawValue: "CONNECT") - public static let delete = HTTPMethod(rawValue: "DELETE") - public static let get = HTTPMethod(rawValue: "GET") - public static let head = HTTPMethod(rawValue: "HEAD") - public static let options = HTTPMethod(rawValue: "OPTIONS") - public static let patch = HTTPMethod(rawValue: "PATCH") - public static let post = HTTPMethod(rawValue: "POST") - public static let put = HTTPMethod(rawValue: "PUT") - public static let trace = HTTPMethod(rawValue: "TRACE") - - public let rawValue: String - - public init(rawValue: String) { - self.rawValue = rawValue - } -} -``` - -These values can be passed as the `method` argument to the `AF.request` API: - -```swift -AF.request("https://httpbin.org/get") -AF.request("https://httpbin.org/post", method: .post) -AF.request("https://httpbin.org/put", method: .put) -AF.request("https://httpbin.org/delete", method: .delete) -``` - -It's important to remember that the different HTTP methods may have different semantics and require different parameter encodings depending on what the server expects. For instance, passing body data in a `GET` request is not supported by `URLSession` or Alamofire and will return an error. - -Alamofire also offers an extension on `URLRequest` to bridge the `httpMethod` property that returns a `String` to an `HTTPMethod` value: - -```swift -public extension URLRequest { - /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. - var method: HTTPMethod? { - get { return httpMethod.flatMap(HTTPMethod.init) } - set { httpMethod = newValue?.rawValue } - } -} -``` - -If you need to use an HTTP method that Alamofire's `HTTPMethod` type doesn't support, you can extend the type to add your custom values: - -```swift -extension HTTPMethod { - static let custom = HTTPMethod(rawValue: "CUSTOM") -} -``` - -### Request Parameters and Parameter Encoders - -Alamofire supports passing any `Encodable` type as the parameters of a request. These parameters are then passed through a type conforming to the `ParameterEncoder` protocol and added to the `URLRequest` which is then sent over the network. Alamofire includes two `ParameterEncoder` conforming types: `JSONParameterEncoder` and `URLEncodedFormParameterEncoder `. These types cover the most common encodings used by modern services (XML encoding is left as an exercise for the reader). - -```swift -struct Login: Encodable { - let email: String - let password: String -} - -let login = Login(email: "test@test.test", password: "testPassword") - -AF.request("https://httpbin.org/post", - method: .post, - parameters: login, - encoder: JSONParameterEncoder.default).response { response in - debugPrint(response) -} -``` - -#### `URLEncodedFormParameterEncoder` - -The `URLEncodedFormParameterEncoder` encodes values into a url-encoded string to be set as or appended to any existing URL query string or set as the HTTP body of the request. Controlling where the encoded string is set can be done by setting the `destination` of the encoding. The `URLEncodedFormParameterEncoder.Destination` enumeration has three cases: - -- `.methodDependent` - Applies the encoded query string result to existing query string for `.get`, `.head` and `.delete` requests and sets it as the HTTP body for requests with any other HTTP method. -- `.queryString` - Sets or appends the encoded string to the query of the request's `URL`. -- `.httpBody` - Sets the encoded string as the HTTP body of the `URLRequest`. - -The `Content-Type` HTTP header of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`, if `Content-Type` is not already set. - -Internally, `URLEncodedFormParameterEncoder` uses `URLEncodedFormEncoder` to perform the actual encoding from an `Encodable` type to a URL encoded form `String`. This encoder can be used to customize the encoding for various types, including `Array` using the `ArrayEncoding`, `Bool` using the `BoolEncoding`, `Data` using the `DataEncoding`, `Date` using the `DateEncoding`, coding keys using the `KeyEncoding`, and spaces using the `SpaceEncoding`. - -##### GET Request With URL-Encoded Parameters - -```swift -let parameters = ["foo": "bar"] - -// All three of these calls are equivalent -AF.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` -AF.request("https://httpbin.org/get", parameters: parameters, encoder: URLEncodedFormParameterEncoder.default) -AF.request("https://httpbin.org/get", parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .methodDependent)) - -// https://httpbin.org/get?foo=bar -``` - -##### POST Request With URL-Encoded Parameters - -```swift -let parameters: [String: [String]] = [ - "foo": ["bar"], - "baz": ["a", "b"], - "qux": ["x", "y", "z"] -] - -// All three of these calls are equivalent -AF.request("https://httpbin.org/post", method: .post, parameters: parameters) -AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default) -AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody)) - -// HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar" -``` - -#### Configuring the Sorting of Encoded Values - -Since Swift 4.2, the hashing algorithm used by Swift's `Dictionary` type produces a random internal ordering at runtime which differs between app launches. This can cause encoded parameters to change order, which may have an impact on caching and other behaviors. By default `URLEncodedFormEncoder` will sort its encoded key-value pairs. While this produces constant output for all `Encodable` types, it may not match the actual encoding order implemented by the type. You can set `alphabetizeKeyValuePairs` to `false` to return to implementation order, though that will also have the randomized `Dictionary` order as well. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `alphabetizeKeyValuePairs` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(alphabetizeKeyValuePairs: false)) -``` - -##### Configuring the Encoding of `Array` Parameters - -Since there is no published specification for how to encode collection types, by default Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - -The `URLEncodedFormEncoder.ArrayEncoding` enumeration provides the following methods for encoding `Array` parameters: - -- `.brackets` - An empty set of square brackets is appended to the key for every value. This is the default case. -- `.noBrackets` - No brackets are appended. The key is encoded as is. - -By default, Alamofire uses the `.brackets` encoding, where `foo = [1, 2]` is encoded as `foo[]=1&foo[]=2`. - -Using the `.noBrackets` encoding will encode `foo = [1, 2]` as `foo=1&foo=2`. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `ArrayEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(arrayEncoding: .noBrackets)) -``` - -##### Configuring the Encoding of `Bool` Parameters - -The `URLEncodedFormEncoder.BoolEncoding` enumeration provides the following methods for encoding `Bool` parameters: - -- `.numeric` - Encode `true` as `1` and `false` as `0`. This is the default case. -- `.literal` - Encode `true` and `false` as string literals. - -By default, Alamofire uses the `.numeric` encoding. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `BoolEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(boolEncoding: .numeric)) -``` - -##### Configuring the Encoding of `Data` Parameters - -`DataEncoding` includes the following methods for encoding `Data` parameters: - -- `.deferredToData` - Uses `Data`'s native `Encodable` support. -- `.base64` - Encodes `Data` as a Base 64 encoded `String`. This is the default case. -- `.custom((Data) -> throws -> String)` - Encodes `Data` using the given closure. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `DataEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(dataEncoding: .base64)) -``` - -##### Configuring the Encoding of `Date` Parameters - -Given the sheer number of ways to encode a `Date` into a `String`, `DateEncoding` includes the following methods for encoding `Date` parameters: - -- `.deferredToDate` - Uses `Date`'s native `Encodable` support. This is the default case. -- `.secondsSince1970` - Encodes `Date`s as seconds since midnight UTC on January 1, 1970. -- `.millisecondsSince1970` - Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. -- `.iso8601` - Encodes `Date`s according to the ISO 8601 and RFC3339 standards. -- `.formatted(DateFormatter)` - Encodes `Date`s using the given `DateFormatter`. -- `.custom((Date) throws -> String)` - Encodes `Date`s using the given closure. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `DateEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(dateEncoding: .iso8601)) -``` - -##### Configuring the Encoding of Coding Keys - -Due to the variety of parameter key styles, `KeyEncoding` provides the following methods to customize key encoding from keys in `lowerCamelCase`: - -- `.useDefaultKeys` - Uses the keys specified by each type. This is the default case. -- `.convertToSnakeCase` - Converts keys to snake case: `oneTwoThree` becomes `one_two_three`. -- `.convertToKebabCase` - Converts keys to kebab case: `oneTwoThree` becomes `one-two-three`. -- `.capitalized` - Capitalizes the first letter only, a.k.a `UpperCamelCase`: `oneTwoThree` becomes `OneTwoThree`. -- `.uppercased` - Uppercases all letters: `oneTwoThree` becomes `ONETWOTHREE`. -- `.lowercased` - Lowercases all letters: `oneTwoThree` becomes `onetwothree`. -- `.custom((String) -> String)` - Encodes keys using the given closure. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `KeyEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(keyEncoding: .convertToSnakeCase)) -``` - -##### Configuring the Encoding of Spaces - -Older form encoders used `+` to encode spaces and some servers still expect this encoding instead of the modern percent encoding, so Alamofire includes the following methods for encoding spaces: - -- `.percentEscaped` - Encodes space characters by applying standard percent escaping. `" "` is encoded as `"%20"`. This is the default case. -- `.plusReplaced` - Encodes space characters by replacing them with `+`. `" "` is encoded as `"+"`. - -You can create your own `URLEncodedFormParameterEncoder` and specify the desired `SpaceEncoding` in the initializer of the passed `URLEncodedFormEncoder`: - -```swift -let encoder = URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(spaceEncoding: .plusReplaced)) -``` - -#### `JSONParameterEncoder` - -`JSONParameterEncoder` encodes `Encodable` values using Swift's `JSONEncoder` and sets the result as the `httpBody` of the `URLRequest`. The `Content-Type` HTTP header field of an encoded request is set to `application/json` if not already set. - -##### POST Request with JSON-Encoded Parameters - -```swift -let parameters: [String: [String]] = [ - "foo": ["bar"], - "baz": ["a", "b"], - "qux": ["x", "y", "z"] -] - -AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default) -AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.prettyPrinted) -AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.sortedKeys) - -// HTTP body: {"baz":["a","b"],"foo":["bar"],"qux":["x","y","z"]} -``` - -##### Configuring a Custom `JSONEncoder` - -You can customize the behavior of `JSONParameterEncoder` by passing it a `JSONEncoder` instance configured to your needs: - -```swift -let encoder = JSONEncoder() -encoder.dateEncoding = .iso8601 -encoder.keyEncodingStrategy = .convertToSnakeCase -let parameterEncoder = JSONParameterEncoder(encoder: encoder) -``` - -##### Manual Parameter Encoding of a `URLRequest` - -The `ParameterEncoder` APIs can also be used outside of Alamofire by encoding parameters directly in `URLRequest`s. - -```swift -let url = URL(string: "https://httpbin.org/get")! -var urlRequest = URLRequest(url: url) - -let parameters = ["foo": "bar"] -let encodedURLRequest = try URLEncodedFormParameterEncoder.default.encode(parameters, - into: urlRequest) -``` - -### HTTP Headers - -Alamofire includes its own `HTTPHeaders` type, an order-preserving and case-insensitive representation of HTTP header name / value pairs. The `HTTPHeader` types encapsulate a single name / value pair and provides a variety of static values for common headers. - -Adding custom `HTTPHeaders` to a `Request` is as simple as passing a value to one of the `request` methods: - -```swift -let headers: HTTPHeaders = [ - "Authorization": "Basic VXNlcm5hbWU6UGFzc3dvcmQ=", - "Accept": "application/json" -] - -AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in - debugPrint(response) -} -``` - -`HTTPHeaders` can also be constructed from an array of `HTTPHeader` values: - -```swift -let headers: HTTPHeaders = [ - .authorization(username: "Username", password: "Password"), - .accept("application/json") -] - -AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in - debugPrint(response) -} -``` - -> For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Configurations](AdvancedUsage.md#session-manager) section. - -The default Alamofire `Session` provides a default set of headers for every `Request`. These include: - -- `Accept-Encoding`, which defaults to `br;q=1.0, gzip;q=0.8, deflate;q=0.6`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). -- `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). -- `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). - -If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated, and the configuration applied to a new `Session` instance. Use `URLSessionConfiguration.af.default` to customize your configuration while keeping Alamofire's default headers. - -### Response Validation - -By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate()` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. - -#### Automatic Validation - -The `validate()` API automatically validates that status codes are within the `200..<300` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. - -```swift -AF.request("https://httpbin.org/get").validate().responseJSON { response in - debugPrint(response) -} -``` - -#### Manual Validation - -```swift -AF.request("https://httpbin.org/get") - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .responseData { response in - switch response.result { - case .success: - print("Validation Successful") - case let .failure(error): - print(error) - } - } -``` - -### Response Handling - -Alamofire's `DataRequest` and `DownloadRequest` both have a corresponding response type: `DataResponse` and `DownloadResponse`. Both of these are composed of two generics: the serialized type and the error type. By default, all response values will produce the `AFError` error type (i.e. `DataResponse`). Alamofire uses the simpler `AFDataResponse` and `AFDownloadResponse`, in its public API, which always have `AFError` error types. `UploadRequest`, a subclass of `DataRequest`, uses the same `DataResponse` type. - -Handling the `DataResponse` of a `DataRequest` or `UploadRequest` made in Alamofire involves chaining a response handler like `responseJSON` onto the `DataRequest`: - -```swift -AF.request("https://httpbin.org/get").responseJSON { response in - debugPrint(response) -} -``` - -In the above example, the `responseJSON` handler is added to the `DataRequest` to be executed once the `DataRequest` is complete. The closure passed to the handler receives the `AFDataResponse` value produced by the `JSONResponseSerializer` from the response properties. - -Rather than blocking execution to wait for a response from the server, this closure is added as a [callback](https://en.wikipedia.org/wiki/Callback_%28computer_programming%29) to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. - -> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. - -Alamofire contains six different data response handlers by default, including: - -```swift -// Response Handler - Unserialized Response -func response(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self - -// Response Serializer Handler - Serialize using the passed Serializer -func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self - -// Response Data Handler - Serialized into Data -func responseData(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self - -// Response String Handler - Serialized into String -func responseString(queue: DispatchQueue = .main, - encoding: String.Encoding? = nil, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self - -// Response JSON Handler - Serialized into Any Using JSONSerialization -func responseJSON(queue: DispatchQueue = .main, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self - -// Response Decodable Handler - Serialized into Decodable Type -func responseDecodable(of type: T.Type = T.self, - queue: DispatchQueue = .main, - decoder: DataDecoder = JSONDecoder(), - completionHandler: @escaping (AFDataResponse) -> Void) -> Self -``` - -None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. - -> For example, response status codes in the `400..<500` and `500..<600` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. - -#### Response Handler - -The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the `URLSessionDelegate`. It is the Alamofire equivalent of using `cURL` to execute a `Request`. - -```swift -AF.request("https://httpbin.org/get").response { response in - debugPrint("Response: \(response)") -} -``` - -> We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. - -#### Response Data Handler - -The `responseData` handler uses a `DataResponseSerializer` to extract and validate the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be the `Data` returned from the server. - -```swift -AF.request("https://httpbin.org/get").responseData { response in - debugPrint("Response: \(response)") -} -``` - -#### Response String Handler - -The `responseString` handler uses a `StringResponseSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. - -```swift -AF.request("https://httpbin.org/get").responseString { response in - debugPrint("Response: \(response)") -} -``` - -> If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. - -#### Response JSON Handler - -The `responseJSON` handler uses a `JSONResponseSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `AFResult` will be a `.success` and the `value` will be of type `Any`. - -```swift -AF.request("https://httpbin.org/get").responseJSON { response in - debugPrint("Response: \(response)") -} -``` - -> JSON serialization in `responseJSON` is handled by the `JSONSerialization` API from the `Foundation` framework. - -#### Response `Decodable` Handler - -The `responseDecodable` handler uses a `DecodableResponseSerializer` to convert the `Data` returned by the server into the passed `Decodable` type using the specified `DataDecoder` (a protocol abstraction for `Decoder`s which can decode from `Data`). If no errors occur and the server data is successfully decoded into a `Decodable` type, the response `Result` will be a `.success` and the `value` will be of the passed type. - -```swift -struct HTTPBinResponse: Decodable { let url: String } - -AF.request("https://httpbin.org/get").responseDecodable(of: HTTPBinResponse.self) { response in - debugPrint("Response: \(response)") -} -``` - -#### Chained Response Handlers - -Response handlers can also be chained: - -```swift -Alamofire.request("https://httpbin.org/get") - .responseString { response in - print("Response String: \(response.value)") - } - .responseJSON { response in - print("Response JSON: \(response.value)") - } -``` - -> It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times, once for each response handler. Using multiple response handlers on the same `Request` should generally be avoided as best practice, especially in production environments. They should only be used for debugging or in circumstances where there is no better option. - -#### Response Handler Queue - -Closures passed to response handlers are executed on the `.main` queue by default, but a specific `DispatchQueue` can passed on which to execute the closure. Actual serialization work (conversion of `Data` to some other type) is always executed on a background queue. - -```swift -let utilityQueue = DispatchQueue.global(qos: .utility) - -AF.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in - print("Executed on utility queue.") - debugPrint(response) -} -``` - -### Response Caching - -Response caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. - -> By default, Alamofire leverages the `URLCache.shared` instance. In order to customize the `URLCache` instance used, see the [Session Configuration](AdvancedUsage.md#session-manager) section. - -### Authentication - -Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). - -> These authentication APIs are for servers which prompt for authorization, not general use with APIs which require an `Authenticate` or equivalent header. - -**Supported Authentication Schemes** - -- [HTTP Basic](https://en.wikipedia.org/wiki/Basic_access_authentication) -- [HTTP Digest](https://en.wikipedia.org/wiki/Digest_access_authentication) -- [Kerberos](https://en.wikipedia.org/wiki/Kerberos_%28protocol%29) -- [NTLM](https://en.wikipedia.org/wiki/NT_LAN_Manager) - -#### HTTP Basic Authentication - -The `authenticate` method on a `Request` will automatically provide a `URLCredential` when challenged with a `URLAuthenticationChallenge` when appropriate: - -```swift -let user = "user" -let password = "password" - -AF.request("https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(username: user, password: password) - .responseJSON { response in - debugPrint(response) - } -``` - -#### Authentication with `URLCredential` - -```swift -let user = "user" -let password = "password" - -let credential = URLCredential(user: user, password: password, persistence: .forSession) - -AF.request("https://httpbin.org/basic-auth/\(user)/\(password)") - .authenticate(with: credential) - .responseJSON { response in - debugPrint(response) - } -``` - -> It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. - -#### Manual Authentication - -If you are communicating with an API that always requires an `Authenticate` or similar header without prompting, it can be added manually: - -```swift -let user = "user" -let password = "password" - -let headers: HTTPHeaders = [.authorization(username: user, password: password)] - -AF.request("https://httpbin.org/basic-auth/user/password", headers: headers) - .responseJSON { response in - debugPrint(response) - } -``` - -However, headers that must be part of all requests are often better handled as part of a custom [`URLSessionConfiguration`](AdvancedUsage.md#session-manager), or by using a [`RequestAdapter`](AdvancedUsage.md#request-adapter). - -### Downloading Data to a File - -In addition to fetching data into memory, Alamofire also provides the `Session.download`, `DownloadRequest`, and `DownloadResponse` APIs to facilitate downloading to disk. While downloading into memory works great for small payloads like most JSON API responses, fetching larger assets like images and videos should be downloaded to disk to avoid memory issues with your application. - -```swift -AF.download("https://httpbin.org/image/png").responseData { response in - if let data = response.value { - let image = UIImage(data: data) - } -} -``` - -> `DownloadRequest` has most of the same `response` handlers that `DataRequest` does. However, since it downloads data to disk, serializing the response involves reading from disk, and may also involve reading large amounts of data into memory. It's important to keep these facts in mind when architecting your download handling. - -#### Download File Destination - -All downloaded data is initially stored in the system temporary directory. It will eventually be deleted by the system at some point in the future, so if it's something that needs to live longer, it's important to move the file somewhere else. - -You can provide a `Destination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `Options` specified in the closure will be executed. The two currently supported `Options` are: - -- `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. -- `.removePreviousFile` - Removes a previous file from the destination URL if specified. - -```swift -let destination: DownloadRequest.Destination = { _, _ in - let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] - let fileURL = documentsURL.appendingPathComponent("image.png") - - return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) -} - -AF.download("https://httpbin.org/image/png", to: destination).response { response in - debugPrint(response) - - if response.error == nil, let imagePath = response.fileURL?.path { - let image = UIImage(contentsOfFile: imagePath) - } -} -``` - -You can also use the suggested download destination API: - -```swift -let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) - -AF.download("https://httpbin.org/image/png", to: destination) -``` - -#### Download Progress - -Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. - -```swift -AF.download("https://httpbin.org/image/png") - .downloadProgress { progress in - print("Download Progress: \(progress.fractionCompleted)") - } - .responseData { response in - if let data = response.value { - let image = UIImage(data: data) - } - } -``` - -> The progress reporting APIs for `URLSession`, and therefore Alamofire, only work if the server properly returns a `Content-Length` header that can be used to calculate the progress. Without that header, progress will stay at `0.0` until the download completes, at which point the progress will jump to `1.0`. - -The `downloadProgress` API can also take a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. - -```swift -let utilityQueue = DispatchQueue.global(qos: .utility) - -AF.download("https://httpbin.org/image/png") - .downloadProgress(queue: utilityQueue) { progress in - print("Download Progress: \(progress.fractionCompleted)") - } - .responseData { response in - if let data = response.value { - let image = UIImage(data: data) - } - } -``` - -#### Canceling and Resuming a Download - -In addition to the `cancel()` API that all `Request` classes have, `DownloadRequest`s can also produce resume data, which can be used to later resume a download. There are two forms of this API: `cancel(producingResumeData: Bool)`, which allows control over whether resume data is produced, but only makes it available on the `DownloadResponse`; and `cancel(byProducingResumeData: (_ resumeData: Data?) -> Void)`, which performs the same actions but makes the resume data available in the completion handler. - -If a `DownloadRequest` is canceled or interrupted, the underlying `URLSessionDownloadTask` *may* generate resume data. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. - -> **IMPORTANT:** On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), `resumeData` is broken on background `URLSessionConfiguration`s. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this [Stack Overflow post](https://stackoverflow.com/a/39347461/1342462). - -```swift -var resumeData: Data! - -let download = AF.download("https://httpbin.org/image/png").responseData { response in - if let data = response.value { - let image = UIImage(data: data) - } -} - -// download.cancel(producingResumeData: true) // Makes resumeData available in response only. -download.cancel { data in - resumeData = data -} - -AF.download(resumingWith: resumeData).responseData { response in - if let data = response.value { - let image = UIImage(data: data) - } -} -``` - -### Uploading Data to a Server - -When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `request()` APIs are usually sufficient. If you need to send much larger amounts of data from `Data` in memory, a file `URL`, or an `InputStream`, then the `upload()` APIs are what you want to use. - -#### Uploading Data - -```swift -let data = Data("data".utf8) - -AF.upload(data, to: "https://httpbin.org/post").responseJSON { response in - debugPrint(response) -} -``` - -#### Uploading a File - -```swift -let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") - -AF.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in - debugPrint(response) -} -``` - -#### Uploading Multipart Form Data - -```swift -AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(Data("one".utf8), withName: "one") - multipartFormData.append(Data("two".utf8), withName: "two") -}, to: "https://httpbin.org/post") - .responseJSON { response in - debugPrint(response) - } -``` - -#### Upload Progress - -While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress of the upload and download progress of the response data download using the `uploadProgress` and `downloadProgress` APIs. - -```swift -let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") - -AF.upload(fileURL, to: "https://httpbin.org/post") - .uploadProgress { progress in - print("Upload Progress: \(progress.fractionCompleted)") - } - .downloadProgress { progress in - print("Download Progress: \(progress.fractionCompleted)") - } - .responseJSON { response in - debugPrint(response) - } -``` - -### Statistical Metrics - -#### `URLSessionTaskMetrics` - -Alamofire gathers `URLSessionTaskMetrics` for every `Request`. `URLSessionTaskMetrics` encapsulate some fantastic statistical information about the underlying network connection and request and response timing. - -```swift -AF.request("https://httpbin.org/get").responseJSON { response in - print(response.metrics) -} -``` - -### cURL Command Output - -Debugging platform issues can be frustrating. Thankfully, Alamofire's `Request` type can produce the equivalent cURL command for easy debugging. Due to the asynchronous nature of Alamofire's `Request` creation, this API has both synchronous and asynchronous versions. To get the cURL command as soon as possible, you can chain the `cURLDescription` onto a request: - -```swift -AF.request("https://httpbin.org/get") - .cURLDescription { description in - print(description) - } - .responseJSON { response in - debugPrint(response.metrics) - } -``` - -This should produce: - -```bash -$ curl -v \ --X GET \ --H "Accept-Language: en;q=1.0" \ --H "Accept-Encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8" \ --H "User-Agent: Demo/1.0 (com.demo.Demo; build:1; iOS 13.0.0) Alamofire/1.0" \ -"https://httpbin.org/get" -``` diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/LaunchScreen.storyboard b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 2d5bcd2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/Main.storyboard b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/Main.storyboard deleted file mode 100644 index b74839e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Base.lproj/Main.storyboard +++ /dev/null @@ -1,369 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/AppIcon.appiconset/Contents.json b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d8db8d6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "83.5x83.5", - "scale" : "2x" - }, - { - "idiom" : "ios-marketing", - "size" : "1024x1024", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Contents.json b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Contents.json b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Contents.json deleted file mode 100644 index bd086a5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Contents.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "Logo.png", - "scale" : "1x" - }, - { - "idiom" : "universal", - "filename" : "Logo@2x.png", - "scale" : "2x" - }, - { - "idiom" : "universal", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo.png b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo.png deleted file mode 100644 index 4060979..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo@2x.png b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo@2x.png deleted file mode 100644 index adbb083..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Images.xcassets/Logo.imageset/Logo@2x.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Info.plist b/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Info.plist deleted file mode 100644 index 5c42ca7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Resources/Info.plist +++ /dev/null @@ -1,57 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Alamofire - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UIStatusBarTintParameters - - UINavigationBar - - Style - UIBarStyleDefault - Translucent - - - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/AppDelegate.swift b/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/AppDelegate.swift deleted file mode 100644 index 74c07b0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/AppDelegate.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// AppDelegate.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import UIKit - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { - // MARK: - Properties - - var window: UIWindow? - - // MARK: - UIApplicationDelegate - - func application(_ application: UIApplication, - didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { - let splitViewController = window!.rootViewController as! UISplitViewController - let navigationController = splitViewController.viewControllers.last as! UINavigationController - navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem - splitViewController.delegate = self - - return true - } - - // MARK: - UISplitViewControllerDelegate - - func splitViewController(_ splitViewController: UISplitViewController, - collapseSecondary secondaryViewController: UIViewController, - onto primaryViewController: UIViewController) - -> Bool { - if - let secondaryAsNavController = secondaryViewController as? UINavigationController, - let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { - return topAsDetailController.request == nil - } - - return false - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/DetailViewController.swift b/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/DetailViewController.swift deleted file mode 100644 index 2cac437..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/DetailViewController.swift +++ /dev/null @@ -1,210 +0,0 @@ -// -// DetailViewController.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import UIKit - -class DetailViewController: UITableViewController { - enum Sections: Int { - case headers, body - } - - var request: Request? { - didSet { - oldValue?.cancel() - - title = request?.description - refreshControl?.endRefreshing() - headers.removeAll() - body = nil - elapsedTime = nil - } - } - - var headers: [String: String] = [:] - var body: String? - var elapsedTime: TimeInterval? - var segueIdentifier: String? - - static let numberFormatter: NumberFormatter = { - let formatter = NumberFormatter() - formatter.numberStyle = .decimal - return formatter - }() - - // MARK: View Lifecycle - - override func awakeFromNib() { - super.awakeFromNib() - refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), for: .valueChanged) - } - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - refresh() - } - - // MARK: IBActions - - @IBAction func refresh() { - guard let request = request else { - return - } - - refreshControl?.beginRefreshing() - - let start = CACurrentMediaTime() - - let requestComplete: (HTTPURLResponse?, Result) -> Void = { response, result in - let end = CACurrentMediaTime() - self.elapsedTime = end - start - - if let response = response { - for (field, value) in response.allHeaderFields { - self.headers["\(field)"] = "\(value)" - } - } - - if let segueIdentifier = self.segueIdentifier { - switch segueIdentifier { - case "GET", "POST", "PUT", "DELETE": - if case let .success(value) = result { self.body = value } - case "DOWNLOAD": - self.body = self.downloadedBodyString() - default: - break - } - } - - self.tableView.reloadData() - self.refreshControl?.endRefreshing() - } - - if let request = request as? DataRequest { - request.responseString { response in - requestComplete(response.response, response.result) - } - } else if let request = request as? DownloadRequest { - request.responseString { response in - requestComplete(response.response, response.result) - } - } - } - - private func downloadedBodyString() -> String { - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - - do { - let contents = try fileManager.contentsOfDirectory(at: cachesDirectory, - includingPropertiesForKeys: nil, - options: .skipsHiddenFiles) - - if let fileURL = contents.first, let data = try? Data(contentsOf: fileURL) { - let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) - let prettyData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) - - if let prettyString = String(data: prettyData, encoding: String.Encoding.utf8) { - try fileManager.removeItem(at: fileURL) - return prettyString - } - } - } catch { - // No-op - } - - return "" - } -} - -// MARK: - UITableViewDataSource - -extension DetailViewController { - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - switch Sections(rawValue: section)! { - case .headers: - return headers.count - case .body: - return body == nil ? 0 : 1 - } - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - switch Sections(rawValue: (indexPath as NSIndexPath).section)! { - case .headers: - let cell = tableView.dequeueReusableCell(withIdentifier: "Header")! - let field = headers.keys.sorted(by: <)[indexPath.row] - let value = headers[field] - - cell.textLabel?.text = field - cell.detailTextLabel?.text = value - - return cell - case .body: - let cell = tableView.dequeueReusableCell(withIdentifier: "Body")! - cell.textLabel?.text = body - - return cell - } - } -} - -// MARK: - UITableViewDelegate - -extension DetailViewController { - override func numberOfSections(in tableView: UITableView) -> Int { - return 2 - } - - override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { - if self.tableView(tableView, numberOfRowsInSection: section) == 0 { - return "" - } - - switch Sections(rawValue: section)! { - case .headers: - return "Headers" - case .body: - return "Body" - } - } - - override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - switch Sections(rawValue: (indexPath as NSIndexPath).section)! { - case .body: - return 300 - default: - return tableView.rowHeight - } - } - - override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { - if Sections(rawValue: section) == .body, let elapsedTime = elapsedTime { - let elapsedTimeText = DetailViewController.numberFormatter.string(from: elapsedTime as NSNumber) ?? "???" - return "Elapsed Time: \(elapsedTimeText) sec" - } - - return "" - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/MasterViewController.swift b/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/MasterViewController.swift deleted file mode 100644 index cfdec85..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/Source/MasterViewController.swift +++ /dev/null @@ -1,101 +0,0 @@ -// -// MasterViewController.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import UIKit - -class MasterViewController: UITableViewController { - // MARK: - Properties - - @IBOutlet var titleImageView: UIImageView! - - var detailViewController: DetailViewController? - var objects = NSMutableArray() - - private var reachability: NetworkReachabilityManager! - - // MARK: - View Lifecycle - - override func awakeFromNib() { - super.awakeFromNib() - - navigationItem.titleView = titleImageView - clearsSelectionOnViewWillAppear = true - - monitorReachability() - } - - // MARK: - UIStoryboardSegue - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if - let navigationController = segue.destination as? UINavigationController, - let detailViewController = navigationController.topViewController as? DetailViewController { - func requestForSegue(_ segue: UIStoryboardSegue) -> Request? { - switch segue.identifier! { - case "GET": - detailViewController.segueIdentifier = "GET" - return AF.request("https://httpbin.org/get") - case "POST": - detailViewController.segueIdentifier = "POST" - return AF.request("https://httpbin.org/post", method: .post) - case "PUT": - detailViewController.segueIdentifier = "PUT" - return AF.request("https://httpbin.org/put", method: .put) - case "DELETE": - detailViewController.segueIdentifier = "DELETE" - return AF.request("https://httpbin.org/delete", method: .delete) - case "DOWNLOAD": - detailViewController.segueIdentifier = "DOWNLOAD" - let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory, - in: .userDomainMask) - return AF.download("https://httpbin.org/stream/1", to: destination) - default: - return nil - } - } - - if let request = requestForSegue(segue) { - detailViewController.request = request - } - } - } - - // MARK: - UITableViewDelegate - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - if indexPath.section == 3 && indexPath.row == 0 { - print("Reachability Status: \(reachability.status)") - tableView.deselectRow(at: indexPath, animated: true) - } - } - - // MARK: - Private - Reachability - - private func monitorReachability() { - NetworkReachabilityManager.default?.startListening { status in - print("Reachability Status Changed: \(status)") - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.pbxproj b/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.pbxproj deleted file mode 100644 index 575b465..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.pbxproj +++ /dev/null @@ -1,515 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 3129D57622F230AE009C145F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3129D57422F230AE009C145F /* LaunchScreen.storyboard */; }; - 31E476821C55DE6D00968569 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 31E4766A1C55DD5900968569 /* Alamofire.framework */; }; - 31E476831C55DE6D00968569 /* Alamofire.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = 31E4766A1C55DD5900968569 /* Alamofire.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 4C6D2C801C67EFE100846168 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C6D2C7D1C67EFE100846168 /* AppDelegate.swift */; }; - 4C6D2C811C67EFE100846168 /* DetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C6D2C7E1C67EFE100846168 /* DetailViewController.swift */; }; - 4C6D2C821C67EFE100846168 /* MasterViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C6D2C7F1C67EFE100846168 /* MasterViewController.swift */; }; - 4C6D2C8F1C67EFEC00846168 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4C6D2C8C1C67EFEC00846168 /* Images.xcassets */; }; - 4C6D2C981C67F03B00846168 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4C6D2C961C67F03B00846168 /* Main.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 31E476691C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F8111E3319A95C8B0040E7D1; - remoteInfo = "Alamofire iOS"; - }; - 31E4766B1C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F8111E3E19A95C8B0040E7D1; - remoteInfo = "Alamofire iOS Tests"; - }; - 31E4766D1C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 4DD67C0B1A5C55C900ED2280; - remoteInfo = "Alamofire OSX"; - }; - 31E4766F1C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F829C6B21A7A94F100A2CD59; - remoteInfo = "Alamofire OSX Tests"; - }; - 31E476711C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 4CF626EF1BA7CB3E0011A099; - remoteInfo = "Alamofire tvOS"; - }; - 31E476731C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 4CF626F81BA7CB3E0011A099; - remoteInfo = "Alamofire tvOS Tests"; - }; - 31E476751C55DD5900968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = E4202FE01B667AA100C997FB; - remoteInfo = "Alamofire watchOS"; - }; - 31E476841C55DE6D00968569 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = F8111E3219A95C8B0040E7D1; - remoteInfo = "Alamofire iOS"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - F818D0E519CA8D15006034B1 /* Copy Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - 31E476831C55DE6D00968569 /* Alamofire.framework in Copy Frameworks */, - ); - name = "Copy Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 3129D57522F230AE009C145F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Resources/Base.lproj/LaunchScreen.storyboard; sourceTree = SOURCE_ROOT; }; - 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = Alamofire.xcodeproj; path = ../Alamofire.xcodeproj; sourceTree = ""; }; - 4C6D2C7D1C67EFE100846168 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = Source/AppDelegate.swift; sourceTree = SOURCE_ROOT; }; - 4C6D2C7E1C67EFE100846168 /* DetailViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DetailViewController.swift; path = Source/DetailViewController.swift; sourceTree = SOURCE_ROOT; }; - 4C6D2C7F1C67EFE100846168 /* MasterViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MasterViewController.swift; path = Source/MasterViewController.swift; sourceTree = SOURCE_ROOT; }; - 4C6D2C8C1C67EFEC00846168 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Resources/Images.xcassets; sourceTree = SOURCE_ROOT; }; - 4C6D2C8D1C67EFEC00846168 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Resources/Info.plist; sourceTree = SOURCE_ROOT; }; - 4C6D2C971C67F03B00846168 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Main.storyboard; sourceTree = ""; }; - F8111E0519A951050040E7D1 /* iOS Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "iOS Example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - F8111E0219A951050040E7D1 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 31E476821C55DE6D00968569 /* Alamofire.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 31E476601C55DD5900968569 /* Products */ = { - isa = PBXGroup; - children = ( - 31E4766A1C55DD5900968569 /* Alamofire.framework */, - 31E4766C1C55DD5900968569 /* Alamofire iOS Tests.xctest */, - 31E4766E1C55DD5900968569 /* Alamofire.framework */, - 31E476701C55DD5900968569 /* Alamofire macOS Tests.xctest */, - 31E476721C55DD5900968569 /* Alamofire.framework */, - 31E476741C55DD5900968569 /* Alamofire tvOS Tests.xctest */, - 31E476761C55DD5900968569 /* Alamofire.framework */, - ); - name = Products; - sourceTree = ""; - }; - 4C6D2C951C67F03B00846168 /* Base.lproj */ = { - isa = PBXGroup; - children = ( - 3129D57422F230AE009C145F /* LaunchScreen.storyboard */, - 4C6D2C961C67F03B00846168 /* Main.storyboard */, - ); - name = Base.lproj; - path = Resources/Base.lproj; - sourceTree = SOURCE_ROOT; - }; - F8111DFC19A951050040E7D1 = { - isa = PBXGroup; - children = ( - F8111E0719A951050040E7D1 /* Source */, - F8111E0619A951050040E7D1 /* Products */, - 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */, - ); - indentWidth = 4; - sourceTree = ""; - tabWidth = 4; - usesTabs = 0; - }; - F8111E0619A951050040E7D1 /* Products */ = { - isa = PBXGroup; - children = ( - F8111E0519A951050040E7D1 /* iOS Example.app */, - ); - name = Products; - sourceTree = ""; - }; - F8111E0719A951050040E7D1 /* Source */ = { - isa = PBXGroup; - children = ( - 4C6D2C7D1C67EFE100846168 /* AppDelegate.swift */, - 4C6D2C7E1C67EFE100846168 /* DetailViewController.swift */, - 4C6D2C7F1C67EFE100846168 /* MasterViewController.swift */, - F8111E0819A951050040E7D1 /* Supporting Files */, - ); - path = Source; - sourceTree = ""; - }; - F8111E0819A951050040E7D1 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 4C6D2C8D1C67EFEC00846168 /* Info.plist */, - 4C6D2C8C1C67EFEC00846168 /* Images.xcassets */, - 4C6D2C951C67F03B00846168 /* Base.lproj */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - F8111E0419A951050040E7D1 /* iOS Example */ = { - isa = PBXNativeTarget; - buildConfigurationList = F8111E2319A951050040E7D1 /* Build configuration list for PBXNativeTarget "iOS Example" */; - buildPhases = ( - F8111E0119A951050040E7D1 /* Sources */, - F8111E0219A951050040E7D1 /* Frameworks */, - F8111E0319A951050040E7D1 /* Resources */, - F818D0E519CA8D15006034B1 /* Copy Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 31E476851C55DE6D00968569 /* PBXTargetDependency */, - ); - name = "iOS Example"; - productName = Alamofire; - productReference = F8111E0519A951050040E7D1 /* iOS Example.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - F8111DFD19A951050040E7D1 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0720; - LastUpgradeCheck = 1020; - ORGANIZATIONNAME = Alamofire; - TargetAttributes = { - F8111E0419A951050040E7D1 = { - CreatedOnToolsVersion = 6.0; - LastSwiftMigration = 0900; - }; - }; - }; - buildConfigurationList = F8111E0019A951050040E7D1 /* Build configuration list for PBXProject "iOS Example" */; - compatibilityVersion = "Xcode 10.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = F8111DFC19A951050040E7D1; - productRefGroup = F8111E0619A951050040E7D1 /* Products */; - projectDirPath = ""; - projectReferences = ( - { - ProductGroup = 31E476601C55DD5900968569 /* Products */; - ProjectRef = 31E4765F1C55DD5900968569 /* Alamofire.xcodeproj */; - }, - ); - projectRoot = ""; - targets = ( - F8111E0419A951050040E7D1 /* iOS Example */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXReferenceProxy section */ - 31E4766A1C55DD5900968569 /* Alamofire.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = Alamofire.framework; - remoteRef = 31E476691C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E4766C1C55DD5900968569 /* Alamofire iOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "Alamofire iOS Tests.xctest"; - remoteRef = 31E4766B1C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E4766E1C55DD5900968569 /* Alamofire.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = Alamofire.framework; - remoteRef = 31E4766D1C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E476701C55DD5900968569 /* Alamofire macOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "Alamofire macOS Tests.xctest"; - remoteRef = 31E4766F1C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E476721C55DD5900968569 /* Alamofire.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = Alamofire.framework; - remoteRef = 31E476711C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E476741C55DD5900968569 /* Alamofire tvOS Tests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "Alamofire tvOS Tests.xctest"; - remoteRef = 31E476731C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 31E476761C55DD5900968569 /* Alamofire.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = Alamofire.framework; - remoteRef = 31E476751C55DD5900968569 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; -/* End PBXReferenceProxy section */ - -/* Begin PBXResourcesBuildPhase section */ - F8111E0319A951050040E7D1 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3129D57622F230AE009C145F /* LaunchScreen.storyboard in Resources */, - 4C6D2C8F1C67EFEC00846168 /* Images.xcassets in Resources */, - 4C6D2C981C67F03B00846168 /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - F8111E0119A951050040E7D1 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4C6D2C801C67EFE100846168 /* AppDelegate.swift in Sources */, - 4C6D2C821C67EFE100846168 /* MasterViewController.swift in Sources */, - 4C6D2C811C67EFE100846168 /* DetailViewController.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 31E476851C55DE6D00968569 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Alamofire iOS"; - targetProxy = 31E476841C55DE6D00968569 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 3129D57422F230AE009C145F /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 3129D57522F230AE009C145F /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; - 4C6D2C961C67F03B00846168 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 4C6D2C971C67F03B00846168 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - F8111E2119A951050040E7D1 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - MACOSX_DEPLOYMENT_TARGET = 10.12; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_SWIFT3_OBJC_INFERENCE = Off; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TVOS_DEPLOYMENT_TARGET = 10.0; - WATCHOS_DEPLOYMENT_TARGET = 3.0; - }; - name = Debug; - }; - F8111E2219A951050040E7D1 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = YES; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - MACOSX_DEPLOYMENT_TARGET = 10.12; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_SWIFT3_OBJC_INFERENCE = Off; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TVOS_DEPLOYMENT_TARGET = 10.0; - VALIDATE_PRODUCT = YES; - WATCHOS_DEPLOYMENT_TARGET = 3.0; - }; - name = Release; - }; - F8111E2419A951050040E7D1 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - INFOPLIST_FILE = Resources/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.iOS-Example"; - PRODUCT_NAME = "iOS Example"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - F8111E2519A951050040E7D1 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - INFOPLIST_FILE = Resources/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = "org.alamofire.iOS-Example"; - PRODUCT_NAME = "iOS Example"; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - F8111E0019A951050040E7D1 /* Build configuration list for PBXProject "iOS Example" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F8111E2119A951050040E7D1 /* Debug */, - F8111E2219A951050040E7D1 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F8111E2319A951050040E7D1 /* Build configuration list for PBXNativeTarget "iOS Example" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F8111E2419A951050040E7D1 /* Debug */, - F8111E2519A951050040E7D1 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = F8111DFD19A951050040E7D1 /* Project object */; -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index bfe77a2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/xcshareddata/xcschemes/iOS Example.xcscheme b/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/xcshareddata/xcschemes/iOS Example.xcscheme deleted file mode 100644 index 4b2bd1c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Example/iOS Example.xcodeproj/xcshareddata/xcschemes/iOS Example.xcscheme +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Gemfile b/Lesson12/Carthage/Checkouts/Alamofire/Gemfile deleted file mode 100644 index db0490c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -source "https://rubygems.org" - -gem "cocoapods" -gem "xcpretty" -gem "jazzy" diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Gemfile.lock b/Lesson12/Carthage/Checkouts/Alamofire/Gemfile.lock deleted file mode 100644 index 270fca8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Gemfile.lock +++ /dev/null @@ -1,107 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - CFPropertyList (3.0.1) - activesupport (4.2.11.1) - i18n (~> 0.7) - minitest (~> 5.1) - thread_safe (~> 0.3, >= 0.3.4) - tzinfo (~> 1.1) - algoliasearch (1.27.1) - httpclient (~> 2.8, >= 2.8.3) - json (>= 1.5.1) - atomos (0.1.3) - claide (1.0.3) - cocoapods (1.8.4) - activesupport (>= 4.0.2, < 5) - claide (>= 1.0.2, < 2.0) - cocoapods-core (= 1.8.4) - cocoapods-deintegrate (>= 1.0.3, < 2.0) - cocoapods-downloader (>= 1.2.2, < 2.0) - cocoapods-plugins (>= 1.0.0, < 2.0) - cocoapods-search (>= 1.0.0, < 2.0) - cocoapods-stats (>= 1.0.0, < 2.0) - cocoapods-trunk (>= 1.4.0, < 2.0) - cocoapods-try (>= 1.1.0, < 2.0) - colored2 (~> 3.1) - escape (~> 0.0.4) - fourflusher (>= 2.3.0, < 3.0) - gh_inspector (~> 1.0) - molinillo (~> 0.6.6) - nap (~> 1.0) - ruby-macho (~> 1.4) - xcodeproj (>= 1.11.1, < 2.0) - cocoapods-core (1.8.4) - activesupport (>= 4.0.2, < 6) - algoliasearch (~> 1.0) - concurrent-ruby (~> 1.1) - fuzzy_match (~> 2.0.4) - nap (~> 1.0) - cocoapods-deintegrate (1.0.4) - cocoapods-downloader (1.2.2) - cocoapods-plugins (1.0.0) - nap - cocoapods-search (1.0.0) - cocoapods-stats (1.1.0) - cocoapods-trunk (1.4.1) - nap (>= 0.8, < 2.0) - netrc (~> 0.11) - cocoapods-try (1.1.0) - colored2 (3.1.2) - concurrent-ruby (1.1.5) - escape (0.0.4) - ffi (1.11.1) - fourflusher (2.3.1) - fuzzy_match (2.0.4) - gh_inspector (1.1.3) - httpclient (2.8.3) - i18n (0.9.5) - concurrent-ruby (~> 1.0) - jazzy (0.11.2) - cocoapods (~> 1.5) - mustache (~> 1.1) - open4 - redcarpet (~> 3.4) - rouge (>= 2.0.6, < 4.0) - sassc (~> 2.1) - sqlite3 (~> 1.3) - xcinvoke (~> 0.3.0) - json (2.2.0) - liferaft (0.0.6) - minitest (5.12.2) - molinillo (0.6.6) - mustache (1.1.0) - nanaimo (0.2.6) - nap (1.1.0) - netrc (0.11.0) - open4 (1.3.4) - redcarpet (3.5.0) - rouge (2.0.7) - ruby-macho (1.4.0) - sassc (2.2.1) - ffi (~> 1.9) - sqlite3 (1.4.1) - thread_safe (0.3.6) - tzinfo (1.2.5) - thread_safe (~> 0.1) - xcinvoke (0.3.0) - liferaft (~> 0.0.6) - xcodeproj (1.13.0) - CFPropertyList (>= 2.3.3, < 4.0) - atomos (~> 0.1.3) - claide (>= 1.0.2, < 2.0) - colored2 (~> 3.1) - nanaimo (~> 0.2.6) - xcpretty (0.3.0) - rouge (~> 2.0.7) - -PLATFORMS - ruby - -DEPENDENCIES - cocoapods - jazzy - xcpretty - -BUNDLED WITH - 1.17.3 diff --git a/Lesson12/Carthage/Checkouts/Alamofire/LICENSE b/Lesson12/Carthage/Checkouts/Alamofire/LICENSE deleted file mode 100644 index 2ec3cb1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Package.swift b/Lesson12/Carthage/Checkouts/Alamofire/Package.swift deleted file mode 100644 index b744de5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Package.swift +++ /dev/null @@ -1,37 +0,0 @@ -// swift-tools-version:5.0 -// -// Package.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import PackageDescription - -let package = Package(name: "Alamofire", - platforms: [.macOS(.v10_12), - .iOS(.v10), - .tvOS(.v10), - .watchOS(.v3)], - products: [.library(name: "Alamofire", - targets: ["Alamofire"])], - targets: [.target(name: "Alamofire", - path: "Source")], - swiftLanguageVersions: [.v5]) diff --git a/Lesson12/Carthage/Checkouts/Alamofire/README.md b/Lesson12/Carthage/Checkouts/Alamofire/README.md deleted file mode 100644 index bcd4c3b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/README.md +++ /dev/null @@ -1,202 +0,0 @@ -![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) - -[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) -[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) -[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) -[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) -[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) -[![Open Source Helpers](https://www.codetriage.com/alamofire/alamofire/badges/users.svg)](https://www.codetriage.com/alamofire/alamofire) - -Alamofire is an HTTP networking library written in Swift. - -**⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️** This documentation is out of date during the Alamofire 5 beta process. - -- [Features](#features) -- [Component Libraries](#component-libraries) -- [Requirements](#requirements) -- [Migration Guides](#migration-guides) -- [Communication](#communication) -- [Installation](#installation) -- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) - - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) - - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) - - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) - - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) -- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) - - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) - - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) - - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) - - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) -- [Open Radars](#open-radars) -- [FAQ](#faq) -- [Credits](#credits) -- [Donations](#donations) -- [License](#license) - -## Features - -- [x] Chainable Request / Response Methods -- [x] URL / JSON / plist Parameter Encoding -- [x] Upload File / Data / Stream / MultipartFormData -- [x] Download File using Request or Resume Data -- [x] Authentication with URLCredential -- [x] HTTP Response Validation -- [x] Upload and Download Progress Closures with Progress -- [x] cURL Command Output -- [x] Dynamically Adapt and Retry Requests -- [x] TLS Certificate and Public Key Pinning -- [x] Network Reachability -- [x] Comprehensive Unit and Integration Test Coverage -- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) - -## Component Libraries - -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - -- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. -- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. - -## Requirements - -- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ -- Xcode 10.2+ -- Swift 5+ - -## Migration Guides - -- Alamofire 5.0 Migration Guide: To be written! -- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) -- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) -- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) - -## Communication -- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. -- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. -- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! -- If you **want to contribute**, submit a pull request. - -## Installation - -### CocoaPods - -[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -pod 'Alamofire', '~> 5.0.0-rc.3' -``` - -### Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "Alamofire/Alamofire" "5.0.0-rc.3" -``` - -### Swift Package Manager - -The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. - -Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. - -```swift -dependencies: [ - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0-rc.3") -] -``` - -### Manually - -If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. - -#### Embedded Framework - -- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: - - ```bash - $ git init - ``` - -- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: - - ```bash - $ git submodule add https://github.com/Alamofire/Alamofire.git - ``` - -- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. - - > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - -- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. -- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. -- In the tab bar at the top of that window, open the "General" panel. -- Click on the `+` button under the "Embedded Binaries" section. -- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. - - > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - -- Select the top `Alamofire.framework` for iOS and the bottom one for macOS. - - > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. - -- And that's it! - - > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. - -## Open Radars - -The following radars have some effect on the current implementation of Alamofire. - -- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case -- `rdar://26870455` - Background URL Session Configurations do not work in the simulator -- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` - -## Resolved Radars - -The following radars have been resolved over time after being filed against the Alamofire project. - -- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. - - (Resolved): 9/1/17 in Xcode 9 beta 6. -- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ - - (Resolved): Just add `CFNetwork` to your linked frameworks. - -## FAQ - -### What's the origin of the name Alamofire? - -Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. - -## Credits - -Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. - -### Security Disclosure - -If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. - -## Donations - -The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. -Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. -Donating to the ASF will enable us to: - -- Pay our yearly legal fees to keep the non-profit in good status -- Pay for our mail servers to help us stay on top of all questions and security issues -- Potentially fund test servers to make it easier for us to test the edge cases -- Potentially fund developers to work on one of our projects full-time - -The community adoption of the ASF libraries has been amazing. -We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. -With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. -If you use any of our libraries for work, see if your employers would be interested in donating. -Any amount you can donate today to help us reach our goal would be greatly appreciated. - -[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) - -## License - -Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/AFError.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/AFError.swift deleted file mode 100644 index 8ab282c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/AFError.swift +++ /dev/null @@ -1,840 +0,0 @@ -// -// AFError.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with -/// their own associated reasons. -public enum AFError: Error { - /// The underlying reason the `.multipartEncodingFailed` error occurred. - public enum MultipartEncodingFailureReason { - /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. - case bodyPartURLInvalid(url: URL) - /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. - case bodyPartFilenameInvalid(in: URL) - /// The file at the `fileURL` provided was not reachable. - case bodyPartFileNotReachable(at: URL) - /// Attempting to check the reachability of the `fileURL` provided threw an error. - case bodyPartFileNotReachableWithError(atURL: URL, error: Error) - /// The file at the `fileURL` provided is actually a directory. - case bodyPartFileIsDirectory(at: URL) - /// The size of the file at the `fileURL` provided was not returned by the system. - case bodyPartFileSizeNotAvailable(at: URL) - /// The attempt to find the size of the file at the `fileURL` provided threw an error. - case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) - /// An `InputStream` could not be created for the provided `fileURL`. - case bodyPartInputStreamCreationFailed(for: URL) - /// An `OutputStream` could not be created when attempting to write the encoded data to disk. - case outputStreamCreationFailed(for: URL) - /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. - case outputStreamFileAlreadyExists(at: URL) - /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. - case outputStreamURLInvalid(url: URL) - /// The attempt to write the encoded body data to disk failed with an underlying error. - case outputStreamWriteFailed(error: Error) - /// The attempt to read an encoded body part `InputStream` failed with underlying system error. - case inputStreamReadFailed(error: Error) - } - - /// The underlying reason the `.parameterEncodingFailed` error occurred. - public enum ParameterEncodingFailureReason { - /// The `URLRequest` did not have a `URL` to encode. - case missingURL - /// JSON serialization failed with an underlying system error during the encoding process. - case jsonEncodingFailed(error: Error) - /// Custom parameter encoding failed due to the associated `Error`. - case customEncodingFailed(error: Error) - } - - /// The underlying reason the `.parameterEncoderFailed` error occurred. - public enum ParameterEncoderFailureReason { - /// Possible missing components. - public enum RequiredComponent { - /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. - case url - /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. - case httpMethod(rawValue: String) - } - - /// A `RequiredComponent` was missing during encoding. - case missingRequiredComponent(RequiredComponent) - /// The underlying encoder failed with the associated error. - case encoderFailed(error: Error) - } - - /// The underlying reason the `.responseValidationFailed` error occurred. - public enum ResponseValidationFailureReason { - /// The data file containing the server response did not exist. - case dataFileNil - /// The data file containing the server response at the associated `URL` could not be read. - case dataFileReadFailed(at: URL) - /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a - /// wildcard type. - case missingContentType(acceptableContentTypes: [String]) - /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. - case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) - /// The response status code was not acceptable. - case unacceptableStatusCode(code: Int) - /// Custom response validation failed due to the associated `Error`. - case customValidationFailed(error: Error) - } - - /// The underlying reason the response serialization error occurred. - public enum ResponseSerializationFailureReason { - /// The server response contained no data or the data was zero length. - case inputDataNilOrZeroLength - /// The file containing the server response did not exist. - case inputFileNil - /// The file containing the server response could not be read from the associated `URL`. - case inputFileReadFailed(at: URL) - /// String serialization failed using the provided `String.Encoding`. - case stringSerializationFailed(encoding: String.Encoding) - /// JSON serialization failed with an underlying system error. - case jsonSerializationFailed(error: Error) - /// A `DataDecoder` failed to decode the response due to the associated `Error`. - case decodingFailed(error: Error) - /// A custom response serializer failed due to the associated `Error`. - case customSerializationFailed(error: Error) - /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. - case invalidEmptyResponse(type: String) - } - - /// Underlying reason a server trust evaluation error occurred. - public enum ServerTrustFailureReason { - /// The output of a server trust evaluation. - public struct Output { - /// The host for which the evaluation was performed. - public let host: String - /// The `SecTrust` value which was evaluated. - public let trust: SecTrust - /// The `OSStatus` of evaluation operation. - public let status: OSStatus - /// The result of the evaluation operation. - public let result: SecTrustResultType - - /// Creates an `Output` value from the provided values. - init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { - self.host = host - self.trust = trust - self.status = status - self.result = result - } - } - - /// No `ServerTrustEvaluator` was found for the associated host. - case noRequiredEvaluator(host: String) - /// No certificates were found with which to perform the trust evaluation. - case noCertificatesFound - /// No public keys were found with which to perform the trust evaluation. - case noPublicKeysFound - /// During evaluation, application of the associated `SecPolicy` failed. - case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) - /// During evaluation, setting the associated anchor certificates failed. - case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) - /// During evaluation, creation of the revocation policy failed. - case revocationPolicyCreationFailed - /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. - case trustEvaluationFailed(error: Error?) - /// Default evaluation failed with the associated `Output`. - case defaultEvaluationFailed(output: Output) - /// Host validation failed with the associated `Output`. - case hostValidationFailed(output: Output) - /// Revocation check failed with the associated `Output` and options. - case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) - /// Certificate pinning failed. - case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) - /// Public key pinning failed. - case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) - /// Custom server trust evaluation failed due to the associated `Error`. - case customEvaluationFailed(error: Error) - } - - /// The underlying reason the `.urlRequestValidationFailed` - public enum URLRequestValidationFailureReason { - /// URLRequest with GET method had body data. - case bodyDataInGETRequest(Data) - } - - /// `UploadableConvertible` threw an error in `createUploadable()`. - case createUploadableFailed(error: Error) - /// `URLRequestConvertible` threw an error in `asURLRequest()`. - case createURLRequestFailed(error: Error) - /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. - case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) - /// `Request` was explicitly cancelled. - case explicitlyCancelled - /// `URLConvertible` type failed to create a valid `URL`. - case invalidURL(url: URLConvertible) - /// Multipart form encoding failed. - case multipartEncodingFailed(reason: MultipartEncodingFailureReason) - /// `ParameterEncoding` threw an error during the encoding process. - case parameterEncodingFailed(reason: ParameterEncodingFailureReason) - /// `ParameterEncoder` threw an error while running the encoder. - case parameterEncoderFailed(reason: ParameterEncoderFailureReason) - /// `RequestAdapter` threw an error during adaptation. - case requestAdaptationFailed(error: Error) - /// `RequestRetrier` threw an error during the request retry process. - case requestRetryFailed(retryError: Error, originalError: Error) - /// Response validation failed. - case responseValidationFailed(reason: ResponseValidationFailureReason) - /// Response serialization failed. - case responseSerializationFailed(reason: ResponseSerializationFailureReason) - /// `ServerTrustEvaluating` instance threw an error during trust evaluation. - case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) - /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. - case sessionDeinitialized - /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. - case sessionInvalidated(error: Error?) - /// `URLSessionTask` completed with error. - case sessionTaskFailed(error: Error) - /// `URLRequest` failed validation. - case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) -} - -extension Error { - /// Returns the instance cast as an `AFError`. - public var asAFError: AFError? { - return self as? AFError - } - - /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. - public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { - guard let afError = self as? AFError else { - fatalError(message(), file: file, line: line) - } - return afError - } - - /// Casts the instance as `AFError` or returns `defaultAFError` - func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { - return self as? AFError ?? defaultAFError() - } -} - -// MARK: - Error Booleans - -extension AFError { - /// Returns whether the instance is `.sessionDeinitialized`. - public var isSessionDeinitializedError: Bool { - if case .sessionDeinitialized = self { return true } - return false - } - - /// Returns whether the instance is `.sessionInvalidated`. - public var isSessionInvalidatedError: Bool { - if case .sessionInvalidated = self { return true } - return false - } - - /// Returns whether the instance is `.explicitlyCancelled`. - public var isExplicitlyCancelledError: Bool { - if case .explicitlyCancelled = self { return true } - return false - } - - /// Returns whether the instance is `.invalidURL`. - public var isInvalidURLError: Bool { - if case .invalidURL = self { return true } - return false - } - - /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isParameterEncodingError: Bool { - if case .parameterEncodingFailed = self { return true } - return false - } - - /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isParameterEncoderError: Bool { - if case .parameterEncoderFailed = self { return true } - return false - } - - /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` - /// properties will contain the associated values. - public var isMultipartEncodingError: Bool { - if case .multipartEncodingFailed = self { return true } - return false - } - - /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isRequestAdaptationError: Bool { - if case .requestAdaptationFailed = self { return true } - return false - } - - /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, - /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. - public var isResponseValidationError: Bool { - if case .responseValidationFailed = self { return true } - return false - } - - /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and - /// `underlyingError` properties will contain the associated values. - public var isResponseSerializationError: Bool { - if case .responseSerializationFailed = self { return true } - return false - } - - /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isServerTrustEvaluationError: Bool { - if case .serverTrustEvaluationFailed = self { return true } - return false - } - - /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isRequestRetryError: Bool { - if case .requestRetryFailed = self { return true } - return false - } - - /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isCreateUploadableError: Bool { - if case .createUploadableFailed = self { return true } - return false - } - - /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isCreateURLRequestError: Bool { - if case .createURLRequestFailed = self { return true } - return false - } - - /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will - /// contain the associated values. - public var isDownloadedFileMoveError: Bool { - if case .downloadedFileMoveFailed = self { return true } - return false - } - - /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isSessionTaskError: Bool { - if case .sessionTaskFailed = self { return true } - return false - } -} - -// MARK: - Convenience Properties - -extension AFError { - /// The `URLConvertible` associated with the error. - public var urlConvertible: URLConvertible? { - guard case let .invalidURL(url) = self else { return nil } - return url - } - - /// The `URL` associated with the error. - public var url: URL? { - guard case let .multipartEncodingFailed(reason) = self else { return nil } - return reason.url - } - - /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, - /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, - /// `.responseSerializationFailed`, `.requestRetryFailed` errors. - public var underlyingError: Error? { - switch self { - case let .multipartEncodingFailed(reason): - return reason.underlyingError - case let .parameterEncodingFailed(reason): - return reason.underlyingError - case let .parameterEncoderFailed(reason): - return reason.underlyingError - case let .requestAdaptationFailed(error): - return error - case let .requestRetryFailed(retryError, _): - return retryError - case let .responseValidationFailed(reason): - return reason.underlyingError - case let .responseSerializationFailed(reason): - return reason.underlyingError - case let .serverTrustEvaluationFailed(reason): - return reason.underlyingError - case let .sessionInvalidated(error): - return error - case let .createUploadableFailed(error): - return error - case let .createURLRequestFailed(error): - return error - case let .downloadedFileMoveFailed(error, _, _): - return error - case let .sessionTaskFailed(error): - return error - case .explicitlyCancelled, - .invalidURL, - .sessionDeinitialized, - .urlRequestValidationFailed: - return nil - } - } - - /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. - public var acceptableContentTypes: [String]? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.acceptableContentTypes - } - - /// The response `Content-Type` of a `.responseValidationFailed` error. - public var responseContentType: String? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.responseContentType - } - - /// The response code of a `.responseValidationFailed` error. - public var responseCode: Int? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.responseCode - } - - /// The `String.Encoding` associated with a failed `.stringResponse()` call. - public var failedStringEncoding: String.Encoding? { - guard case let .responseSerializationFailed(reason) = self else { return nil } - return reason.failedStringEncoding - } - - /// The `source` URL of a `.downloadedFileMoveFailed` error. - public var sourceURL: URL? { - guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } - return source - } - - /// The `destination` URL of a `.downloadedFileMoveFailed` error. - public var destinationURL: URL? { - guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } - return destination - } -} - -extension AFError.ParameterEncodingFailureReason { - var underlyingError: Error? { - switch self { - case let .jsonEncodingFailed(error), - let .customEncodingFailed(error): - return error - case .missingURL: - return nil - } - } -} - -extension AFError.ParameterEncoderFailureReason { - var underlyingError: Error? { - switch self { - case let .encoderFailed(error): - return error - case .missingRequiredComponent: - return nil - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var url: URL? { - switch self { - case let .bodyPartURLInvalid(url), - let .bodyPartFilenameInvalid(url), - let .bodyPartFileNotReachable(url), - let .bodyPartFileIsDirectory(url), - let .bodyPartFileSizeNotAvailable(url), - let .bodyPartInputStreamCreationFailed(url), - let .outputStreamCreationFailed(url), - let .outputStreamFileAlreadyExists(url), - let .outputStreamURLInvalid(url), - let .bodyPartFileNotReachableWithError(url, _), - let .bodyPartFileSizeQueryFailedWithError(url, _): - return url - case .outputStreamWriteFailed, - .inputStreamReadFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .bodyPartFileNotReachableWithError(_, error), - let .bodyPartFileSizeQueryFailedWithError(_, error), - let .outputStreamWriteFailed(error), - let .inputStreamReadFailed(error): - return error - case .bodyPartURLInvalid, - .bodyPartFilenameInvalid, - .bodyPartFileNotReachable, - .bodyPartFileIsDirectory, - .bodyPartFileSizeNotAvailable, - .bodyPartInputStreamCreationFailed, - .outputStreamCreationFailed, - .outputStreamFileAlreadyExists, - .outputStreamURLInvalid: - return nil - } - } -} - -extension AFError.ResponseValidationFailureReason { - var acceptableContentTypes: [String]? { - switch self { - case let .missingContentType(types), - let .unacceptableContentType(types, _): - return types - case .dataFileNil, - .dataFileReadFailed, - .unacceptableStatusCode, - .customValidationFailed: - return nil - } - } - - var responseContentType: String? { - switch self { - case let .unacceptableContentType(_, responseType): - return responseType - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableStatusCode, - .customValidationFailed: - return nil - } - } - - var responseCode: Int? { - switch self { - case let .unacceptableStatusCode(code): - return code - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableContentType, - .customValidationFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .customValidationFailed(error): - return error - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableContentType, - .unacceptableStatusCode: - return nil - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var failedStringEncoding: String.Encoding? { - switch self { - case let .stringSerializationFailed(encoding): - return encoding - case .inputDataNilOrZeroLength, - .inputFileNil, - .inputFileReadFailed(_), - .jsonSerializationFailed(_), - .decodingFailed(_), - .customSerializationFailed(_), - .invalidEmptyResponse: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .jsonSerializationFailed(error), - let .decodingFailed(error), - let .customSerializationFailed(error): - return error - case .inputDataNilOrZeroLength, - .inputFileNil, - .inputFileReadFailed, - .stringSerializationFailed, - .invalidEmptyResponse: - return nil - } - } -} - -extension AFError.ServerTrustFailureReason { - var output: AFError.ServerTrustFailureReason.Output? { - switch self { - case let .defaultEvaluationFailed(output), - let .hostValidationFailed(output), - let .revocationCheckFailed(output, _): - return output - case .noRequiredEvaluator, - .noCertificatesFound, - .noPublicKeysFound, - .policyApplicationFailed, - .settingAnchorCertificatesFailed, - .revocationPolicyCreationFailed, - .trustEvaluationFailed, - .certificatePinningFailed, - .publicKeyPinningFailed, - .customEvaluationFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .customEvaluationFailed(error): - return error - case let .trustEvaluationFailed(error): - return error - case .noRequiredEvaluator, - .noCertificatesFound, - .noPublicKeysFound, - .policyApplicationFailed, - .settingAnchorCertificatesFailed, - .revocationPolicyCreationFailed, - .defaultEvaluationFailed, - .hostValidationFailed, - .revocationCheckFailed, - .certificatePinningFailed, - .publicKeyPinningFailed: - return nil - } - } -} - -// MARK: - Error Descriptions - -extension AFError: LocalizedError { - public var errorDescription: String? { - switch self { - case .explicitlyCancelled: - return "Request explicitly cancelled." - case let .invalidURL(url): - return "URL is not valid: \(url)" - case let .parameterEncodingFailed(reason): - return reason.localizedDescription - case let .parameterEncoderFailed(reason): - return reason.localizedDescription - case let .multipartEncodingFailed(reason): - return reason.localizedDescription - case let .requestAdaptationFailed(error): - return "Request adaption failed with error: \(error.localizedDescription)" - case let .responseValidationFailed(reason): - return reason.localizedDescription - case let .responseSerializationFailed(reason): - return reason.localizedDescription - case let .requestRetryFailed(retryError, originalError): - return """ - Request retry failed with retry error: \(retryError.localizedDescription), \ - original error: \(originalError.localizedDescription) - """ - case .sessionDeinitialized: - return """ - Session was invalidated without error, so it was likely deinitialized unexpectedly. \ - Be sure to retain a reference to your Session for the duration of your requests. - """ - case let .sessionInvalidated(error): - return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" - case let .serverTrustEvaluationFailed(reason): - return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" - case let .urlRequestValidationFailed(reason): - return "URLRequest validation failed due to reason: \(reason.localizedDescription)" - case let .createUploadableFailed(error): - return "Uploadable creation failed with error: \(error.localizedDescription)" - case let .createURLRequestFailed(error): - return "URLRequest creation failed with error: \(error.localizedDescription)" - case let .downloadedFileMoveFailed(error, source, destination): - return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" - case let .sessionTaskFailed(error): - return "URLSessionTask failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.ParameterEncodingFailureReason { - var localizedDescription: String { - switch self { - case .missingURL: - return "URL request to encode was missing a URL" - case let .jsonEncodingFailed(error): - return "JSON could not be encoded because of error:\n\(error.localizedDescription)" - case let .customEncodingFailed(error): - return "Custom parameter encoder failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.ParameterEncoderFailureReason { - var localizedDescription: String { - switch self { - case let .missingRequiredComponent(component): - return "Encoding failed due to a missing request component: \(component)" - case let .encoderFailed(error): - return "The underlying encoder failed with the error: \(error)" - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var localizedDescription: String { - switch self { - case let .bodyPartURLInvalid(url): - return "The URL provided is not a file URL: \(url)" - case let .bodyPartFilenameInvalid(url): - return "The URL provided does not have a valid filename: \(url)" - case let .bodyPartFileNotReachable(url): - return "The URL provided is not reachable: \(url)" - case let .bodyPartFileNotReachableWithError(url, error): - return """ - The system returned an error while checking the provided URL for reachability. - URL: \(url) - Error: \(error) - """ - case let .bodyPartFileIsDirectory(url): - return "The URL provided is a directory: \(url)" - case let .bodyPartFileSizeNotAvailable(url): - return "Could not fetch the file size from the provided URL: \(url)" - case let .bodyPartFileSizeQueryFailedWithError(url, error): - return """ - The system returned an error while attempting to fetch the file size from the provided URL. - URL: \(url) - Error: \(error) - """ - case let .bodyPartInputStreamCreationFailed(url): - return "Failed to create an InputStream for the provided URL: \(url)" - case let .outputStreamCreationFailed(url): - return "Failed to create an OutputStream for URL: \(url)" - case let .outputStreamFileAlreadyExists(url): - return "A file already exists at the provided URL: \(url)" - case let .outputStreamURLInvalid(url): - return "The provided OutputStream URL is invalid: \(url)" - case let .outputStreamWriteFailed(error): - return "OutputStream write failed with error: \(error)" - case let .inputStreamReadFailed(error): - return "InputStream read failed with error: \(error)" - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var localizedDescription: String { - switch self { - case .inputDataNilOrZeroLength: - return "Response could not be serialized, input data was nil or zero length." - case .inputFileNil: - return "Response could not be serialized, input file was nil." - case let .inputFileReadFailed(url): - return "Response could not be serialized, input file could not be read: \(url)." - case let .stringSerializationFailed(encoding): - return "String could not be serialized with encoding: \(encoding)." - case let .jsonSerializationFailed(error): - return "JSON could not be serialized because of error:\n\(error.localizedDescription)" - case let .invalidEmptyResponse(type): - return """ - Empty response could not be serialized to type: \(type). \ - Use Empty as the expected type for such responses. - """ - case let .decodingFailed(error): - return "Response could not be decoded because of error:\n\(error.localizedDescription)" - case let .customSerializationFailed(error): - return "Custom response serializer failed with error:\n\(error.localizedDescription)" - } - } -} - -extension AFError.ResponseValidationFailureReason { - var localizedDescription: String { - switch self { - case .dataFileNil: - return "Response could not be validated, data file was nil." - case let .dataFileReadFailed(url): - return "Response could not be validated, data file could not be read: \(url)." - case let .missingContentType(types): - return """ - Response Content-Type was missing and acceptable content types \ - (\(types.joined(separator: ","))) do not match "*/*". - """ - case let .unacceptableContentType(acceptableTypes, responseType): - return """ - Response Content-Type "\(responseType)" does not match any acceptable types: \ - \(acceptableTypes.joined(separator: ",")). - """ - case let .unacceptableStatusCode(code): - return "Response status code was unacceptable: \(code)." - case let .customValidationFailed(error): - return "Custom response validation failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.ServerTrustFailureReason { - var localizedDescription: String { - switch self { - case let .noRequiredEvaluator(host): - return "A ServerTrustEvaluating value is required for host \(host) but none was found." - case .noCertificatesFound: - return "No certificates were found or provided for evaluation." - case .noPublicKeysFound: - return "No public keys were found or provided for evaluation." - case .policyApplicationFailed: - return "Attempting to set a SecPolicy failed." - case .settingAnchorCertificatesFailed: - return "Attempting to set the provided certificates as anchor certificates failed." - case .revocationPolicyCreationFailed: - return "Attempting to create a revocation policy failed." - case let .trustEvaluationFailed(error): - return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" - case let .defaultEvaluationFailed(output): - return "Default evaluation failed for host \(output.host)." - case let .hostValidationFailed(output): - return "Host validation failed for host \(output.host)." - case let .revocationCheckFailed(output, _): - return "Revocation check failed for host \(output.host)." - case let .certificatePinningFailed(host, _, _, _): - return "Certificate pinning failed for host \(host)." - case let .publicKeyPinningFailed(host, _, _, _): - return "Public key pinning failed for host \(host)." - case let .customEvaluationFailed(error): - return "Custom trust evaluation failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.URLRequestValidationFailureReason { - var localizedDescription: String { - switch self { - case let .bodyDataInGETRequest(data): - return """ - Invalid URLRequest: Requests with GET method cannot have body data: - \(String(decoding: data, as: UTF8.self)) - """ - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.h b/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.h deleted file mode 100644 index 5d7609a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.h +++ /dev/null @@ -1,28 +0,0 @@ -// -// Alamofire.h -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@import Foundation; - -FOUNDATION_EXPORT double AlamofireVersionNumber; -FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.swift deleted file mode 100644 index f6f0b80..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Alamofire.swift +++ /dev/null @@ -1,520 +0,0 @@ -// -// Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Global namespace containing API for the `default` `Session` instance. -public enum AF { - /// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. - static let version = "5.0.0-rc.3" - - // MARK: - Data Request - - /// Creates a `DataRequest` using `Session.default` to retrieve the contents of the specified `url` using the - /// `method`, `parameters`, `encoding`, and `headers` provided. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`, `.get` by default. - /// - parameters: The `Parameters`, `nil` by default. - /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - /// - Returns: The created `DataRequest`. - public static func request(_ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil) -> DataRequest { - return Session.default.request(url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - interceptor: interceptor) - } - - /// Creates a `DataRequest` using `Session.default` to retrieve the contents of the specified `url` using the - /// `method`, `parameters`, `encoding`, and `headers` provided. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`, `.get` by default. - /// - parameters: The `Encodable` parameters, `nil` by default. - /// - encoding: The `ParameterEncoder`, `URLEncodedFormParameterEncoder.default` by default. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - /// - Returns: The created `DataRequest`. - public static func request(_ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil) -> DataRequest { - return Session.default.request(url, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers, - interceptor: interceptor) - } - - /// Creates a `DataRequest` using `Session.default` to execute the specified `urlRequest`. - /// - /// - Parameters: - /// - urlRequest: The `URLRequestConvertible` value. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - /// - Returns: The created `DataRequest`. - public static func request(_ urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { - return Session.default.request(urlRequest, interceptor: interceptor) - } - - // MARK: - Download Request - - /// Creates a `DownloadRequest` using `Session.default` to download the contents of the specified `url` to - /// the provided `destination` using the `method`, `parameters`, `encoding`, and `headers` provided. - /// - /// If `destination` is not specified, the download will be moved to a temporary location determined by Alamofire. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`, `.get` by default. - /// - parameters: The `Parameters`, `nil` by default. - /// - encoding: The `ParameterEncoding`, `URLEncoding.default` by default. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the - /// downloaded file. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - public static func download(_ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - return Session.default.download(url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - interceptor: interceptor, - to: destination) - } - - /// Creates a `DownloadRequest` using `Session.default` to download the contents of the specified `url` to the - /// provided `destination` using the `method`, encodable `parameters`, `encoder`, and `headers` provided. - /// - /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by - /// Alamofire. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`, `.get` by default. - /// - parameters: The `Encodable` parameters, `nil` by default. - /// - encoder: The `ParameterEncoder`, `URLEncodedFormParameterEncoder.default` by default. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the - /// downloaded file. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - public static func download(_ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - return Session.default.download(url, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers, - interceptor: interceptor, - to: destination) - } - - // MARK: URLRequest - - /// Creates a `DownloadRequest` using `Session.default` to execute the specified `urlRequest` and download - /// the result to the provided `destination`. - /// - /// - Parameters: - /// - urlRequest: The `URLRequestConvertible` value. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - destination: The `DownloadRequest.Destination` closure used the determine the destination of the - /// downloaded file. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - public static func download(_ urlRequest: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - return Session.default.download(urlRequest, interceptor: interceptor, to: destination) - } - - // MARK: Resume Data - - /// Creates a `DownloadRequest` using the `Session.default` from the `resumeData` produced from a previous - /// `DownloadRequest` cancellation to retrieve the contents of the original request and save them to the `destination`. - /// - /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by - /// Alamofire. - /// - /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), - /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` - /// generation logic where the data is written incorrectly and will always fail to resume the download. For more - /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). - /// - /// - Parameters: - /// - resumeData: The resume `Data`. This is an opaque blob produced by `URLSessionDownloadTask` when a task is - /// cancelled. See [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel) - /// for more information. - /// - interceptor: The `RequestInterceptor`, `nil` by default. - /// - destination: The `DownloadRequest.Destination` closure used to determine the destination of the downloaded - /// file. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - public static func download(resumingWith resumeData: Data, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - return Session.default.download(resumingWith: resumeData, interceptor: interceptor, to: destination) - } - - // MARK: - Upload Request - - // MARK: Data - - /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ data: Data, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(data, - to: convertible, - method: method, - headers: headers, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ data: Data, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: File - - /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided - /// components and `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ fileURL: URL, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(fileURL, - to: convertible, - method: method, - headers: headers, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ fileURL: URL, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ stream: InputStream, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(stream, - to: convertible, - method: method, - headers: headers, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(_ stream: InputStream, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: MultipartFormData - - /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided - /// `URLRequest` components and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(multipartFormData: multipartFormData, - to: url, - usingThreshold: encodingMemoryThreshold, - method: method, - headers: headers, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` - /// value, and a `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(multipartFormData: multipartFormData, - with: request, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components - /// and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(multipartFormData: MultipartFormData, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(multipartFormData: multipartFormData, - to: url, - usingThreshold: encodingMemoryThreshold, - method: method, - headers: headers, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` - /// value and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - public static func upload(multipartFormData: MultipartFormData, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return Session.default.upload(multipartFormData: multipartFormData, - with: request, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/AlamofireExtended.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/AlamofireExtended.swift deleted file mode 100644 index 3009e8b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/AlamofireExtended.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// AlamofireExtended.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -/// Type that acts as a generic extension point for all `AlamofireExtended` types. -public struct AlamofireExtension { - /// Stores the type or metatype of any extended type. - let type: ExtendedType - - init(_ type: ExtendedType) { - self.type = type - } -} - -/// Protocol describing the `af` extension points for Alamofire extended types. -public protocol AlamofireExtended { - /// Type being extended. - associatedtype ExtendedType - - /// Static Alamofire extension point. - static var af: AlamofireExtension.Type { get set } - /// Instance Alamofire extension point. - var af: AlamofireExtension { get set } -} - -public extension AlamofireExtended { - /// Static Alamofire extension point. - static var af: AlamofireExtension.Type { - get { return AlamofireExtension.self } - set {} - } - - /// Instance Alamofire extension point. - var af: AlamofireExtension { - get { return AlamofireExtension(self) } - set {} - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/CachedResponseHandler.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/CachedResponseHandler.swift deleted file mode 100644 index b6e0d4b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/CachedResponseHandler.swift +++ /dev/null @@ -1,91 +0,0 @@ -// -// CachedResponseHandler.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that handles whether the data task should store the HTTP response in the cache. -public protocol CachedResponseHandler { - /// Determines whether the HTTP response should be stored in the cache. - /// - /// The `completion` closure should be passed one of three possible options: - /// - /// 1. The cached response provided by the server (this is the most common use case). - /// 2. A modified version of the cached response (you may want to modify it in some way before caching). - /// 3. A `nil` value to prevent the cached response from being stored in the cache. - /// - /// - Parameters: - /// - task: The data task whose request resulted in the cached response. - /// - response: The cached response to potentially store in the cache. - /// - completion: The closure to execute containing cached response, a modified response, or `nil`. - func dataTask(_ task: URLSessionDataTask, - willCacheResponse response: CachedURLResponse, - completion: @escaping (CachedURLResponse?) -> Void) -} - -// MARK: - - -/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached -/// response. -public struct ResponseCacher { - /// Defines the behavior of the `ResponseCacher` type. - public enum Behavior { - /// Stores the cached response in the cache. - case cache - /// Prevents the cached response from being stored in the cache. - case doNotCache - /// Modifies the cached response before storing it in the cache. - case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) - } - - /// Returns a `ResponseCacher` with a follow `Behavior`. - public static let cache = ResponseCacher(behavior: .cache) - /// Returns a `ResponseCacher` with a do not follow `Behavior`. - public static let doNotCache = ResponseCacher(behavior: .doNotCache) - - /// The `Behavior` of the `ResponseCacher`. - public let behavior: Behavior - - /// Creates a `ResponseCacher` instance from the `Behavior`. - /// - /// - Parameter behavior: The `Behavior`. - public init(behavior: Behavior) { - self.behavior = behavior - } -} - -extension ResponseCacher: CachedResponseHandler { - public func dataTask(_ task: URLSessionDataTask, - willCacheResponse response: CachedURLResponse, - completion: @escaping (CachedURLResponse?) -> Void) { - switch behavior { - case .cache: - completion(response) - case .doNotCache: - completion(nil) - case let .modify(closure): - let response = closure(task, response) - completion(response) - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift deleted file mode 100644 index 10cd273..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/DispatchQueue+Alamofire.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// DispatchQueue+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Dispatch -import Foundation - -extension DispatchQueue { - /// Execute the provided closure after a `TimeInterval`. - /// - /// - Parameters: - /// - delay: `TimeInterval` to delay execution. - /// - closure: Closure to execute. - func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { - asyncAfter(deadline: .now() + delay, execute: closure) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/EventMonitor.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/EventMonitor.swift deleted file mode 100644 index 4363828..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/EventMonitor.swift +++ /dev/null @@ -1,844 +0,0 @@ -// -// EventMonitor.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. -public protocol EventMonitor { - /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. - var queue: DispatchQueue { get } - - // MARK: - URLSession Events - - // MARK: URLSessionDelegate Events - - /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. - func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) - - // MARK: URLSessionTaskDelegate Events - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. - func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. - func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. - func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) - - // MARK: URLSessionDataDelegate Events - - /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) - - /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) - - // MARK: URLSessionDownloadDelegate Events - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. - func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. - func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. - func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) - - // MARK: - Request Events - - /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the - /// `URLRequest` will be adapted before being issued. - func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) - - /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. - func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) - - /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. - func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) - - /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. - func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) - - /// Event called when a final `URLRequest` is created for a `Request`. - func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) - - /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. - func request(_ request: Request, didCreateTask task: URLSessionTask) - - /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. - func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) - - /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. - func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) - - /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event - /// multiple times if it is retried. - func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) - - /// Event called when a `Request` is about to be retried. - func requestIsRetrying(_ request: Request) - - /// Event called when a `Request` finishes and response serializers are being called. - func requestDidFinish(_ request: Request) - - /// Event called when a `Request` receives a `resume` call. - func requestDidResume(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is resumed. - func request(_ request: Request, didResumeTask task: URLSessionTask) - - /// Event called when a `Request` receives a `suspend` call. - func requestDidSuspend(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is suspended. - func request(_ request: Request, didSuspendTask task: URLSessionTask) - - /// Event called when a `Request` receives a `cancel` call. - func requestDidCancel(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. - func request(_ request: Request, didCancelTask task: URLSessionTask) - - // MARK: DataRequest Events - - /// Event called when a `DataRequest` calls a `Validation`. - func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) - - /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. - func request(_ request: DataRequest, didParseResponse response: DataResponse) - - /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. - func request(_ request: DataRequest, didParseResponse response: DataResponse) - - // MARK: UploadRequest Events - - /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. - func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) - - /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. - func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) - - /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if - /// the `InputStream` does not wrap a `Data` value or file `URL`. - func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) - - // MARK: DownloadRequest Events - - /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. - func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) - - /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the - /// downloaded file will be moved to. - func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) - - /// Event called when a `DownloadRequest` calls a `Validation`. - func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) - - /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. - func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) - - /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` - func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) -} - -extension EventMonitor { - /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. - public var queue: DispatchQueue { return .main } - - // MARK: Default Implementations - - public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) {} - public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didFinishCollecting metrics: URLSessionTaskMetrics) {} - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} - public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} - public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) {} - public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} - public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} - public func request(_ request: Request, - didAdaptInitialRequest initialRequest: URLRequest, - to adaptedRequest: URLRequest) {} - public func request(_ request: Request, - didFailToAdaptURLRequest initialRequest: URLRequest, - withError error: AFError) {} - public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} - public func request(_ request: Request, didCreateTask task: URLSessionTask) {} - public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} - public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} - public func requestIsRetrying(_ request: Request) {} - public func requestDidFinish(_ request: Request) {} - public func requestDidResume(_ request: Request) {} - public func request(_ request: Request, didResumeTask task: URLSessionTask) {} - public func requestDidSuspend(_ request: Request) {} - public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} - public func requestDidCancel(_ request: Request) {} - public func request(_ request: Request, didCancelTask task: URLSessionTask) {} - public func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) {} - public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} - public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} - public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} - public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} - public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} - public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} - public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} - public func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) {} - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} -} - -/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. -public final class CompositeEventMonitor: EventMonitor { - public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .background) - - let monitors: [EventMonitor] - - init(monitors: [EventMonitor]) { - self.monitors = monitors - } - - func performEvent(_ event: @escaping (EventMonitor) -> Void) { - queue.async { - for monitor in self.monitors { - monitor.queue.async { event(monitor) } - } - } - } - - public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge) { - performEvent { $0.urlSession(session, task: task, didReceive: challenge) } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - performEvent { - $0.urlSession(session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - } - } - - public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { - performEvent { - $0.urlSession(session, taskNeedsNewBodyStream: task) - } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) { - performEvent { - $0.urlSession(session, - task: task, - willPerformHTTPRedirection: response, - newRequest: request) - } - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } - } - - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } - } - - public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse) { - performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - performEvent { - $0.urlSession(session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes) - } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - performEvent { - $0.urlSession(session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } - } - - public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { - performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } - } - - public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { - performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } - } - - public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { - performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } - } - - public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { - performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } - } - - public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { - performEvent { $0.request(request, didCreateURLRequest: urlRequest) } - } - - public func request(_ request: Request, didCreateTask task: URLSessionTask) { - performEvent { $0.request(request, didCreateTask: task) } - } - - public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { - performEvent { $0.request(request, didGatherMetrics: metrics) } - } - - public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { - performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } - } - - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - performEvent { $0.request(request, didCompleteTask: task, with: error) } - } - - public func requestIsRetrying(_ request: Request) { - performEvent { $0.requestIsRetrying(request) } - } - - public func requestDidFinish(_ request: Request) { - performEvent { $0.requestDidFinish(request) } - } - - public func requestDidResume(_ request: Request) { - performEvent { $0.requestDidResume(request) } - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - performEvent { $0.request(request, didResumeTask: task) } - } - - public func requestDidSuspend(_ request: Request) { - performEvent { $0.requestDidSuspend(request) } - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - performEvent { $0.request(request, didSuspendTask: task) } - } - - public func requestDidCancel(_ request: Request) { - performEvent { $0.requestDidCancel(request) } - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - performEvent { $0.request(request, didCancelTask: task) } - } - - public func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) { - performEvent { $0.request(request, - didValidateRequest: urlRequest, - response: response, - data: data, - withResult: result) - } - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { - performEvent { $0.request(request, didCreateUploadable: uploadable) } - } - - public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { - performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } - } - - public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { - performEvent { $0.request(request, didProvideInputStream: stream) } - } - - public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { - performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } - } - - public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { - performEvent { $0.request(request, didCreateDestinationURL: url) } - } - - public func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) { - performEvent { $0.request(request, - didValidateRequest: urlRequest, - response: response, - fileURL: fileURL, - withResult: result) } - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } -} - -/// `EventMonitor` that allows optional closures to be set to receive events. -open class ClosureEventMonitor: EventMonitor { - /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. - open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? - - /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. - open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? - - /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. - open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. - open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? - - /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. - open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? - - /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. - open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? - - /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. - open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? - - /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. - open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? - - /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. - open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - - /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. - open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. - open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` - /// event. - open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: - Request Events - - /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. - open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? - - /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. - open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? - - /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. - open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? - - /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. - open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? - - /// Closure called on the `request(_:didCreateURLRequest:)` event. - open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? - - /// Closure called on the `request(_:didCreateTask:)` event. - open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `request(_:didGatherMetrics:)` event. - open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? - - /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. - open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? - - /// Closure called on the `request(_:didCompleteTask:with:)` event. - open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? - - /// Closure called on the `requestIsRetrying(_:)` event. - open var requestIsRetrying: ((Request) -> Void)? - - /// Closure called on the `requestDidFinish(_:)` event. - open var requestDidFinish: ((Request) -> Void)? - - /// Closure called on the `requestDidResume(_:)` event. - open var requestDidResume: ((Request) -> Void)? - - /// Closure called on the `request(_:didResumeTask:)` event. - open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `requestDidSuspend(_:)` event. - open var requestDidSuspend: ((Request) -> Void)? - - /// Closure called on the `request(_:didSuspendTask:)` event. - open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `requestDidCancel(_:)` event. - open var requestDidCancel: ((Request) -> Void)? - - /// Closure called on the `request(_:didCancelTask:)` event. - open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. - open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? - - /// Closure called on the `request(_:didParseResponse:)` event. - open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? - - /// Closure called on the `request(_:didCreateUploadable:)` event. - open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? - - /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. - open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? - - /// Closure called on the `request(_:didProvideInputStream:)` event. - open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? - - /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. - open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? - - /// Closure called on the `request(_:didCreateDestinationURL:)` event. - open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? - - /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. - open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? - - /// Closure called on the `request(_:didParseResponse:)` event. - open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? - - public let queue: DispatchQueue - - /// Creates an instance using the provided queue. - /// - /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. - public init(queue: DispatchQueue = .main) { - self.queue = queue - } - - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - sessionDidBecomeInvalidWithError?(session, error) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { - taskDidReceiveChallenge?(session, task, challenge) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } - - open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { - taskNeedNewBodyStream?(session, task) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) { - taskWillPerformHTTPRedirection?(session, task, response, request) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - taskDidFinishCollectingMetrics?(session, task, metrics) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - taskDidComplete?(session, task, error) - } - - open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - taskIsWaitingForConnectivity?(session, task) - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - dataTaskDidReceiveData?(session, dataTask, data) - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { - dataTaskWillCacheResponse?(session, dataTask, proposedResponse) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } - - open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { - downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) - } - - // MARK: Request Events - - open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { - requestDidCreateInitialURLRequest?(request, urlRequest) - } - - open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { - requestDidFailToCreateURLRequestWithError?(request, error) - } - - open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { - requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) - } - - open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { - requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) - } - - open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { - requestDidCreateURLRequest?(request, urlRequest) - } - - open func request(_ request: Request, didCreateTask task: URLSessionTask) { - requestDidCreateTask?(request, task) - } - - open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { - requestDidGatherMetrics?(request, metrics) - } - - open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { - requestDidFailTaskEarlyWithError?(request, task, error) - } - - open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - requestDidCompleteTaskWithError?(request, task, error) - } - - open func requestIsRetrying(_ request: Request) { - requestIsRetrying?(request) - } - - open func requestDidFinish(_ request: Request) { - requestDidFinish?(request) - } - - open func requestDidResume(_ request: Request) { - requestDidResume?(request) - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - requestDidResumeTask?(request, task) - } - - open func requestDidSuspend(_ request: Request) { - requestDidSuspend?(request) - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - requestDidSuspendTask?(request, task) - } - - open func requestDidCancel(_ request: Request) { - requestDidCancel?(request) - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - requestDidCancelTask?(request, task) - } - - open func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) { - requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) - } - - open func request(_ request: DataRequest, didParseResponse response: DataResponse) { - requestDidParseResponse?(request, response) - } - - open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { - requestDidCreateUploadable?(request, uploadable) - } - - open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { - requestDidFailToCreateUploadableWithError?(request, error) - } - - open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { - requestDidProvideInputStream?(request, stream) - } - - open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { - requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) - } - - open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { - requestDidCreateDestinationURL?(request, url) - } - - open func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) { - requestDidValidateRequestResponseFileURLWithResult?(request, - urlRequest, - response, - fileURL, - result) - } - - open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - requestDidParseDownloadResponse?(request, response) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPHeaders.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPHeaders.swift deleted file mode 100644 index 2833bb7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPHeaders.swift +++ /dev/null @@ -1,445 +0,0 @@ -// -// HTTPHeaders.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// An order-preserving and case-insensitive representation of HTTP headers. -public struct HTTPHeaders { - private var headers: [HTTPHeader] = [] - - /// Creates an empty instance. - public init() {} - - /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last - /// name and value encountered. - public init(_ headers: [HTTPHeader]) { - self.init() - - headers.forEach { update($0) } - } - - /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name - /// and value encountered. - public init(_ dictionary: [String: String]) { - self.init() - - dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } - } - - /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. - /// - /// - Parameters: - /// - name: The `HTTPHeader` name. - /// - value: The `HTTPHeader value. - public mutating func add(name: String, value: String) { - update(HTTPHeader(name: name, value: value)) - } - - /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. - /// - /// - Parameter header: The `HTTPHeader` to update or append. - public mutating func add(_ header: HTTPHeader) { - update(header) - } - - /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. - /// - /// - Parameters: - /// - name: The `HTTPHeader` name. - /// - value: The `HTTPHeader value. - public mutating func update(name: String, value: String) { - update(HTTPHeader(name: name, value: value)) - } - - /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. - /// - /// - Parameter header: The `HTTPHeader` to update or append. - public mutating func update(_ header: HTTPHeader) { - guard let index = headers.index(of: header.name) else { - headers.append(header) - return - } - - headers.replaceSubrange(index...index, with: [header]) - } - - /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. - /// - /// - Parameter name: The name of the `HTTPHeader` to remove. - public mutating func remove(name: String) { - guard let index = headers.index(of: name) else { return } - - headers.remove(at: index) - } - - /// Sort the current instance by header name. - public mutating func sort() { - headers.sort { $0.name < $1.name } - } - - /// Returns an instance sorted by header name. - /// - /// - Returns: A copy of the current instance sorted by name. - public func sorted() -> HTTPHeaders { - return HTTPHeaders(headers.sorted { $0.name < $1.name }) - } - - /// Case-insensitively find a header's value by name. - /// - /// - Parameter name: The name of the header to search for, case-insensitively. - /// - /// - Returns: The value of header, if it exists. - public func value(for name: String) -> String? { - guard let index = headers.index(of: name) else { return nil } - - return headers[index].value - } - - /// Case-insensitively access the header with the given name. - /// - /// - Parameter name: The name of the header. - public subscript(_ name: String) -> String? { - get { return value(for: name) } - set { - if let value = newValue { - update(name: name, value: value) - } else { - remove(name: name) - } - } - } - - /// The dictionary representation of all headers. - /// - /// This representation does not preserve the current order of the instance. - public var dictionary: [String: String] { - let namesAndValues = headers.map { ($0.name, $0.value) } - - return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) - } -} - -extension HTTPHeaders: ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, String)...) { - self.init() - - elements.forEach { update(name: $0.0, value: $0.1) } - } -} - -extension HTTPHeaders: ExpressibleByArrayLiteral { - public init(arrayLiteral elements: HTTPHeader...) { - self.init(elements) - } -} - -extension HTTPHeaders: Sequence { - public func makeIterator() -> IndexingIterator<[HTTPHeader]> { - return headers.makeIterator() - } -} - -extension HTTPHeaders: Collection { - public var startIndex: Int { - return headers.startIndex - } - - public var endIndex: Int { - return headers.endIndex - } - - public subscript(position: Int) -> HTTPHeader { - return headers[position] - } - - public func index(after i: Int) -> Int { - return headers.index(after: i) - } -} - -extension HTTPHeaders: CustomStringConvertible { - public var description: String { - return headers.map { $0.description } - .joined(separator: "\n") - } -} - -// MARK: - HTTPHeader - -/// A representation of a single HTTP header's name / value pair. -public struct HTTPHeader: Hashable { - /// Name of the header. - public let name: String - - /// Value of the header. - public let value: String - - /// Creates an instance from the given `name` and `value`. - /// - /// - Parameters: - /// - name: The name of the header. - /// - value: The value of the header. - public init(name: String, value: String) { - self.name = name - self.value = value - } -} - -extension HTTPHeader: CustomStringConvertible { - public var description: String { - return "\(name): \(value)" - } -} - -extension HTTPHeader { - /// Returns an `Accept` header. - /// - /// - Parameter value: The `Accept` value. - /// - Returns: The header. - public static func accept(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Accept", value: value) - } - - /// Returns an `Accept-Charset` header. - /// - /// - Parameter value: The `Accept-Charset` value. - /// - Returns: The header. - public static func acceptCharset(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Accept-Charset", value: value) - } - - /// Returns an `Accept-Language` header. - /// - /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. - /// Use `HTTPHeader.defaultAcceptLanguage`. - /// - /// - Parameter value: The `Accept-Language` value. - /// - /// - Returns: The header. - public static func acceptLanguage(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Accept-Language", value: value) - } - - /// Returns an `Accept-Encoding` header. - /// - /// Alamofire offers a default accept encoding value that provides the most common values. Use - /// `HTTPHeader.defaultAcceptEncoding`. - /// - /// - Parameter value: The `Accept-Encoding` value. - /// - /// - Returns: The header - public static func acceptEncoding(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Accept-Encoding", value: value) - } - - /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. - /// - /// - Parameters: - /// - username: The username of the header. - /// - password: The password of the header. - /// - /// - Returns: The header. - public static func authorization(username: String, password: String) -> HTTPHeader { - let credential = Data("\(username):\(password)".utf8).base64EncodedString() - - return authorization("Basic \(credential)") - } - - /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided - /// - /// - Parameter bearerToken: The bearer token. - /// - /// - Returns: The header. - public static func authorization(bearerToken: String) -> HTTPHeader { - return authorization("Bearer \(bearerToken)") - } - - /// Returns an `Authorization` header. - /// - /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use - /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use - /// `HTTPHeader.authorization(bearerToken:)`. - /// - /// - Parameter value: The `Authorization` value. - /// - /// - Returns: The header. - public static func authorization(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Authorization", value: value) - } - - /// Returns a `Content-Disposition` header. - /// - /// - Parameter value: The `Content-Disposition` value. - /// - /// - Returns: The header. - public static func contentDisposition(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Content-Disposition", value: value) - } - - /// Returns a `Content-Type` header. - /// - /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not be necessary to manually - /// set this value. - /// - /// - Parameter value: The `Content-Type` value. - /// - /// - Returns: The header. - public static func contentType(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "Content-Type", value: value) - } - - /// Returns a `User-Agent` header. - /// - /// - Parameter value: The `User-Agent` value. - /// - /// - Returns: The header. - public static func userAgent(_ value: String) -> HTTPHeader { - return HTTPHeader(name: "User-Agent", value: value) - } -} - -extension Array where Element == HTTPHeader { - /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. - func index(of name: String) -> Int? { - let lowercasedName = name.lowercased() - return firstIndex { $0.name.lowercased() == lowercasedName } - } -} - -// MARK: - Defaults - -public extension HTTPHeaders { - /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and - /// `User-Agent`. - static let `default`: HTTPHeaders = [.defaultAcceptEncoding, - .defaultAcceptLanguage, - .defaultUserAgent] -} - -extension HTTPHeader { - /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS - /// versions. - /// - /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . - public static let defaultAcceptEncoding: HTTPHeader = { - let encodings: [String] - if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { - encodings = ["br", "gzip", "deflate"] - } else { - encodings = ["gzip", "deflate"] - } - - return .acceptEncoding(encodings.qualityEncoded()) - }() - - /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's - /// `preferredLanguages`. - /// - /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). - public static let defaultAcceptLanguage: HTTPHeader = { - .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) - }() - - /// Returns Alamofire's default `User-Agent` header. - /// - /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). - /// - /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` - public static let defaultUserAgent: HTTPHeader = { - let userAgent: String = { - if let info = Bundle.main.infoDictionary { - let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" - let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" - let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" - let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - - let osNameVersion: String = { - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - // swiftformat:disable indent - let osName: String = { - #if os(iOS) - return "iOS" - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "macOS" - #elseif os(Linux) - return "Linux" - #else - return "Unknown" - #endif - }() - // swiftformat:enable indent - - return "\(osName) \(versionString)" - }() - - let alamofireVersion = "Alamofire/\(AF.version)" - - return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" - } - - return "Alamofire" - }() - - return .userAgent(userAgent) - }() -} - -extension Collection where Element == String { - func qualityEncoded() -> String { - return enumerated().map { index, encoding in - let quality = 1.0 - (Double(index) * 0.1) - return "\(encoding);q=\(quality)" - }.joined(separator: ", ") - } -} - -// MARK: - System Type Extensions - -extension URLRequest { - /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. - public var headers: HTTPHeaders { - get { return allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } - set { allHTTPHeaderFields = newValue.dictionary } - } -} - -extension HTTPURLResponse { - /// Returns `allHeaderFields` as `HTTPHeaders`. - public var headers: HTTPHeaders { - return (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() - } -} - -public extension URLSessionConfiguration { - /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. - var headers: HTTPHeaders { - get { return (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } - set { httpAdditionalHeaders = newValue.dictionary } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPMethod.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPMethod.swift deleted file mode 100644 index 4867c1e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/HTTPMethod.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// HTTPMethod.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so -/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. -/// -/// See https://tools.ietf.org/html/rfc7231#section-4.3 -public struct HTTPMethod: RawRepresentable, Equatable, Hashable { - /// `CONNECT` method. - public static let connect = HTTPMethod(rawValue: "CONNECT") - /// `DELETE` method. - public static let delete = HTTPMethod(rawValue: "DELETE") - /// `GET` method. - public static let get = HTTPMethod(rawValue: "GET") - /// `HEAD` method. - public static let head = HTTPMethod(rawValue: "HEAD") - /// `OPTIONS` method. - public static let options = HTTPMethod(rawValue: "OPTIONS") - /// `PATCH` method. - public static let patch = HTTPMethod(rawValue: "PATCH") - /// `POST` method. - public static let post = HTTPMethod(rawValue: "POST") - /// `PUT` method. - public static let put = HTTPMethod(rawValue: "PUT") - /// `TRACE` method. - public static let trace = HTTPMethod(rawValue: "TRACE") - - public let rawValue: String - - public init(rawValue: String) { - self.rawValue = rawValue - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Info.plist b/Lesson12/Carthage/Checkouts/Alamofire/Source/Info.plist deleted file mode 100644 index 747466d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Info.plist +++ /dev/null @@ -1,24 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - FMWK - CFBundleShortVersionString - 5.0.0 - CFBundleSignature - ???? - CFBundleVersion - $(CURRENT_PROJECT_VERSION) - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartFormData.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartFormData.swift deleted file mode 100644 index 4ef54aa..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartFormData.swift +++ /dev/null @@ -1,544 +0,0 @@ -// -// MultipartFormData.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -#if os(iOS) || os(watchOS) || os(tvOS) -import MobileCoreServices -#elseif os(macOS) -import CoreServices -#endif - -/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode -/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. -/// -/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well -/// and the w3 form documentation. -/// -/// - https://www.ietf.org/rfc/rfc2388.txt -/// - https://www.ietf.org/rfc/rfc2045.txt -/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 -open class MultipartFormData { - // MARK: - Helper Types - - struct EncodingCharacters { - static let crlf = "\r\n" - } - - struct BoundaryGenerator { - enum BoundaryType { - case initial, encapsulated, final - } - - static func randomBoundary() -> String { - return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) - } - - static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { - let boundaryText: String - - switch boundaryType { - case .initial: - boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" - case .encapsulated: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" - case .final: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" - } - - return Data(boundaryText.utf8) - } - } - - class BodyPart { - let headers: HTTPHeaders - let bodyStream: InputStream - let bodyContentLength: UInt64 - var hasInitialBoundary = false - var hasFinalBoundary = false - - init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { - self.headers = headers - self.bodyStream = bodyStream - self.bodyContentLength = bodyContentLength - } - } - - // MARK: - Properties - - /// Default memory threshold used when encoding `MultipartFormData`, in bytes. - public static let encodingMemoryThreshold: UInt64 = 10_000_000 - - /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. - open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" - - /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. - public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } - - /// The boundary used to separate the body parts in the encoded form data. - public let boundary: String - - let fileManager: FileManager - - private var bodyParts: [BodyPart] - private var bodyPartError: AFError? - private let streamBufferSize: Int - - // MARK: - Lifecycle - - /// Creates an instance. - /// - /// - Parameters: - /// - fileManager: `FileManager` to use for file operations, if needed. - /// - boundary: Boundary `String` used to separate body parts. - public init(fileManager: FileManager = .default, boundary: String? = nil) { - self.fileManager = fileManager - self.boundary = boundary ?? BoundaryGenerator.randomBoundary() - bodyParts = [] - - // - // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more - // information, please refer to the following article: - // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html - // - streamBufferSize = 1024 - } - - // MARK: - Body Parts - - /// Creates a body part from the data and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - Parameters: - /// - data: `Data` to encoding into the instance. - /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the file and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the - /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the - /// system associated MIME type. - /// - /// - Parameters: - /// - fileURL: `URL` of the file whose content will be encoded into the instance. - /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. - public func append(_ fileURL: URL, withName name: String) { - let fileName = fileURL.lastPathComponent - let pathExtension = fileURL.pathExtension - - if !fileName.isEmpty && !pathExtension.isEmpty { - let mime = mimeType(forPathExtension: pathExtension) - append(fileURL, withName: name, fileName: fileName, mimeType: mime) - } else { - setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) - } - } - - /// Creates a body part from the file and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - /// - Content-Type: #{mimeType} (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - Parameters: - /// - fileURL: `URL` of the file whose content will be encoded into the instance. - /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. - public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - - //============================================================ - // Check 1 - is file URL? - //============================================================ - - guard fileURL.isFileURL else { - setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) - return - } - - //============================================================ - // Check 2 - is file URL reachable? - //============================================================ - - do { - let isReachable = try fileURL.checkPromisedItemIsReachable() - guard isReachable else { - setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) - return - } - } catch { - setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 3 - is file URL a directory? - //============================================================ - - var isDirectory: ObjCBool = false - let path = fileURL.path - - guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { - setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) - return - } - - //============================================================ - // Check 4 - can the file size be extracted? - //============================================================ - - let bodyContentLength: UInt64 - - do { - guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { - setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) - return - } - - bodyContentLength = fileSize.uint64Value - } catch { - setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 5 - can a stream be created from file URL? - //============================================================ - - guard let stream = InputStream(url: fileURL) else { - setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) - return - } - - append(stream, withLength: bodyContentLength, headers: headers) - } - - /// Creates a body part from the stream and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - Parameters: - /// - stream: `InputStream` to encode into the instance. - /// - length: Length, in bytes, of the stream. - /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. - public func append(_ stream: InputStream, - withLength length: UInt64, - name: String, - fileName: String, - mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part with the stream, length, and headers and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - HTTP headers - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - Parameters: - /// - stream: `InputStream` to encode into the instance. - /// - length: Length, in bytes, of the stream. - /// - headers: `HTTPHeaders` for the body part. - public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { - let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) - bodyParts.append(bodyPart) - } - - // MARK: - Data Encoding - - /// Encodes all appended body parts into a single `Data` value. - /// - /// - Note: This method will load all the appended body parts into memory all at the same time. This method should - /// only be used when the encoded data will have a small memory footprint. For large data cases, please use - /// the `writeEncodedData(to:))` method. - /// - /// - Returns: The encoded `Data`, if encoding is successful. - /// - Throws: An `AFError` if encoding encounters an error. - public func encode() throws -> Data { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - var encoded = Data() - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - let encodedData = try encode(bodyPart) - encoded.append(encodedData) - } - - return encoded - } - - /// Writes all appended body parts to the given file `URL`. - /// - /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, - /// this approach is very memory efficient and should be used for large body part data. - /// - /// - Parameter fileURL: File `URL` to which to write the form data. - /// - Throws: An `AFError` if encoding encounters an error. - public func writeEncodedData(to fileURL: URL) throws { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - if fileManager.fileExists(atPath: fileURL.path) { - throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) - } else if !fileURL.isFileURL { - throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) - } - - guard let outputStream = OutputStream(url: fileURL, append: false) else { - throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) - } - - outputStream.open() - defer { outputStream.close() } - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - try write(bodyPart, to: outputStream) - } - } - - // MARK: - Private - Body Part Encoding - - private func encode(_ bodyPart: BodyPart) throws -> Data { - var encoded = Data() - - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - encoded.append(initialData) - - let headerData = encodeHeaders(for: bodyPart) - encoded.append(headerData) - - let bodyStreamData = try encodeBodyStream(for: bodyPart) - encoded.append(bodyStreamData) - - if bodyPart.hasFinalBoundary { - encoded.append(finalBoundaryData()) - } - - return encoded - } - - private func encodeHeaders(for bodyPart: BodyPart) -> Data { - let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } - .joined() - + EncodingCharacters.crlf - - return Data(headerText.utf8) - } - - private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { - let inputStream = bodyPart.bodyStream - inputStream.open() - defer { inputStream.close() } - - var encoded = Data() - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let error = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) - } - - if bytesRead > 0 { - encoded.append(buffer, count: bytesRead) - } else { - break - } - } - - return encoded - } - - // MARK: - Private - Writing Body Part to Output Stream - - private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { - try writeInitialBoundaryData(for: bodyPart, to: outputStream) - try writeHeaderData(for: bodyPart, to: outputStream) - try writeBodyStream(for: bodyPart, to: outputStream) - try writeFinalBoundaryData(for: bodyPart, to: outputStream) - } - - private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - return try write(initialData, to: outputStream) - } - - private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let headerData = encodeHeaders(for: bodyPart) - return try write(headerData, to: outputStream) - } - - private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let inputStream = bodyPart.bodyStream - - inputStream.open() - defer { inputStream.close() } - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let streamError = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) - } - - if bytesRead > 0 { - if buffer.count != bytesRead { - buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { - let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) - - if let error = outputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) - } - - bytesToWrite -= bytesWritten - - if bytesToWrite > 0 { - buffer = Array(buffer[bytesWritten.. String { - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { - return contentType as String - } - - return "application/octet-stream" - } - - // MARK: - Private - Content Headers - - private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders { - var disposition = "form-data; name=\"\(name)\"" - if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } - - var headers: HTTPHeaders = [.contentDisposition(disposition)] - if let mimeType = mimeType { headers.add(.contentType(mimeType)) } - - return headers - } - - // MARK: - Private - Boundary Encoding - - private func initialBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) - } - - private func encapsulatedBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) - } - - private func finalBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) - } - - // MARK: - Private - Errors - - private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { - guard bodyPartError == nil else { return } - bodyPartError = AFError.multipartEncodingFailed(reason: reason) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartUpload.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartUpload.swift deleted file mode 100644 index 4772c30..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/MultipartUpload.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// MultipartUpload.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Internal type which encapsulates a `MultipartFormData` upload. -final class MultipartUpload { - lazy var result = Result { try build() } - - let isInBackgroundSession: Bool - let multipartFormData: MultipartFormData - let encodingMemoryThreshold: UInt64 - let request: URLRequestConvertible - let fileManager: FileManager - - init(isInBackgroundSession: Bool, - encodingMemoryThreshold: UInt64, - request: URLRequestConvertible, - multipartFormData: MultipartFormData) { - self.isInBackgroundSession = isInBackgroundSession - self.encodingMemoryThreshold = encodingMemoryThreshold - self.request = request - fileManager = multipartFormData.fileManager - self.multipartFormData = multipartFormData - } - - func build() throws -> (request: URLRequest, uploadable: UploadRequest.Uploadable) { - var urlRequest = try request.asURLRequest() - urlRequest.setValue(multipartFormData.contentType, forHTTPHeaderField: "Content-Type") - - let uploadable: UploadRequest.Uploadable - if multipartFormData.contentLength < encodingMemoryThreshold && !isInBackgroundSession { - let data = try multipartFormData.encode() - - uploadable = .data(data) - } else { - let tempDirectoryURL = fileManager.temporaryDirectory - let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") - let fileName = UUID().uuidString - let fileURL = directoryURL.appendingPathComponent(fileName) - - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) - - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - // Cleanup after attempted write if it fails. - try? fileManager.removeItem(at: fileURL) - } - - uploadable = .file(fileURL, shouldRemove: true) - } - - return (request: urlRequest, uploadable: uploadable) - } -} - -extension MultipartUpload: UploadConvertible { - func asURLRequest() throws -> URLRequest { - return try result.get().request - } - - func createUploadable() throws -> UploadRequest.Uploadable { - return try result.get().uploadable - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/NetworkReachabilityManager.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/NetworkReachabilityManager.swift deleted file mode 100644 index d2c4338..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/NetworkReachabilityManager.swift +++ /dev/null @@ -1,266 +0,0 @@ -// -// NetworkReachabilityManager.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if !(os(watchOS) || os(Linux)) - -import Foundation -import SystemConfiguration - -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and -/// WiFi network interfaces. -/// -/// Reachability can be used to determine background information about why a network operation failed, or to retry -/// network requests when a connection is established. It should not be used to prevent a user from initiating a network -/// request, as it's possible that an initial request may be required to establish reachability. -open class NetworkReachabilityManager { - /// Defines the various states of network reachability. - public enum NetworkReachabilityStatus { - /// It is unknown whether the network is reachable. - case unknown - /// The network is not reachable. - case notReachable - /// The network is reachable on the associated `ConnectionType`. - case reachable(ConnectionType) - - init(_ flags: SCNetworkReachabilityFlags) { - guard flags.isActuallyReachable else { self = .notReachable; return } - - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) - - if flags.isCellular { networkStatus = .reachable(.cellular) } - - self = networkStatus - } - - /// Defines the various connection types detected by reachability flags. - public enum ConnectionType { - /// The connection type is either over Ethernet or WiFi. - case ethernetOrWiFi - /// The connection type is a cellular connection. - case cellular - } - } - - /// A closure executed when the network reachability status changes. The closure takes a single argument: the - /// network reachability status. - public typealias Listener = (NetworkReachabilityStatus) -> Void - - /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. - public static let `default` = NetworkReachabilityManager() - - // MARK: - Properties - - /// Whether the network is currently reachable. - open var isReachable: Bool { return isReachableOnCellular || isReachableOnEthernetOrWiFi } - - /// Whether the network is currently reachable over the cellular interface. - /// - /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. - /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. - /// - open var isReachableOnCellular: Bool { return status == .reachable(.cellular) } - - /// Whether the network is currently reachable over Ethernet or WiFi interface. - open var isReachableOnEthernetOrWiFi: Bool { return status == .reachable(.ethernetOrWiFi) } - - /// `DispatchQueue` on which reachability will update. - public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") - - /// Flags of the current reachability type, if any. - open var flags: SCNetworkReachabilityFlags? { - var flags = SCNetworkReachabilityFlags() - - return (SCNetworkReachabilityGetFlags(reachability, &flags)) ? flags : nil - } - - /// The current network reachability status. - open var status: NetworkReachabilityStatus { - return flags.map(NetworkReachabilityStatus.init) ?? .unknown - } - - /// Mutable state storage. - struct MutableState { - /// A closure executed when the network reachability status changes. - var listener: Listener? - /// `DispatchQueue` on which listeners will be called. - var listenerQueue: DispatchQueue? - /// Previously calculated status. - var previousStatus: NetworkReachabilityStatus? - } - - /// `SCNetworkReachability` instance providing notifications. - private let reachability: SCNetworkReachability - - /// Protected storage for mutable state. - private let mutableState = Protector(MutableState()) - - // MARK: - Initialization - - /// Creates an instance with the specified host. - /// - /// - Note: The `host` value must *not* contain a scheme, just the hostname. - /// - /// - Parameters: - /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). - public convenience init?(host: String) { - guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } - - self.init(reachability: reachability) - } - - /// Creates an instance that monitors the address 0.0.0.0. - /// - /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing - /// status of the device, both IPv4 and IPv6. - public convenience init?() { - var zero = sockaddr() - zero.sa_len = UInt8(MemoryLayout.size) - zero.sa_family = sa_family_t(AF_INET) - - guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } - - self.init(reachability: reachability) - } - - private init(reachability: SCNetworkReachability) { - self.reachability = reachability - } - - deinit { - stopListening() - } - - // MARK: - Listening - - /// Starts listening for changes in network reachability status. - /// - /// - Note: Stops and removes any existing listener. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. - /// - listener: `Listener` closure called when reachability changes. - /// - /// - Returns: `true` if listening was started successfully, `false` otherwise. - @discardableResult - open func startListening(onQueue queue: DispatchQueue = .main, - onUpdatePerforming listener: @escaping Listener) -> Bool { - stopListening() - - mutableState.write { state in - state.listenerQueue = queue - state.listener = listener - } - - var context = SCNetworkReachabilityContext(version: 0, - info: Unmanaged.passRetained(self).toOpaque(), - retain: nil, - release: nil, - copyDescription: nil) - let callback: SCNetworkReachabilityCallBack = { _, flags, info in - guard let info = info else { return } - - let instance = Unmanaged.fromOpaque(info).takeUnretainedValue() - instance.notifyListener(flags) - } - - let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) - let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) - - // Manually call listener to give initial state, since the framework may not. - if let currentFlags = flags { - reachabilityQueue.async { - self.notifyListener(currentFlags) - } - } - - return callbackAdded && queueAdded - } - - /// Stops listening for changes in network reachability status. - open func stopListening() { - SCNetworkReachabilitySetCallback(reachability, nil, nil) - SCNetworkReachabilitySetDispatchQueue(reachability, nil) - mutableState.write { state in - state.listener = nil - state.listenerQueue = nil - state.previousStatus = nil - } - } - - // MARK: - Internal - Listener Notification - - /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. - /// - /// - Note: Should only be called from the `reachabilityQueue`. - /// - /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. - func notifyListener(_ flags: SCNetworkReachabilityFlags) { - let newStatus = NetworkReachabilityStatus(flags) - - mutableState.write { state in - guard state.previousStatus != newStatus else { return } - - state.previousStatus = newStatus - - let listener = state.listener - state.listenerQueue?.async { listener?(newStatus) } - } - } -} - -// MARK: - - -extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} - -extension SCNetworkReachabilityFlags { - var isReachable: Bool { return contains(.reachable) } - var isConnectionRequired: Bool { return contains(.connectionRequired) } - var canConnectAutomatically: Bool { return contains(.connectionOnDemand) || contains(.connectionOnTraffic) } - var canConnectWithoutUserInteraction: Bool { return canConnectAutomatically && !contains(.interventionRequired) } - var isActuallyReachable: Bool { return isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } - var isCellular: Bool { -#if os(iOS) || os(tvOS) - return contains(.isWWAN) -#else - return false -#endif - } - - /// Human readable `String` for all states, to help with debugging. - var readableDescription: String { - let W = isCellular ? "W" : "-" - let R = isReachable ? "R" : "-" - let c = isConnectionRequired ? "c" : "-" - let t = contains(.transientConnection) ? "t" : "-" - let i = contains(.interventionRequired) ? "i" : "-" - let C = contains(.connectionOnTraffic) ? "C" : "-" - let D = contains(.connectionOnDemand) ? "D" : "-" - let l = contains(.isLocalAddress) ? "l" : "-" - let d = contains(.isDirect) ? "d" : "-" - let a = contains(.connectionAutomatic) ? "a" : "-" - - return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" - } -} -#endif diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Notifications.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Notifications.swift deleted file mode 100644 index 4a4b25a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Notifications.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// Notifications.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -public extension Request { - /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. - static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") - /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. - static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") - /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. - static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") - /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. - static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") - - /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. - static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") - /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. - static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") - /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. - static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") - /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. - static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") -} - -// MARK: - - -extension Notification { - /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. - public var request: Request? { - return userInfo?[String.requestKey] as? Request - } - - /// Convenience initializer for a `Notification` containing a `Request` payload. - /// - /// - Parameters: - /// - name: The name of the notification. - /// - request: The `Request` payload. - init(name: Notification.Name, request: Request) { - self.init(name: name, object: nil, userInfo: [String.requestKey: request]) - } -} - -extension NotificationCenter { - /// Convenience function for posting notifications with `Request` payloads. - /// - /// - Parameters: - /// - name: The name of the notification. - /// - request: The `Request` payload. - func postNotification(named name: Notification.Name, with request: Request) { - let notification = Notification(name: name, request: request) - post(notification) - } -} - -extension String { - /// User info dictionary key representing the `Request` associated with the notification. - fileprivate static let requestKey = "org.alamofire.notification.key.request" -} - -/// `EventMonitor` that provides Alamofire's notifications. -public final class AlamofireNotifications: EventMonitor { - public func requestDidResume(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) - } - - public func requestDidSuspend(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) - } - - public func requestDidCancel(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) - } - - public func requestDidFinish(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) - } - - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/OperationQueue+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/OperationQueue+Alamofire.swift deleted file mode 100644 index b06a0cc..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/OperationQueue+Alamofire.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// OperationQueue+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension OperationQueue { - /// Creates an instance using the provided parameters. - /// - /// - Parameters: - /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. - /// - maxConcurrentOperationCount: Maximum concurrent operations. - /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. - /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. - /// - name: Name for the queue. `nil` by default. - /// - startSuspended: Whether the queue starts suspended. `false` by default. - convenience init(qualityOfService: QualityOfService = .default, - maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, - underlyingQueue: DispatchQueue? = nil, - name: String? = nil, - startSuspended: Bool = false) { - self.init() - self.qualityOfService = qualityOfService - self.maxConcurrentOperationCount = maxConcurrentOperationCount - self.underlyingQueue = underlyingQueue - self.name = name - isSuspended = startSuspended - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoder.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoder.swift deleted file mode 100644 index 1e5c70a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoder.swift +++ /dev/null @@ -1,184 +0,0 @@ -// -// ParameterEncoder.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that can encode any `Encodable` type into a `URLRequest`. -public protocol ParameterEncoder { - /// Encode the provided `Encodable` parameters into `request`. - /// - /// - Parameters: - /// - parameters: The `Encodable` parameter value. - /// - request: The `URLRequest` into which to encode the parameters. - /// - /// - Returns: A `URLRequest` with the result of the encoding. - /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of - /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. - func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest -} - -/// A `ParameterEncoder` that encodes types as JSON body data. -/// -/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. -open class JSONParameterEncoder: ParameterEncoder { - /// Returns an encoder with default parameters. - public static var `default`: JSONParameterEncoder { return JSONParameterEncoder() } - - /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. - public static var prettyPrinted: JSONParameterEncoder { - let encoder = JSONEncoder() - encoder.outputFormatting = .prettyPrinted - - return JSONParameterEncoder(encoder: encoder) - } - - /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - public static var sortedKeys: JSONParameterEncoder { - let encoder = JSONEncoder() - encoder.outputFormatting = .sortedKeys - - return JSONParameterEncoder(encoder: encoder) - } - - /// `JSONEncoder` used to encode parameters. - public let encoder: JSONEncoder - - /// Creates an instance with the provided `JSONEncoder`. - /// - /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. - public init(encoder: JSONEncoder = JSONEncoder()) { - self.encoder = encoder - } - - open func encode(_ parameters: Parameters?, - into request: URLRequest) throws -> URLRequest { - guard let parameters = parameters else { return request } - - var request = request - - do { - let data = try encoder.encode(parameters) - request.httpBody = data - if request.headers["Content-Type"] == nil { - request.headers.update(.contentType("application/json")) - } - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return request - } -} - -/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -/// on the `Destination` set. -/// -/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. -open class URLEncodedFormParameterEncoder: ParameterEncoder { - /// Defines where the URL-encoded string should be set for each `URLRequest`. - public enum Destination { - /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. - /// Sets it to the `httpBody` for all other methods. - case methodDependent - /// Applies the encoded query string to any existing query string from the `URLRequest`. - case queryString - /// Applies the encoded query string to the `httpBody` of the `URLRequest`. - case httpBody - - /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. - /// - /// - Parameter method: The `HTTPMethod`. - /// - /// - Returns: Whether the URL-encoded string should be applied to a `URL`. - func encodesParametersInURL(for method: HTTPMethod) -> Bool { - switch self { - case .methodDependent: return [.get, .head, .delete].contains(method) - case .queryString: return true - case .httpBody: return false - } - } - } - - /// Returns an encoder with default parameters. - public static var `default`: URLEncodedFormParameterEncoder { return URLEncodedFormParameterEncoder() } - - /// The `URLEncodedFormEncoder` to use. - public let encoder: URLEncodedFormEncoder - - /// The `Destination` for the URL-encoded string. - public let destination: Destination - - /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. - /// - /// - Parameters: - /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. - /// - destination: The `Destination`. `.methodDependent` by default. - public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { - self.encoder = encoder - self.destination = destination - } - - open func encode(_ parameters: Parameters?, - into request: URLRequest) throws -> URLRequest { - guard let parameters = parameters else { return request } - - var request = request - - guard let url = request.url else { - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) - } - - guard let method = request.method else { - let rawValue = request.method?.rawValue ?? "nil" - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) - } - - if destination.encodesParametersInURL(for: method), - var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let query: String = try Result { try encoder.encode(parameters) } - .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() - let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() - components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString - - guard let newURL = components.url else { - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) - } - - request.url = newURL - } else { - if request.headers["Content-Type"] == nil { - request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) - } - - request.httpBody = try Result { try encoder.encode(parameters) } - .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() - } - - return request - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift deleted file mode 100644 index fbf1701..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift +++ /dev/null @@ -1,314 +0,0 @@ -// -// ParameterEncoding.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A dictionary of parameters to apply to a `URLRequest`. -public typealias Parameters = [String: Any] - -/// A type used to define how a set of parameters are applied to a `URLRequest`. -public protocol ParameterEncoding { - /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. - /// - /// - Parameters: - /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. - /// - parameters: `Parameters` to encode onto the request. - /// - /// - Returns: The encoded `URLRequest`. - /// - Throws: Any `Error` produced during parameter encoding. - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest -} - -// MARK: - - -/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -/// the HTTP body depends on the destination of the encoding. -/// -/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// There is no published specification for how to encode collection types. By default the convention of appending -/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for -/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the -/// square brackets appended to array keys. -/// -/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode -/// `true` as 1 and `false` as 0. -public struct URLEncoding: ParameterEncoding { - // MARK: Helper Types - - /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the - /// resulting URL request. - public enum Destination { - /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and - /// sets as the HTTP body for requests with any other HTTP method. - case methodDependent - /// Sets or appends encoded query string result to existing query string. - case queryString - /// Sets encoded query string result as the HTTP body of the URL request. - case httpBody - - func encodesParametersInURL(for method: HTTPMethod) -> Bool { - switch self { - case .methodDependent: return [.get, .head, .delete].contains(method) - case .queryString: return true - case .httpBody: return false - } - } - } - - /// Configures how `Array` parameters are encoded. - public enum ArrayEncoding { - /// An empty set of square brackets is appended to the key for every value. This is the default behavior. - case brackets - /// No brackets are appended. The key is encoded as is. - case noBrackets - - func encode(key: String) -> String { - switch self { - case .brackets: - return "\(key)[]" - case .noBrackets: - return key - } - } - } - - /// Configures how `Bool` parameters are encoded. - public enum BoolEncoding { - /// Encode `true` as `1` and `false` as `0`. This is the default behavior. - case numeric - /// Encode `true` and `false` as string literals. - case literal - - func encode(value: Bool) -> String { - switch self { - case .numeric: - return value ? "1" : "0" - case .literal: - return value ? "true" : "false" - } - } - } - - // MARK: Properties - - /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. - public static var `default`: URLEncoding { return URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.queryString` destination. - public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } - - /// Returns a `URLEncoding` instance with an `.httpBody` destination. - public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } - - /// The destination defining where the encoded query string is to be applied to the URL request. - public let destination: Destination - - /// The encoding to use for `Array` parameters. - public let arrayEncoding: ArrayEncoding - - /// The encoding to use for `Bool` parameters. - public let boolEncoding: BoolEncoding - - // MARK: Initialization - - /// Creates an instance using the specified parameters. - /// - /// - Parameters: - /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by - /// default. - /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. - /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. - public init(destination: Destination = .methodDependent, - arrayEncoding: ArrayEncoding = .brackets, - boolEncoding: BoolEncoding = .numeric) { - self.destination = destination - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - } - - // MARK: Encoding - - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { - guard let url = urlRequest.url else { - throw AFError.parameterEncodingFailed(reason: .missingURL) - } - - if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { - let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) - urlComponents.percentEncodedQuery = percentEncodedQuery - urlRequest.url = urlComponents.url - } - } else { - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = Data(query(parameters).utf8) - } - - return urlRequest - } - - /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. - /// - /// - Parameters: - /// - key: Key of the query component. - /// - value: Value of the query component. - /// - /// - Returns: The percent-escaped, URL encoded query string components. - public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { - var components: [(String, String)] = [] - - if let dictionary = value as? [String: Any] { - for (nestedKey, value) in dictionary { - components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) - } - } else if let array = value as? [Any] { - for value in array { - components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) - } - } else if let value = value as? NSNumber { - if value.isBool { - components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - } else if let bool = value as? Bool { - components.append((escape(key), escape(boolEncoding.encode(value: bool)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - - return components - } - - /// Creates a percent-escaped string following RFC 3986 for a query string key or value. - /// - /// - Parameter string: `String` to be percent-escaped. - /// - /// - Returns: The percent-escaped `String`. - public func escape(_ string: String) -> String { - return string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string - } - - private func query(_ parameters: [String: Any]) -> String { - var components: [(String, String)] = [] - - for key in parameters.keys.sorted(by: <) { - let value = parameters[key]! - components += queryComponents(fromKey: key, value: value) - } - return components.map { "\($0)=\($1)" }.joined(separator: "&") - } -} - -// MARK: - - -/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the -/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. -public struct JSONEncoding: ParameterEncoding { - // MARK: Properties - - /// Returns a `JSONEncoding` instance with default writing options. - public static var `default`: JSONEncoding { return JSONEncoding() } - - /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. - public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } - - /// The options for writing the parameters as JSON data. - public let options: JSONSerialization.WritingOptions - - // MARK: Initialization - - /// Creates an instance using the specified `WritingOptions`. - /// - /// - Parameter options: `JSONSerialization.WritingOptions` to use. - public init(options: JSONSerialization.WritingOptions = []) { - self.options = options - } - - // MARK: Encoding - - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: parameters, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } - - /// Encodes any JSON compatible object into a `URLRequest`. - /// - /// - Parameters: - /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. - /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. - /// - /// - Returns: The encoded `URLRequest`. - /// - Throws: Any `Error` produced during encoding. - public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let jsonObject = jsonObject else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - -extension NSNumber { - fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Protector.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Protector.swift deleted file mode 100644 index 3e42a53..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Protector.swift +++ /dev/null @@ -1,167 +0,0 @@ -// -// Protector.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -// MARK: - - -/// An `os_unfair_lock` wrapper. -final class UnfairLock { - private let unfairLock: os_unfair_lock_t - - init() { - unfairLock = .allocate(capacity: 1) - unfairLock.initialize(to: os_unfair_lock()) - } - - deinit { - unfairLock.deinitialize(count: 1) - unfairLock.deallocate() - } - - private func lock() { - os_unfair_lock_lock(unfairLock) - } - - private func unlock() { - os_unfair_lock_unlock(unfairLock) - } - - /// Executes a closure returning a value while acquiring the lock. - /// - /// - Parameter closure: The closure to run. - /// - /// - Returns: The value the closure generated. - func around(_ closure: () -> T) -> T { - lock(); defer { unlock() } - return closure() - } - - /// Execute a closure while acquiring the lock. - /// - /// - Parameter closure: The closure to run. - func around(_ closure: () -> Void) { - lock(); defer { unlock() } - return closure() - } -} - -/// A thread-safe wrapper around a value. -final class Protector { - private let lock = UnfairLock() - private var value: T - - init(_ value: T) { - self.value = value - } - - /// The contained value. Unsafe for anything more than direct read or write. - var directValue: T { - get { return lock.around { value } } - set { lock.around { value = newValue } } - } - - /// Synchronously read or transform the contained value. - /// - /// - Parameter closure: The closure to execute. - /// - /// - Returns: The return value of the closure passed. - func read(_ closure: (T) -> U) -> U { - return lock.around { closure(self.value) } - } - - /// Synchronously modify the protected value. - /// - /// - Parameter closure: The closure to execute. - /// - /// - Returns: The modified value. - @discardableResult - func write(_ closure: (inout T) -> U) -> U { - return lock.around { closure(&self.value) } - } -} - -extension Protector where T: RangeReplaceableCollection { - /// Adds a new element to the end of this protected collection. - /// - /// - Parameter newElement: The `Element` to append. - func append(_ newElement: T.Element) { - write { (ward: inout T) in - ward.append(newElement) - } - } - - /// Adds the elements of a sequence to the end of this protected collection. - /// - /// - Parameter newElements: The `Sequence` to append. - func append(contentsOf newElements: S) where S.Element == T.Element { - write { (ward: inout T) in - ward.append(contentsOf: newElements) - } - } - - /// Add the elements of a collection to the end of the protected collection. - /// - /// - Parameter newElements: The `Collection` to append. - func append(contentsOf newElements: C) where C.Element == T.Element { - write { (ward: inout T) in - ward.append(contentsOf: newElements) - } - } -} - -extension Protector where T == Data? { - /// Adds the contents of a `Data` value to the end of the protected `Data`. - /// - /// - Parameter data: The `Data` to be appended. - func append(_ data: Data) { - write { (ward: inout T) in - ward?.append(data) - } - } -} - -extension Protector where T == Request.MutableState { - /// Attempts to transition to the passed `State`. - /// - /// - Parameter state: The `State` to attempt transition to. - /// - /// - Returns: Whether the transition occurred. - func attemptToTransitionTo(_ state: Request.State) -> Bool { - return lock.around { - guard value.state.canTransitionTo(state) else { return false } - - value.state = state - - return true - } - } - - /// Perform a closure while locked with the provided `Request.State`. - /// - /// - Parameter perform: The closure to perform while locked. - func withState(perform: (Request.State) -> Void) { - lock.around { perform(value.state) } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/RedirectHandler.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/RedirectHandler.swift deleted file mode 100644 index 5f35a92..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/RedirectHandler.swift +++ /dev/null @@ -1,95 +0,0 @@ -// -// RedirectHandler.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. -public protocol RedirectHandler { - /// Determines how the HTTP redirect response should be redirected to the new request. - /// - /// The `completion` closure should be passed one of three possible options: - /// - /// 1. The new request specified by the redirect (this is the most common use case). - /// 2. A modified version of the new request (you may want to route it somewhere else). - /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. - /// - /// - Parameters: - /// - task: The task whose request resulted in a redirect. - /// - request: The URL request object to the new location specified by the redirect response. - /// - response: The response containing the server's response to the original request. - /// - completion: The closure to execute containing the new request, a modified request, or `nil`. - func task(_ task: URLSessionTask, - willBeRedirectedTo request: URLRequest, - for response: HTTPURLResponse, - completion: @escaping (URLRequest?) -> Void) -} - -// MARK: - - -/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. -public struct Redirector { - /// Defines the behavior of the `Redirector` type. - public enum Behavior { - /// Follow the redirect as defined in the response. - case follow - /// Do not follow the redirect defined in the response. - case doNotFollow - /// Modify the redirect request defined in the response. - case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) - } - - /// Returns a `Redirector` with a `.follow` `Behavior`. - public static let follow = Redirector(behavior: .follow) - /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. - public static let doNotFollow = Redirector(behavior: .doNotFollow) - - /// The `Behavior` of the `Redirector`. - public let behavior: Behavior - - /// Creates a `Redirector` instance from the `Behavior`. - /// - /// - Parameter behavior: The `Behavior`. - public init(behavior: Behavior) { - self.behavior = behavior - } -} - -// MARK: - - -extension Redirector: RedirectHandler { - public func task(_ task: URLSessionTask, - willBeRedirectedTo request: URLRequest, - for response: HTTPURLResponse, - completion: @escaping (URLRequest?) -> Void) { - switch behavior { - case .follow: - completion(request) - case .doNotFollow: - completion(nil) - case let .modify(closure): - let request = closure(task, request, response) - completion(request) - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Request.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Request.swift deleted file mode 100644 index 6f98b37..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Request.swift +++ /dev/null @@ -1,1461 +0,0 @@ -// -// Request.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback -/// handling. -public class Request { - /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or - /// `cancel()` on the `Request`. - public enum State { - /// Initial state of the `Request`. - case initialized - /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on - /// them in this state. - case resumed - /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on - /// them in this state. - case suspended - /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on - /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition - /// to any other state. - case cancelled - /// `State` set when all response serialization completion closures have been cleared on the `Request` and - /// enqueued on their respective queues. - case finished - - /// Determines whether `self` can be transitioned to the provided `State`. - func canTransitionTo(_ state: State) -> Bool { - switch (self, state) { - case (.initialized, _): - return true - case (_, .initialized), (.cancelled, _), (.finished, _): - return false - case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): - return true - case (.suspended, .suspended), (.resumed, .resumed): - return false - case (_, .finished): - return true - } - } - } - - // MARK: - Initial State - - /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. - public let id: UUID - /// The serial queue for all internal async actions. - public let underlyingQueue: DispatchQueue - /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. - public let serializationQueue: DispatchQueue - /// `EventMonitor` used for event callbacks. - public let eventMonitor: EventMonitor? - /// The `Request`'s interceptor. - public let interceptor: RequestInterceptor? - /// The `Request`'s delegate. - public private(set) weak var delegate: RequestDelegate? - - // MARK: - Mutable State - - /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. - struct MutableState { - /// State of the `Request`. - var state: State = .initialized - /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. - var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? - /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. - var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? - /// `RedirectHandler` provided for to handle request redirection. - var redirectHandler: RedirectHandler? - /// `CachedResponseHandler` provided to handle response caching. - var cachedResponseHandler: CachedResponseHandler? - /// Closure called when the `Request` is able to create a cURL description of itself. - var cURLHandler: ((String) -> Void)? - /// Response serialization closures that handle response parsing. - var responseSerializers: [() -> Void] = [] - /// Response serialization completion closures executed once all response serializers are complete. - var responseSerializerCompletions: [() -> Void] = [] - /// Whether response serializer processing is finished. - var responseSerializerProcessingFinished = false - /// `URLCredential` used for authentication challenges. - var credential: URLCredential? - /// All `URLRequest`s created by Alamofire on behalf of the `Request`. - var requests: [URLRequest] = [] - /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. - var tasks: [URLSessionTask] = [] - /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond - /// exactly the the `tasks` created. - var metrics: [URLSessionTaskMetrics] = [] - /// Number of times any retriers provided retried the `Request`. - var retryCount = 0 - /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. - var error: AFError? - } - - /// Protected `MutableState` value that provides thread-safe access to state values. - fileprivate let protectedMutableState: Protector = Protector(MutableState()) - - /// `State` of the `Request`. - public var state: State { return protectedMutableState.directValue.state } - /// Returns whether `state` is `.initialized`. - public var isInitialized: Bool { return state == .initialized } - /// Returns whether `state is `.resumed`. - public var isResumed: Bool { return state == .resumed } - /// Returns whether `state` is `.suspended`. - public var isSuspended: Bool { return state == .suspended } - /// Returns whether `state` is `.cancelled`. - public var isCancelled: Bool { return state == .cancelled } - /// Returns whether `state` is `.finished`. - public var isFinished: Bool { return state == .finished } - - // MARK: Progress - - /// Closure type executed when monitoring the upload or download progress of a request. - public typealias ProgressHandler = (Progress) -> Void - - /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. - public let uploadProgress = Progress(totalUnitCount: 0) - /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. - public let downloadProgress = Progress(totalUnitCount: 0) - /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. - fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { - get { return protectedMutableState.directValue.uploadProgressHandler } - set { protectedMutableState.write { $0.uploadProgressHandler = newValue } } - } - - /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. - fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { - get { return protectedMutableState.directValue.downloadProgressHandler } - set { protectedMutableState.write { $0.downloadProgressHandler = newValue } } - } - - // MARK: Redirect Handling - - /// `RedirectHandler` set on the instance. - public private(set) var redirectHandler: RedirectHandler? { - get { return protectedMutableState.directValue.redirectHandler } - set { protectedMutableState.write { $0.redirectHandler = newValue } } - } - - // MARK: Cached Response Handling - - /// `CachedResponseHandler` set on the instance. - public private(set) var cachedResponseHandler: CachedResponseHandler? { - get { return protectedMutableState.directValue.cachedResponseHandler } - set { protectedMutableState.write { $0.cachedResponseHandler = newValue } } - } - - // MARK: URLCredential - - /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. - public private(set) var credential: URLCredential? { - get { return protectedMutableState.directValue.credential } - set { protectedMutableState.write { $0.credential = newValue } } - } - - // MARK: Validators - - /// `Validator` callback closures that store the validation calls enqueued. - fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([]) - - // MARK: URLRequests - - /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. - public var requests: [URLRequest] { return protectedMutableState.directValue.requests } - /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. - public var firstRequest: URLRequest? { return requests.first } - /// Last `URLRequest` created on behalf of the `Request`. - public var lastRequest: URLRequest? { return requests.last } - /// Current `URLRequest` created on behalf of the `Request`. - public var request: URLRequest? { return lastRequest } - - /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from - /// `requests` due to `URLSession` manipulation. - public var performedRequests: [URLRequest] { - return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } } - } - - // MARK: HTTPURLResponse - - /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the - /// last `URLSessionTask`. - public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse } - - // MARK: Tasks - - /// All `URLSessionTask`s created on behalf of the `Request`. - public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks } - /// First `URLSessionTask` created on behalf of the `Request`. - public var firstTask: URLSessionTask? { return tasks.first } - /// Last `URLSessionTask` crated on behalf of the `Request`. - public var lastTask: URLSessionTask? { return tasks.last } - /// Current `URLSessionTask` created on behalf of the `Request`. - public var task: URLSessionTask? { return lastTask } - - // MARK: Metrics - - /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. - public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics } - /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first } - /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last } - /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var metrics: URLSessionTaskMetrics? { return lastMetrics } - - // MARK: Retry Count - - /// Number of times the `Request` has been retried. - public var retryCount: Int { return protectedMutableState.directValue.retryCount } - - // MARK: Error - - /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. - public fileprivate(set) var error: AFError? { - get { return protectedMutableState.directValue.error } - set { protectedMutableState.write { $0.error = newValue } } - } - - /// Default initializer for the `Request` superclass. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate) { - self.id = id - self.underlyingQueue = underlyingQueue - self.serializationQueue = serializationQueue - self.eventMonitor = eventMonitor - self.interceptor = interceptor - self.delegate = delegate - } - - // MARK: - Internal Event API - - // All API must be called from underlyingQueue. - - /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, - /// the `URLRequest` will be adapted before being issued. - /// - /// - Parameter request: The `URLRequest` created. - func didCreateInitialURLRequest(_ request: URLRequest) { - protectedMutableState.write { $0.requests.append(request) } - - eventMonitor?.request(self, didCreateInitialURLRequest: request) - } - - /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. - /// - /// - Note: Triggers retry. - /// - /// - Parameter error: `AFError` thrown from the failed creation. - func didFailToCreateURLRequest(with error: AFError) { - self.error = error - - eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) - - callCURLHandlerIfNecessary() - - retryOrFinish(error: error) - } - - /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. - /// - /// - Parameters: - /// - initialRequest: The `URLRequest` that was adapted. - /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. - func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { - protectedMutableState.write { $0.requests.append(adaptedRequest) } - - eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) - } - - /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. - /// - /// - Note: Triggers retry. - /// - /// - Parameters: - /// - request: The `URLRequest` the adapter was called with. - /// - error: The `AFError` returned by the `RequestAdapter`. - func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { - self.error = error - - eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) - - callCURLHandlerIfNecessary() - - retryOrFinish(error: error) - } - - /// Final `URLRequest` has been created for the instance. - /// - /// - Parameter request: The `URLRequest` created. - func didCreateURLRequest(_ request: URLRequest) { - eventMonitor?.request(self, didCreateURLRequest: request) - - callCURLHandlerIfNecessary() - } - - /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. - private func callCURLHandlerIfNecessary() { - protectedMutableState.write { mutableState in - guard let cURLHandler = mutableState.cURLHandler else { return } - - self.underlyingQueue.async { cURLHandler(self.cURLDescription()) } - mutableState.cURLHandler = nil - } - } - - /// Called when a `URLSessionTask` is created on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` created. - func didCreateTask(_ task: URLSessionTask) { - protectedMutableState.write { $0.tasks.append(task) } - - eventMonitor?.request(self, didCreateTask: task) - } - - /// Called when resumption is completed. - func didResume() { - eventMonitor?.requestDidResume(self) - } - - /// Called when a `URLSessionTask` is resumed on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` resumed. - func didResumeTask(_ task: URLSessionTask) { - eventMonitor?.request(self, didResumeTask: task) - } - - /// Called when suspension is completed. - func didSuspend() { - eventMonitor?.requestDidSuspend(self) - } - - /// Called when a `URLSessionTask` is suspended on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` suspended. - func didSuspendTask(_ task: URLSessionTask) { - eventMonitor?.request(self, didSuspendTask: task) - } - - /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. - func didCancel() { - error = AFError.explicitlyCancelled - - eventMonitor?.requestDidCancel(self) - } - - /// Called when a `URLSessionTask` is cancelled on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` cancelled. - func didCancelTask(_ task: URLSessionTask) { - eventMonitor?.request(self, didCancelTask: task) - } - - /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. - /// - /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. - func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { - protectedMutableState.write { $0.metrics.append(metrics) } - - eventMonitor?.request(self, didGatherMetrics: metrics) - } - - /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. - /// - /// - Parameters: - /// - task: The `URLSessionTask` which failed. - /// - error: The early failure `AFError`. - func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { - self.error = error - - // Task will still complete, so didCompleteTask(_:with:) will handle retry. - eventMonitor?.request(self, didFailTask: task, earlyWithError: error) - } - - /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. - /// - /// - Note: Response validation is synchronously triggered in this step. - /// - /// - Parameters: - /// - task: The `URLSessionTask` which completed. - /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this - /// value is ignored. - func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { - self.error = self.error ?? error - protectedValidators.directValue.forEach { $0() } - - eventMonitor?.request(self, didCompleteTask: task, with: error) - - retryOrFinish(error: self.error) - } - - /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. - func prepareForRetry() { - protectedMutableState.write { $0.retryCount += 1 } - - reset() - - eventMonitor?.requestIsRetrying(self) - } - - /// Called to determine whether retry will be triggered for the particular error, or whether the instance should - /// call `finish()`. - /// - /// - Parameter error: The possible `AFError` which may trigger retry. - func retryOrFinish(error: AFError?) { - guard let error = error, let delegate = delegate else { finish(); return } - - delegate.retryResult(for: self, dueTo: error) { retryResult in - switch retryResult { - case .doNotRetry: - self.finish() - case let .doNotRetryWithError(retryError): - self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - - /// Finishes this `Request` and starts the response serializers. - /// - /// - Parameter error: The possible `Error` with which the instance will finish. - func finish(error: AFError? = nil) { - if let error = error { self.error = error } - - // Start response handlers - processNextResponseSerializer() - - eventMonitor?.requestDidFinish(self) - } - - /// Appends the response serialization closure to the instance. - /// - /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. - /// - /// - Parameter closure: The closure containing the response serialization call. - func appendResponseSerializer(_ closure: @escaping () -> Void) { - protectedMutableState.write { mutableState in - mutableState.responseSerializers.append(closure) - - if mutableState.state == .finished { - mutableState.state = .resumed - } - - if mutableState.responseSerializerProcessingFinished { - underlyingQueue.async { self.processNextResponseSerializer() } - } - - if mutableState.state.canTransitionTo(.resumed) { - underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } - } - } - } - - /// Returns the next response serializer closure to execute if there's one left. - /// - /// - Returns: The next response serialization closure, if there is one. - func nextResponseSerializer() -> (() -> Void)? { - var responseSerializer: (() -> Void)? - - protectedMutableState.write { mutableState in - let responseSerializerIndex = mutableState.responseSerializerCompletions.count - - if responseSerializerIndex < mutableState.responseSerializers.count { - responseSerializer = mutableState.responseSerializers[responseSerializerIndex] - } - } - - return responseSerializer - } - - /// Processes the next response serializer and calls all completions if response serialization is complete. - func processNextResponseSerializer() { - guard let responseSerializer = nextResponseSerializer() else { - // Execute all response serializer completions and clear them - var completions: [() -> Void] = [] - - protectedMutableState.write { mutableState in - completions = mutableState.responseSerializerCompletions - - // Clear out all response serializers and response serializer completions in mutable state since the - // request is complete. It's important to do this prior to calling the completion closures in case - // the completions call back into the request triggering a re-processing of the response serializers. - // An example of how this can happen is by calling cancel inside a response completion closure. - mutableState.responseSerializers.removeAll() - mutableState.responseSerializerCompletions.removeAll() - - if mutableState.state.canTransitionTo(.finished) { - mutableState.state = .finished - } - - mutableState.responseSerializerProcessingFinished = true - } - - completions.forEach { $0() } - - // Cleanup the request - cleanup() - - return - } - - serializationQueue.async { responseSerializer() } - } - - /// Notifies the `Request` that the response serializer is complete. - /// - /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers - /// are complete. - func responseSerializerDidComplete(completion: @escaping () -> Void) { - protectedMutableState.write { $0.responseSerializerCompletions.append(completion) } - processNextResponseSerializer() - } - - /// Resets all task and response serializer related state for retry. - func reset() { - error = nil - - uploadProgress.totalUnitCount = 0 - uploadProgress.completedUnitCount = 0 - downloadProgress.totalUnitCount = 0 - downloadProgress.completedUnitCount = 0 - - protectedMutableState.write { $0.responseSerializerCompletions = [] } - } - - /// Called when updating the upload progress. - /// - /// - Parameters: - /// - totalBytesSent: Total bytes sent so far. - /// - totalBytesExpectedToSend: Total bytes expected to send. - func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { - uploadProgress.totalUnitCount = totalBytesExpectedToSend - uploadProgress.completedUnitCount = totalBytesSent - - uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } - } - - /// Perform a closure on the current `state` while locked. - /// - /// - Parameter perform: The closure to perform. - func withState(perform: (State) -> Void) { - protectedMutableState.withState(perform: perform) - } - - // MARK: Task Creation - - /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. - /// - /// - Parameters: - /// - request: `URLRequest` to use to create the `URLSessionTask`. - /// - session: `URLSession` which creates the `URLSessionTask`. - /// - /// - Returns: The `URLSessionTask` created. - func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - fatalError("Subclasses must override.") - } - - // MARK: - Public API - - // These APIs are callable from any queue. - - // MARK: State - - /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. - /// - /// - Returns: The instance. - @discardableResult - public func cancel() -> Self { - protectedMutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.cancelled) else { return } - - mutableState.state = .cancelled - - underlyingQueue.async { self.didCancel() } - - guard let task = mutableState.tasks.last, task.state != .completed else { - underlyingQueue.async { self.finish() } - return - } - - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - underlyingQueue.async { self.didCancelTask(task) } - } - - return self - } - - /// Suspends the instance. - /// - /// - Returns: The instance. - @discardableResult - public func suspend() -> Self { - protectedMutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.suspended) else { return } - - mutableState.state = .suspended - - underlyingQueue.async { self.didSuspend() } - - guard let task = mutableState.tasks.last, task.state != .completed else { return } - - task.suspend() - underlyingQueue.async { self.didSuspendTask(task) } - } - - return self - } - - /// Resumes the instance. - /// - /// - Returns: The instance. - @discardableResult - public func resume() -> Self { - protectedMutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.resumed) else { return } - - mutableState.state = .resumed - - underlyingQueue.async { self.didResume() } - - guard let task = mutableState.tasks.last, task.state != .completed else { return } - - task.resume() - underlyingQueue.async { self.didResumeTask(task) } - } - - return self - } - - // MARK: - Closure API - - /// Associates a credential using the provided values with the instance. - /// - /// - Parameters: - /// - username: The username. - /// - password: The password. - /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. - /// - /// - Returns: The instance. - @discardableResult - public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { - let credential = URLCredential(user: username, password: password, persistence: persistence) - - return authenticate(with: credential) - } - - /// Associates the provided credential with the instance. - /// - /// - Parameter credential: The `URLCredential`. - /// - /// - Returns: The instance. - @discardableResult - public func authenticate(with credential: URLCredential) -> Self { - protectedMutableState.write { $0.credential = credential } - - return self - } - - /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. - /// - /// - Note: Only the last closure provided is used. - /// - /// - Parameters: - /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. - /// - closure: The closure to be executed periodically as data is read from the server. - /// - /// - Returns: The instance. - @discardableResult - public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { - protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) } - - return self - } - - /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. - /// - /// - Note: Only the last closure provided is used. - /// - /// - Parameters: - /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. - /// - closure: The closure to be executed periodically as data is sent to the server. - /// - /// - Returns: The instance. - @discardableResult - public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { - protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) } - - return self - } - - // MARK: Redirects - - /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. - /// - /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. - /// - /// - Parameter handler: The `RedirectHandler`. - /// - /// - Returns: The instance. - @discardableResult - public func redirect(using handler: RedirectHandler) -> Self { - protectedMutableState.write { mutableState in - precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") - mutableState.redirectHandler = handler - } - - return self - } - - // MARK: Cached Responses - - /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. - /// - /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. - /// - /// - Parameter handler: The `CachedResponseHandler`. - /// - /// - Returns: The instance. - @discardableResult - public func cacheResponse(using handler: CachedResponseHandler) -> Self { - protectedMutableState.write { mutableState in - precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") - mutableState.cachedResponseHandler = handler - } - - return self - } - - /// Sets a handler to be called when the cURL description of the request is available. - /// - /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. - /// - /// - Parameter handler: Closure to be called when the cURL description is available. - /// - /// - Returns: The instance. - @discardableResult - public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { - protectedMutableState.write { mutableState in - if mutableState.requests.last != nil { - underlyingQueue.async { handler(self.cURLDescription()) } - } else { - mutableState.cURLHandler = handler - } - } - - return self - } - - // MARK: Cleanup - - /// Final cleanup step executed when the instance finishes response serialization. - func cleanup() { - delegate?.cleanup(after: self) - // No-op: override in subclass - } -} - -// MARK: - Protocol Conformances - -extension Request: Equatable { - public static func ==(lhs: Request, rhs: Request) -> Bool { - return lhs.id == rhs.id - } -} - -extension Request: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(id) - } -} - -extension Request: CustomStringConvertible { - /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been - /// created, as well as the response status code, if a response has been received. - public var description: String { - guard let request = performedRequests.last ?? lastRequest, - let url = request.url, - let method = request.httpMethod else { return "No request created yet." } - - let requestDescription = "\(method) \(url.absoluteString)" - - return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription - } -} - -extension Request { - /// cURL representation of the instance. - /// - /// - Returns: The cURL equivalent of the instance. - public func cURLDescription() -> String { - guard - let request = lastRequest, - let url = request.url, - let host = url.host, - let method = request.httpMethod else { return "$ curl command could not be created" } - - var components = ["$ curl -v"] - - components.append("-X \(method)") - - if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { - let protectionSpace = URLProtectionSpace(host: host, - port: url.port ?? 0, - protocol: url.scheme, - realm: host, - authenticationMethod: NSURLAuthenticationMethodHTTPBasic) - - if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { - for credential in credentials { - guard let user = credential.user, let password = credential.password else { continue } - components.append("-u \(user):\(password)") - } - } else { - if let credential = credential, let user = credential.user, let password = credential.password { - components.append("-u \(user):\(password)") - } - } - } - - if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { - if - let cookieStorage = configuration.httpCookieStorage, - let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { - let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") - - components.append("-b \"\(allCookies)\"") - } - } - - var headers = HTTPHeaders() - - if let sessionHeaders = delegate?.sessionConfiguration.headers { - for header in sessionHeaders where header.name != "Cookie" { - headers[header.name] = header.value - } - } - - for header in request.headers where header.name != "Cookie" { - headers[header.name] = header.value - } - - for header in headers { - let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") - components.append("-H \"\(header.name): \(escapedValue)\"") - } - - if let httpBodyData = request.httpBody { - let httpBody = String(decoding: httpBodyData, as: UTF8.self) - var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") - escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") - - components.append("-d \"\(escapedBody)\"") - } - - components.append("\"\(url.absoluteString)\"") - - return components.joined(separator: " \\\n\t") - } -} - -/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. -public protocol RequestDelegate: AnyObject { - /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. - var sessionConfiguration: URLSessionConfiguration { get } - - /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. - var startImmediately: Bool { get } - - /// Notifies the delegate the `Request` has reached a point where it needs cleanup. - /// - /// - Parameter request: The `Request` to cleanup after. - func cleanup(after request: Request) - - /// Asynchronously ask the delegate whether a `Request` will be retried. - /// - /// - Parameters: - /// - request: `Request` which failed. - /// - error: `Error` which produced the failure. - /// - completion: Closure taking the `RetryResult` for evaluation. - func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) - - /// Asynchronously retry the `Request`. - /// - /// - Parameters: - /// - request: `Request` which will be retried. - /// - timeDelay: `TimeInterval` after which the retry will be triggered. - func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) -} - -// MARK: - Subclasses - -// MARK: - DataRequest - -/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. -public class DataRequest: Request { - /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. - public let convertible: URLRequestConvertible - /// `Data` read from the server so far. - public var data: Data? { return protectedData.directValue } - - /// Protected storage for the `Data` read by the instance. - private var protectedData: Protector = Protector(nil) - - /// Creates a `DataRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - convertible: URLRequestConvertible, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate) { - self.convertible = convertible - - super.init(id: id, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - override func reset() { - super.reset() - - protectedData.directValue = nil - } - - /// Called when `Data` is received by this instance. - /// - /// - Note: Also calls `updateDownloadProgress`. - /// - /// - Parameter data: The `Data` received. - func didReceive(data: Data) { - if self.data == nil { - protectedData.directValue = data - } else { - protectedData.append(data) - } - - updateDownloadProgress() - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - let copiedRequest = request - return session.dataTask(with: copiedRequest) - } - - /// Called to updated the `downloadProgress` of the instance. - func updateDownloadProgress() { - let totalBytesReceived = Int64(data?.count ?? 0) - let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - downloadProgress.totalUnitCount = totalBytesExpected - downloadProgress.completedUnitCount = totalBytesReceived - - downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } - } - - /// Validates the request, using the specified closure. - /// - /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter validation: `Validation` closure used to validate the response. - /// - /// - Returns: The instance. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validator: () -> Void = { [unowned self] in - guard self.error == nil, let response = self.response else { return } - - let result = validation(self.request, response, self.data) - - if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } - - self.eventMonitor?.request(self, - didValidateRequest: self.request, - response: response, - data: self.data, - withResult: result) - } - - protectedValidators.append(validator) - - return self - } -} - -// MARK: - DownloadRequest - -/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. -public class DownloadRequest: Request { - /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination - /// `URL`. - public struct Options: OptionSet { - /// Specifies that intermediate directories for the destination URL should be created. - public static let createIntermediateDirectories = Options(rawValue: 1 << 0) - /// Specifies that any previous file at the destination `URL` should be removed. - public static let removePreviousFile = Options(rawValue: 1 << 1) - - /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. - public let rawValue: Int - - public init(rawValue: Int) { - self.rawValue = rawValue - } - } - - // MARK: Destination - - /// A closure executed once a download request has successfully completed in order to determine where to move the - /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL - /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and - /// the options defining how the file should be moved. - public typealias Destination = (_ temporaryURL: URL, - _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) - - // MARK: Destination - - /// Creates a download file destination closure which uses the default file manager to move the temporary file to a - /// file URL in the first available directory with the specified search path directory and search path domain mask. - /// - /// - Parameters: - /// - directory: The search path directory. `.documentDirectory` by default. - /// - domain: The search path domain mask. `.userDomainMask` by default. - /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by - /// default. - /// - Returns: The `Destination` closure. - public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, - in domain: FileManager.SearchPathDomainMask = .userDomainMask, - options: Options = []) -> Destination { - return { temporaryURL, response in - let directoryURLs = FileManager.default.urls(for: directory, in: domain) - let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL - - return (url, options) - } - } - - /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends - /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files - /// with this destination must be additionally moved if they should survive the system reclamation of temporary - /// space. - static let defaultDestination: Destination = { url, _ in - let filename = "Alamofire_\(url.lastPathComponent)" - let destination = url.deletingLastPathComponent().appendingPathComponent(filename) - - return (destination, []) - } - - /// Type describing the source used to create the underlying `URLSessionDownloadTask`. - public enum Downloadable { - /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. - case request(URLRequestConvertible) - /// Download should be started from the associated resume `Data` value. - case resumeData(Data) - } - - // MARK: Mutable State - - /// Type containing all mutable state for `DownloadRequest` instances. - private struct DownloadRequestMutableState { - /// Possible resume `Data` produced when cancelling the instance. - var resumeData: Data? - /// `URL` to which `Data` is being downloaded. - var fileURL: URL? - } - - /// Protected mutable state specific to `DownloadRequest`. - private let protectedDownloadMutableState: Protector = Protector(DownloadRequestMutableState()) - - /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the - /// `download(resumingWith data:)` API. - /// - /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). - public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData } - /// If the download is successful, the `URL` where the file was downloaded. - public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL } - - // MARK: Initial State - - /// `Downloadable` value used for this instance. - public let downloadable: Downloadable - /// The `Destination` to which the downloaded file is moved. - let destination: Destination - - /// Creates a `DownloadRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` - /// - destination: `Destination` closure used to move the downloaded file to its final location. - init(id: UUID = UUID(), - downloadable: Downloadable, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate, - destination: @escaping Destination) { - self.downloadable = downloadable - self.destination = destination - - super.init(id: id, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - override func reset() { - super.reset() - - protectedDownloadMutableState.write { - $0.resumeData = nil - $0.fileURL = nil - } - } - - /// Called when a download has finished. - /// - /// - Parameters: - /// - task: `URLSessionTask` that finished the download. - /// - result: `Result` of the automatic move to `destination`. - func didFinishDownloading(using task: URLSessionTask, with result: Result) { - eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) - - switch result { - case let .success(url): protectedDownloadMutableState.write { $0.fileURL = url } - case let .failure(error): self.error = error - } - } - - /// Updates the `downloadProgress` using the provided values. - /// - /// - Parameters: - /// - bytesWritten: Total bytes written so far. - /// - totalBytesExpectedToWrite: Total bytes expected to write. - func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { - downloadProgress.totalUnitCount = totalBytesExpectedToWrite - downloadProgress.completedUnitCount += bytesWritten - - downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - return session.downloadTask(with: request) - } - - /// Creates a `URLSessionTask` from the provided resume data. - /// - /// - Parameters: - /// - data: `Data` used to resume the download. - /// - session: `URLSession` used to create the `URLSessionTask`. - /// - /// - Returns: The `URLSessionTask` created. - public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { - return session.downloadTask(withResumeData: data) - } - - /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. - /// - /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use - /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. - /// - /// - Returns: The instance. - @discardableResult - public override func cancel() -> Self { - return cancel(producingResumeData: false) - } - - /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be - /// resumed or suspended. - /// - /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if - /// available. - /// - /// - Returns: The instance. - @discardableResult - public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { - return cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) - } - - /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed - /// or suspended. - /// - /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` - /// property. - /// - /// - Parameter completionHandler: The completion handler that is called when the download has been successfully - /// cancelled. It is not guaranteed to be called on a particular queue, so you may - /// want use an appropriate queue to perform your work. - /// - /// - Returns: The instance. - @discardableResult - public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { - return cancel(optionallyProducingResumeData: completionHandler) - } - - /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, - /// cancellation is performed without producing resume data. - /// - /// - Parameter completionHandler: Optional resume data handler. - /// - /// - Returns: The instance. - private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { - protectedMutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.cancelled) else { return } - - mutableState.state = .cancelled - - underlyingQueue.async { self.didCancel() } - - guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { - underlyingQueue.async { self.finish() } - return - } - - if let completionHandler = completionHandler { - // Resume to ensure metrics are gathered. - task.resume() - task.cancel { resumeData in - self.protectedDownloadMutableState.write { $0.resumeData = resumeData } - self.underlyingQueue.async { self.didCancelTask(task) } - completionHandler(resumeData) - } - } else { - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - self.underlyingQueue.async { self.didCancelTask(task) } - } - } - - return self - } - - /// Validates the request, using the specified closure. - /// - /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter validation: `Validation` closure to validate the response. - /// - /// - Returns: The instance. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validator: () -> Void = { [unowned self] in - guard self.error == nil, let response = self.response else { return } - - let result = validation(self.request, response, self.fileURL) - - if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } - - self.eventMonitor?.request(self, - didValidateRequest: self.request, - response: response, - fileURL: self.fileURL, - withResult: result) - } - - protectedValidators.append(validator) - - return self - } -} - -// MARK: - UploadRequest - -/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. -public class UploadRequest: DataRequest { - /// Type describing the origin of the upload, whether `Data`, file, or stream. - public enum Uploadable { - /// Upload from the provided `Data` value. - case data(Data) - /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be - /// automatically removed once uploaded. - case file(URL, shouldRemove: Bool) - /// Upload from the provided `InputStream`. - case stream(InputStream) - } - - // MARK: Initial State - - /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. - public let upload: UploadableConvertible - - /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written - /// to disk. - public let fileManager: FileManager - - // MARK: Mutable State - - /// `Uploadable` value used by the instance. - public var uploadable: Uploadable? - - /// Creates an `UploadRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - convertible: UploadConvertible, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - fileManager: FileManager, - delegate: RequestDelegate) { - upload = convertible - self.fileManager = fileManager - - super.init(id: id, - convertible: convertible, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - /// Called when the `Uploadable` value has been created from the `UploadConvertible`. - /// - /// - Parameter uploadable: The `Uploadable` that was created. - func didCreateUploadable(_ uploadable: Uploadable) { - self.uploadable = uploadable - - eventMonitor?.request(self, didCreateUploadable: uploadable) - } - - /// Called when the `Uploadable` value could not be created. - /// - /// - Parameter error: `AFError` produced by the failure. - func didFailToCreateUploadable(with error: AFError) { - self.error = error - - eventMonitor?.request(self, didFailToCreateUploadableWithError: error) - - retryOrFinish(error: error) - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - guard let uploadable = uploadable else { - fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") - } - - switch uploadable { - case let .data(data): return session.uploadTask(with: request, from: data) - case let .file(url, _): return session.uploadTask(with: request, fromFile: url) - case .stream: return session.uploadTask(withStreamedRequest: request) - } - } - - /// Produces the `InputStream` from `uploadable`, if it can. - /// - /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. - /// - /// - Returns: The `InputStream`. - func inputStream() -> InputStream { - guard let uploadable = uploadable else { - fatalError("Attempting to access the input stream but the uploadable doesn't exist.") - } - - guard case let .stream(stream) = uploadable else { - fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") - } - - eventMonitor?.request(self, didProvideInputStream: stream) - - return stream - } - - public override func cleanup() { - defer { super.cleanup() } - - guard - let uploadable = self.uploadable, - case let .file(url, shouldRemove) = uploadable, - shouldRemove - else { return } - - try? fileManager.removeItem(at: url) - } -} - -/// A type that can produce an `UploadRequest.Uploadable` value. -public protocol UploadableConvertible { - /// Produces an `UploadRequest.Uploadable` value from the instance. - /// - /// - Returns: The `UploadRequest.Uploadable`. - /// - Throws: Any `Error` produced during creation. - func createUploadable() throws -> UploadRequest.Uploadable -} - -extension UploadRequest.Uploadable: UploadableConvertible { - public func createUploadable() throws -> UploadRequest.Uploadable { - return self - } -} - -/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. -public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestInterceptor.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestInterceptor.swift deleted file mode 100644 index 36590fc..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestInterceptor.swift +++ /dev/null @@ -1,243 +0,0 @@ -// -// RequestInterceptor.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. -public protocol RequestAdapter { - /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. - /// - /// - Parameters: - /// - urlRequest: The `URLRequest` to adapt. - /// - session: The `Session` that will execute the `URLRequest`. - /// - completion: The completion handler that must be called when adaptation is complete. - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) -} - -// MARK: - - -/// Outcome of determination whether retry is necessary. -public enum RetryResult { - /// Retry should be attempted immediately. - case retry - /// Retry should be attempted after the associated `TimeInterval`. - case retryWithDelay(TimeInterval) - /// Do not retry. - case doNotRetry - /// Do not retry due to the associated `AFError`. - case doNotRetryWithError(Error) -} - -extension RetryResult { - var retryRequired: Bool { - switch self { - case .retry, .retryWithDelay: return true - default: return false - } - } - - var delay: TimeInterval? { - switch self { - case let .retryWithDelay(delay): return delay - default: return nil - } - } - - var error: Error? { - guard case let .doNotRetryWithError(error) = self else { return nil } - return error - } -} - -/// A type that determines whether a request should be retried after being executed by the specified session manager -/// and encountering an error. -public protocol RequestRetrier { - /// Determines whether the `Request` should be retried by calling the `completion` closure. - /// - /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs - /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly - /// cleaned up after. - /// - /// - Parameters: - /// - request: `Request` that failed due to the provided `Error`. - /// - session: `Session` that produced the `Request`. - /// - error: `Error` encountered while executing the `Request`. - /// - completion: Completion closure to be executed when a retry decision has been determined. - func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) -} - -// MARK: - - -/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. -public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} - -extension RequestInterceptor { - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - completion(.success(urlRequest)) - } - - public func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - completion(.doNotRetry) - } -} - -/// `RequestAdapter` closure definition. -public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void -/// `RequestRetrier` closure definition. -public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void - -// MARK: - - -/// Closure-based `RequestAdapter`. -open class Adapter: RequestInterceptor { - private let adaptHandler: AdaptHandler - - /// Creates an instance using the provided closure. - /// - /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. - public init(_ adaptHandler: @escaping AdaptHandler) { - self.adaptHandler = adaptHandler - } - - open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptHandler(urlRequest, session, completion) - } -} - -// MARK: - - -/// Closure-based `RequestRetrier`. -open class Retrier: RequestInterceptor { - private let retryHandler: RetryHandler - - /// Creates an instance using the provided closure. - /// - /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. - public init(_ retryHandler: @escaping RetryHandler) { - self.retryHandler = retryHandler - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retryHandler(request, session, error, completion) - } -} - -// MARK: - - -/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. -open class Interceptor: RequestInterceptor { - /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. - public let adapters: [RequestAdapter] - /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. - public let retriers: [RequestRetrier] - - /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. - /// - /// - Parameters: - /// - adaptHandler: `AdaptHandler` closure to be used. - /// - retryHandler: `RetryHandler` closure to be used. - public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { - adapters = [Adapter(adaptHandler)] - retriers = [Retrier(retryHandler)] - } - - /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. - /// - /// - Parameters: - /// - adapter: `RequestAdapter` value to be used. - /// - retrier: `RequestRetrier` value to be used. - public init(adapter: RequestAdapter, retrier: RequestRetrier) { - adapters = [adapter] - retriers = [retrier] - } - - /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. - /// - /// - Parameters: - /// - adapters: `RequestAdapter` values to be used. - /// - retriers: `RequestRetrier` values to be used. - public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = []) { - self.adapters = adapters - self.retriers = retriers - } - - open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adapt(urlRequest, for: session, using: adapters, completion: completion) - } - - private func adapt(_ urlRequest: URLRequest, - for session: Session, - using adapters: [RequestAdapter], - completion: @escaping (Result) -> Void) { - var pendingAdapters = adapters - - guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } - - let adapter = pendingAdapters.removeFirst() - - adapter.adapt(urlRequest, for: session) { result in - switch result { - case let .success(urlRequest): - self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) - case .failure: - completion(result) - } - } - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retry(request, for: session, dueTo: error, using: retriers, completion: completion) - } - - private func retry(_ request: Request, - for session: Session, - dueTo error: Error, - using retriers: [RequestRetrier], - completion: @escaping (RetryResult) -> Void) { - var pendingRetriers = retriers - - guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } - - let retrier = pendingRetriers.removeFirst() - - retrier.retry(request, for: session, dueTo: error) { result in - switch result { - case .retry, .retryWithDelay, .doNotRetryWithError: - completion(result) - case .doNotRetry: - // Only continue to the next retrier if retry was not triggered and no error was encountered - self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) - } - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestTaskMap.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestTaskMap.swift deleted file mode 100644 index 8d4f33d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/RequestTaskMap.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// RequestTaskMap.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. -struct RequestTaskMap { - private var tasksToRequests: [URLSessionTask: Request] - private var requestsToTasks: [Request: URLSessionTask] - private var taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] - - var requests: [Request] { - return Array(tasksToRequests.values) - } - - init(tasksToRequests: [URLSessionTask: Request] = [:], - requestsToTasks: [Request: URLSessionTask] = [:], - taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { - self.tasksToRequests = tasksToRequests - self.requestsToTasks = requestsToTasks - self.taskEvents = taskEvents - } - - subscript(_ request: Request) -> URLSessionTask? { - get { return requestsToTasks[request] } - set { - guard let newValue = newValue else { - guard let task = requestsToTasks[request] else { - fatalError("RequestTaskMap consistency error: no task corresponding to request found.") - } - - requestsToTasks.removeValue(forKey: request) - tasksToRequests.removeValue(forKey: task) - taskEvents.removeValue(forKey: task) - - return - } - - requestsToTasks[request] = newValue - tasksToRequests[newValue] = request - taskEvents[newValue] = (completed: false, metricsGathered: false) - } - } - - subscript(_ task: URLSessionTask) -> Request? { - get { return tasksToRequests[task] } - set { - guard let newValue = newValue else { - guard let request = tasksToRequests[task] else { - fatalError("RequestTaskMap consistency error: no request corresponding to task found.") - } - - tasksToRequests.removeValue(forKey: task) - requestsToTasks.removeValue(forKey: request) - taskEvents.removeValue(forKey: task) - - return - } - - tasksToRequests[task] = newValue - requestsToTasks[newValue] = task - taskEvents[task] = (completed: false, metricsGathered: false) - } - } - - var count: Int { - precondition(tasksToRequests.count == requestsToTasks.count, - "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") - - return tasksToRequests.count - } - - var eventCount: Int { - precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") - - return taskEvents.count - } - - var isEmpty: Bool { - precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, - "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") - - return tasksToRequests.isEmpty - } - - var isEventsEmpty: Bool { - precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") - - return taskEvents.isEmpty - } - - mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) { - guard let events = taskEvents[task] else { - fatalError("RequestTaskMap consistency error: no events corresponding to task found.") - } - - switch (events.completed, events.metricsGathered) { - case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") - case (false, false): taskEvents[task] = (completed: false, metricsGathered: true) - case (true, false): self[task] = nil - } - } - - mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) { - guard let events = taskEvents[task] else { - fatalError("RequestTaskMap consistency error: no events corresponding to task found.") - } - - switch (events.completed, events.metricsGathered) { - case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") - case (false, false): taskEvents[task] = (completed: true, metricsGathered: false) - case (false, true): self[task] = nil - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Response.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Response.swift deleted file mode 100644 index 5874b28..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Response.swift +++ /dev/null @@ -1,399 +0,0 @@ -// -// Response.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFDataResponse = DataResponse -/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFDownloadResponse = DownloadResponse - -/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. -public struct DataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The final metrics of the response. - public let metrics: URLSessionTaskMetrics? - - /// The time taken to serialize the response. - public let serializationDuration: TimeInterval - - /// The result of response serialization. - public let result: Result - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Success? { return result.success } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Failure? { return result.failure } - - /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. - /// - /// - Parameters: - /// - request: The `URLRequest` sent to the server. - /// - response: The `HTTPURLResponse` from the server. - /// - data: The `Data` returned by the server. - /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. - /// - serializationDuration: The duration taken by serialization. - /// - result: The `Result` of response serialization. - public init(request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - metrics: URLSessionTaskMetrics?, - serializationDuration: TimeInterval, - result: Result) { - self.request = request - self.response = response - self.data = data - self.metrics = metrics - self.serializationDuration = serializationDuration - self.result = result - } -} - -// MARK: - - -extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return "\(result)" - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the server data, the duration of the network and serialization actions, and the response serialization - /// result. - public var debugDescription: String { - let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" - let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" - let responseDescription = response.map { response in - let sortedHeaders = response.headers.sorted() - - return """ - [Status Code]: \(response.statusCode) - [Headers]: - \(sortedHeaders) - """ - } ?? "nil" - let responseBody = data.map { String(decoding: $0, as: UTF8.self) } ?? "None" - let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" - - return """ - [Request]: \(requestDescription) - [Request Body]: \n\(requestBody) - [Response]: \n\(responseDescription) - [Response Body]: \n\(responseBody) - [Data]: \(data?.description ?? "None") - [Network Duration]: \(metricsDescription) - [Serialization Duration]: \(serializationDuration)s - [Result]: \(result) - """ - } -} - -// MARK: - - -extension DataResponse { - /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { - return DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.map(transform)) - } - - /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result - /// value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's - /// result is a failure, returns the same failure. - public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { - return DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMap(transform)) - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { - return DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.mapError(transform)) - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { - return DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMapError(transform)) - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a download request. -public struct DownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The final destination URL of the data returned from the server after it is moved. - public let fileURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The final metrics of the response. - public let metrics: URLSessionTaskMetrics? - - /// The time taken to serialize the response. - public let serializationDuration: TimeInterval - - /// The result of response serialization. - public let result: Result - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Success? { return result.success } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Failure? { return result.failure } - - /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. - /// - /// - Parameters: - /// - request: The `URLRequest` sent to the server. - /// - response: The `HTTPURLResponse` from the server. - /// - temporaryURL: The temporary destination `URL` of the data returned from the server. - /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved. - /// - resumeData: The resume `Data` generated if the request was cancelled. - /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. - /// - serializationDuration: The duration taken by serialization. - /// - result: The `Result` of response serialization. - public init(request: URLRequest?, - response: HTTPURLResponse?, - fileURL: URL?, - resumeData: Data?, - metrics: URLSessionTaskMetrics?, - serializationDuration: TimeInterval, - result: Result) { - self.request = request - self.response = response - self.fileURL = fileURL - self.resumeData = resumeData - self.metrics = metrics - self.serializationDuration = serializationDuration - self.result = result - } -} - -// MARK: - - -extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return "\(result)" - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization - /// actions, and the response serialization result. - public var debugDescription: String { - let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" - let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" - let responseDescription = response.map { response in - let sortedHeaders = response.headers.sorted() - - return """ - [Status Code]: \(response.statusCode) - [Headers]: - \(sortedHeaders) - """ - } ?? "nil" - let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" - let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" - - return """ - [Request]: \(requestDescription) - [Request Body]: \n\(requestBody) - [Response]: \n\(responseDescription) - [File URL]: \(fileURL?.path ?? "nil") - [ResumeData]: \(resumeDataDescription) - [Network Duration]: \(metricsDescription) - [Serialization Duration]: \(serializationDuration)s - [Result]: \(result) - """ - } -} - -// MARK: - - -extension DownloadResponse { - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { - return DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.map(transform)) - } - - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this - /// instance's result is a failure, returns the same failure. - public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { - return DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMap(transform)) - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { - return DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.mapError(transform)) - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { - return DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMapError(transform)) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/ResponseSerialization.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/ResponseSerialization.swift deleted file mode 100644 index fd235f2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/ResponseSerialization.swift +++ /dev/null @@ -1,779 +0,0 @@ -// -// ResponseSerialization.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -// MARK: Protocols - -/// The type to which all data response serializers must conform in order to serialize a response. -public protocol DataResponseSerializerProtocol { - /// The type of serialized object to be created. - associatedtype SerializedObject - - /// Serialize the response `Data` into the provided type.. - /// - /// - Parameters: - /// - request: `URLRequest` which was used to perform the request, if any. - /// - response: `HTTPURLResponse` received from the server, if any. - /// - data: `Data` returned from the server, if any. - /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. - /// - /// - Returns: The `SerializedObject`. - /// - Throws: Any `Error` produced during serialization. - func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject -} - -/// The type to which all download response serializers must conform in order to serialize a response. -public protocol DownloadResponseSerializerProtocol { - /// The type of serialized object to be created. - associatedtype SerializedObject - - /// Serialize the downloaded response `Data` from disk into the provided type.. - /// - /// - Parameters: - /// - request: `URLRequest` which was used to perform the request, if any. - /// - response: `HTTPURLResponse` received from the server, if any. - /// - fileURL: File `URL` to which the response data was downloaded. - /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. - /// - /// - Returns: The `SerializedObject`. - /// - Throws: Any `Error` produced during serialization. - func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject -} - -/// A serializer that can handle both data and download responses. -public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { - /// `DataPreprocessor` used to prepare incoming `Data` for serialization. - var dataPreprocessor: DataPreprocessor { get } - /// `HTTPMethod`s for which empty response bodies are considered appropriate. - var emptyRequestMethods: Set { get } - /// HTTP response codes for which empty response bodies are considered appropriate. - var emptyResponseCodes: Set { get } -} - -/// Type used to preprocess `Data` before it handled by a serializer. -public protocol DataPreprocessor { - /// Process `Data` before it's handled by a serializer. - /// - Parameter data: The raw `Data` to process. - func preprocess(_ data: Data) throws -> Data -} - -/// `DataPreprocessor` that returns passed `Data` without any transform. -public struct PassthroughPreprocessor: DataPreprocessor { - public init() {} - - public func preprocess(_ data: Data) throws -> Data { return data } -} - -/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. -public struct GoogleXSSIPreprocessor: DataPreprocessor { - public init() {} - - public func preprocess(_ data: Data) throws -> Data { - return (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data - } -} - -extension ResponseSerializer { - /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. - public static var defaultDataPreprocessor: DataPreprocessor { return PassthroughPreprocessor() } - /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. - public static var defaultEmptyRequestMethods: Set { return [.head] } - /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. - public static var defaultEmptyResponseCodes: Set { return [204, 205] } - - public var dataPreprocessor: DataPreprocessor { return Self.defaultDataPreprocessor } - public var emptyRequestMethods: Set { return Self.defaultEmptyRequestMethods } - public var emptyResponseCodes: Set { return Self.defaultEmptyResponseCodes } - - /// Determines whether the `request` allows empty response bodies, if `request` exists. - /// - /// - Parameter request: `URLRequest` to evaluate. - /// - /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. - public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { - return request.flatMap { $0.httpMethod } - .flatMap(HTTPMethod.init) - .map { emptyRequestMethods.contains($0) } - } - - /// Determines whether the `response` allows empty response bodies, if `response` exists`. - /// - /// - Parameter response: `HTTPURLResponse` to evaluate. - /// - /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. - public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { - return response.flatMap { $0.statusCode } - .map { emptyResponseCodes.contains($0) } - } - - /// Determines whether `request` and `response` allow empty response bodies. - /// - /// - Parameters: - /// - request: `URLRequest` to evaluate. - /// - response: `HTTPURLResponse` to evaluate. - /// - /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. - public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { - return (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) - } -} - -/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds -/// the data read from disk into the data response serializer. -public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { - func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { - guard error == nil else { throw error! } - - guard let fileURL = fileURL else { - throw AFError.responseSerializationFailed(reason: .inputFileNil) - } - - let data: Data - do { - data = try Data(contentsOf: fileURL) - } catch { - throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) - } - - do { - return try serialize(request: request, response: response, data: data, error: error) - } catch { - throw error - } - } -} - -// MARK: - Default - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let result = AFResult(value: self.data, error: self.error) - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: 0, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDataResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let start = CFAbsoluteTimeGetCurrent() - let result: AFResult = Result { - try responseSerializer.serialize(request: self.request, - response: self.response, - data: self.data, - error: self.error) - }.mapError { error in - error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) - } - - let end = CFAbsoluteTimeGetCurrent() - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - guard let serializerError = result.failure, let delegate = self.delegate else { - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - return - } - - delegate.retryResult(for: self, dueTo: serializerError) { retryResult in - var didComplete: (() -> Void)? - - defer { - if let didComplete = didComplete { - self.responseSerializerDidComplete { queue.async { didComplete() } } - } - } - - switch retryResult { - case .doNotRetry: - didComplete = { completionHandler(response) } - - case let .doNotRetryWithError(retryError): - let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - didComplete = { completionHandler(response) } - - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - } - - return self - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let result = AFResult(value: self.fileURL, error: self.error) - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: 0, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data - /// contained in the destination `URL`. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: T, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let start = CFAbsoluteTimeGetCurrent() - let result: AFResult = Result { - try responseSerializer.serializeDownload(request: self.request, - response: self.response, - fileURL: self.fileURL, - error: self.error) - }.mapError { error in - error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) - } - let end = CFAbsoluteTimeGetCurrent() - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - guard let serializerError = result.failure, let delegate = self.delegate else { - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - return - } - - delegate.retryResult(for: self, dueTo: serializerError) { retryResult in - var didComplete: (() -> Void)? - - defer { - if let didComplete = didComplete { - self.responseSerializerDidComplete { queue.async { didComplete() } } - } - } - - switch retryResult { - case .doNotRetry: - didComplete = { completionHandler(response) } - - case let .doNotRetryWithError(retryError): - let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - didComplete = { completionHandler(response) } - - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - } - - return self - } -} - -// MARK: - Data - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseData(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDataResponse) -> Void) - -> Self { - return response(queue: queue, - responseSerializer: DataResponseSerializer(), - completionHandler: completionHandler) - } -} - -/// A `ResponseSerializer` that performs minimal response checking and returns any response data as-is. By default, a -/// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for -/// empty responses (`204`, `205`), then an empty `Data` value is returned. -public final class DataResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates an instance using the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return Data() - } - - data = try dataPreprocessor.preprocess(data) - - return data - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseData(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - return response(queue: queue, - responseSerializer: DataResponseSerializer(), - completionHandler: completionHandler) - } -} - -// MARK: - String - -/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no -/// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), -/// then an empty `String` is returned. -public final class StringResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - /// Optional string encoding used to validate the response. - public let encoding: String.Encoding? - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates an instance with the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined - /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.encoding = encoding - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return "" - } - - data = try dataPreprocessor.preprocess(data) - - var convertedEncoding = encoding - - if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { - let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName) - let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet) - convertedEncoding = String.Encoding(rawValue: nsStringEncoding) - } - - let actualEncoding = convertedEncoding ?? .isoLatin1 - - guard let string = String(data: data, encoding: actualEncoding) else { - throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) - } - - return string - } -} - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from - /// the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseString(queue: DispatchQueue = .main, - encoding: String.Encoding? = nil, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - return response(queue: queue, - responseSerializer: StringResponseSerializer(encoding: encoding), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from - /// the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseString(queue: DispatchQueue = .main, - encoding: String.Encoding? = nil, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - return response(queue: queue, - responseSerializer: StringResponseSerializer(encoding: encoding), - completionHandler: completionHandler) - } -} - -// MARK: - JSON - -/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning -/// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses -/// (`204`, `205`), then an `NSNull` value is returned. -public final class JSONResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - /// `JSONSerialization.ReadingOptions` used when serializing a response. - public let options: JSONSerialization.ReadingOptions - - /// Creates an instance with the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - /// - options: The options to use. `.allowFragments` by default. - public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, - options: JSONSerialization.ReadingOptions = .allowFragments) { - self.dataPreprocessor = dataPreprocessor - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - self.options = options - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return NSNull() - } - - data = try dataPreprocessor.preprocess(data) - - do { - return try JSONSerialization.jsonObject(with: data, options: options) - } catch { - throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) - } - } -} - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - options: The JSON serialization reading options. `.allowFragments` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseJSON(queue: DispatchQueue = .main, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - return response(queue: queue, - responseSerializer: JSONResponseSerializer(options: options), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - options: The JSON serialization reading options. `.allowFragments` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseJSON(queue: DispatchQueue = .main, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - return response(queue: queue, - responseSerializer: JSONResponseSerializer(options: options), - completionHandler: completionHandler) - } -} - -// MARK: - Empty - -/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. -public protocol EmptyResponse { - /// Empty value for the conforming type. - /// - /// - Returns: Value of `Self` to use for empty values. - static func emptyValue() -> Self -} - -/// Type representing an empty response. Use `Empty.value` to get the static instance. -public struct Empty: Decodable { - /// Static `Empty` instance used for all `Empty` responses. - public static let value = Empty() -} - -extension Empty: EmptyResponse { - public static func emptyValue() -> Empty { - return value - } -} - -// MARK: - DataDecoder Protocol - -/// Any type which can decode `Data` into a `Decodable` type. -public protocol DataDecoder { - /// Decode `Data` into the provided type. - /// - /// - Parameters: - /// - type: The `Type` to be decoded. - /// - data: The `Data` to be decoded. - /// - /// - Returns: The decoded value of type `D`. - /// - Throws: Any error that occurs during decode. - func decode(_ type: D.Type, from data: Data) throws -> D -} - -/// `JSONDecoder` automatically conforms to `DataDecoder`. -extension JSONDecoder: DataDecoder {} - -// MARK: - Decodable - -/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to -/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data -/// is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), then -/// the `Empty.value` value is returned. -public final class DecodableResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - /// The `DataDecoder` instance used to decode responses. - public let decoder: DataDecoder - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates an instance using the values provided. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.decoder = decoder - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { - throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) - } - - return emptyValue - } - - data = try dataPreprocessor.preprocess(data) - - do { - return try decoder.decode(T.self, from: data) - } catch { - throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) - } - } -} - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseDecodable(of type: T.Type = T.self, - queue: DispatchQueue = .main, - decoder: DataDecoder = JSONDecoder(), - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - return response(queue: queue, - responseSerializer: DecodableResponseSerializer(decoder: decoder), - completionHandler: completionHandler) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Result+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Result+Alamofire.swift deleted file mode 100644 index 60b35f8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Result+Alamofire.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// Result+Alamofire.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFResult = Result - -// MARK: - Internal APIs - -extension Result { - /// Returns the associated value if the result is a success, `nil` otherwise. - var success: Success? { - guard case let .success(value) = self else { return nil } - return value - } - - /// Returns the associated error value if the result is a failure, `nil` otherwise. - var failure: Failure? { - guard case let .failure(error) = self else { return nil } - return error - } - - /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. - /// - /// - Parameters: - /// - value: A value. - /// - error: An `Error`. - init(value: Success, error: Failure?) { - if let error = error { - self = .failure(error) - } else { - self = .success(value) - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance. - /// - /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the - /// same failure. - func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { - switch self { - case let .success(value): - do { - return try .success(transform(value)) - } catch { - return .failure(error) - } - case let .failure(error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns - /// the same success. - func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { - switch self { - case let .failure(error): - do { - return try .failure(transform(error)) - } catch { - return .failure(error) - } - case let .success(value): - return .success(value) - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/RetryPolicy.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/RetryPolicy.swift deleted file mode 100644 index 7400718..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/RetryPolicy.swift +++ /dev/null @@ -1,363 +0,0 @@ -// -// RetryPolicy.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -/// as well as certain types of networking errors. -open class RetryPolicy: RequestInterceptor { - /// The default retry limit for retry policies. - public static let defaultRetryLimit: UInt = 2 - - /// The default exponential backoff base for retry policies (must be a minimum of 2). - public static let defaultExponentialBackoffBase: UInt = 2 - - /// The default exponential backoff scale for retry policies. - public static let defaultExponentialBackoffScale: Double = 0.5 - - /// The default HTTP methods to retry. - /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. - public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent - .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent - .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent - .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent - .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent - .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent - ] - - /// The default HTTP status codes to retry. - /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. - public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) - 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) - 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) - 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) - 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) - ] - - /// The default URL error codes to retry. - public static let defaultRetryableURLErrorCodes: Set = [// [Security] App Transport Security disallowed a connection because there is no secure network connection. - // - [Disabled] ATS settings do not change at runtime. - // .appTransportSecurityRequiresSecureConnection, - - // [System] An app or app extension attempted to connect to a background session that is already connected to a - // process. - // - [Enabled] The other process could release the background session. - .backgroundSessionInUseByAnotherProcess, - - // [System] The shared container identifier of the URL session configuration is needed but has not been set. - // - [Disabled] Cannot change at runtime. - // .backgroundSessionRequiresSharedContainer, - - // [System] The app is suspended or exits while a background data task is processing. - // - [Enabled] App can be foregrounded or launched to recover. - .backgroundSessionWasDisconnected, - - // [Network] The URL Loading system received bad data from the server. - // - [Enabled] Server could return valid data when retrying. - .badServerResponse, - - // [Resource] A malformed URL prevented a URL request from being initiated. - // - [Disabled] URL was most likely constructed incorrectly. - // .badURL, - - // [System] A connection was attempted while a phone call is active on a network that does not support - // simultaneous phone and data communication (EDGE or GPRS). - // - [Enabled] Phone call could be ended to allow request to recover. - .callIsActive, - - // [Client] An asynchronous load has been canceled. - // - [Disabled] Request was cancelled by the client. - // .cancelled, - - // [File System] A download task couldn’t close the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotCloseFile, - - // [Network] An attempt to connect to a host failed. - // - [Enabled] Server or DNS lookup could recover during retry. - .cannotConnectToHost, - - // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotCreateFile, - - // [Data] Content data received during a connection request had an unknown content encoding. - // - [Disabled] Server is unlikely to modify the content encoding during a retry. - // .cannotDecodeContentData, - - // [Data] Content data received during a connection request could not be decoded for a known content encoding. - // - [Disabled] Server is unlikely to modify the content encoding during a retry. - // .cannotDecodeRawData, - - // [Network] The host name for a URL could not be resolved. - // - [Enabled] Server or DNS lookup could recover during retry. - .cannotFindHost, - - // [Network] A request to load an item only from the cache could not be satisfied. - // - [Enabled] Cache could be populated during a retry. - .cannotLoadFromNetwork, - - // [File System] A download task was unable to move a downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotMoveFile, - - // [File System] A download task was unable to open the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotOpenFile, - - // [Data] A task could not parse a response. - // - [Disabled] Invalid response is unlikely to recover with retry. - // .cannotParseResponse, - - // [File System] A download task was unable to remove a downloaded file from disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotRemoveFile, - - // [File System] A download task was unable to write to the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotWriteToFile, - - // [Security] A client certificate was rejected. - // - [Disabled] Client certificate is unlikely to change with retry. - // .clientCertificateRejected, - - // [Security] A client certificate was required to authenticate an SSL connection during a request. - // - [Disabled] Client certificate is unlikely to be provided with retry. - // .clientCertificateRequired, - - // [Data] The length of the resource data exceeds the maximum allowed. - // - [Disabled] Resource will likely still exceed the length maximum on retry. - // .dataLengthExceedsMaximum, - - // [System] The cellular network disallowed a connection. - // - [Enabled] WiFi connection could be established during retry. - .dataNotAllowed, - - // [Network] The host address could not be found via DNS lookup. - // - [Enabled] DNS lookup could succeed during retry. - .dnsLookupFailed, - - // [Data] A download task failed to decode an encoded file during the download. - // - [Enabled] Server could correct the decoding issue with retry. - .downloadDecodingFailedMidStream, - - // [Data] A download task failed to decode an encoded file after downloading. - // - [Enabled] Server could correct the decoding issue with retry. - .downloadDecodingFailedToComplete, - - // [File System] A file does not exist. - // - [Disabled] File system error is unlikely to recover with retry. - // .fileDoesNotExist, - - // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, - // but a directory. - // - [Disabled] FTP directory is not likely to change to a file during a retry. - // .fileIsDirectory, - - // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been - // exceeded (currently 16). - // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. - // .httpTooManyRedirects, - - // [System] The attempted connection required activating a data context while roaming, but international roaming - // is disabled. - // - [Enabled] WiFi connection could be established during retry. - .internationalRoamingOff, - - // [Connectivity] A client or server connection was severed in the middle of an in-progress load. - // - [Enabled] A network connection could be established during retry. - .networkConnectionLost, - - // [File System] A resource couldn’t be read because of insufficient permissions. - // - [Disabled] Permissions are unlikely to be granted during retry. - // .noPermissionsToReadFile, - - // [Connectivity] A network resource was requested, but an internet connection has not been established and - // cannot be established automatically. - // - [Enabled] A network connection could be established during retry. - .notConnectedToInternet, - - // [Resource] A redirect was specified by way of server response code, but the server did not accompany this - // code with a redirect URL. - // - [Disabled] The redirect URL is unlikely to be supplied during a retry. - // .redirectToNonExistentLocation, - - // [Client] A body stream is needed but the client did not provide one. - // - [Disabled] The client will be unlikely to supply a body stream during retry. - // .requestBodyStreamExhausted, - - // [Resource] A requested resource couldn’t be retrieved. - // - [Disabled] The resource is unlikely to become available during the retry window. - // .resourceUnavailable, - - // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more - // specifically. - // - [Enabled] The secure connection could be established during a retry given the lack of specificity - // provided by the error. - .secureConnectionFailed, - - // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. - // - [Enabled] The server certificate could become valid within the retry window. - .serverCertificateHasBadDate, - - // [Security] A server certificate was not signed by any root server. - // - [Disabled] The server certificate is unlikely to change during the retry window. - // .serverCertificateHasUnknownRoot, - - // [Security] A server certificate is not yet valid. - // - [Enabled] The server certificate could become valid within the retry window. - .serverCertificateNotYetValid, - - // [Security] A server certificate was signed by a root server that isn’t trusted. - // - [Disabled] The server certificate is unlikely to become trusted within the retry window. - // .serverCertificateUntrusted, - - // [Network] An asynchronous operation timed out. - // - [Enabled] The request timed out for an unknown reason and should be retried. - .timedOut - - // [System] The URL Loading System encountered an error that it can’t interpret. - // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. - // .unknown, - - // [Resource] A properly formed URL couldn’t be handled by the framework. - // - [Disabled] The URL is unlikely to change during a retry. - // .unsupportedURL, - - // [Client] Authentication is required to access a resource. - // - [Disabled] The user authentication is unlikely to be provided by retrying. - // .userAuthenticationRequired, - - // [Client] An asynchronous request for authentication has been canceled by the user. - // - [Disabled] The user cancelled authentication and explicitly took action to not retry. - // .userCancelledAuthentication, - - // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection - // gracefully without sending any data. - // - [Disabled] The server is unlikely to provide data during the retry window. - // .zeroByteResource, - ] - - /// The total number of times the request is allowed to be retried. - public let retryLimit: UInt - - /// The base of the exponential backoff policy (should always be greater than or equal to 2). - public let exponentialBackoffBase: UInt - - /// The scale of the exponential backoff. - public let exponentialBackoffScale: Double - - /// The HTTP methods that are allowed to be retried. - public let retryableHTTPMethods: Set - - /// The HTTP status codes that are automatically retried by the policy. - public let retryableHTTPStatusCodes: Set - - /// The URL error codes that are automatically retried by the policy. - public let retryableURLErrorCodes: Set - - /// Creates an `ExponentialBackoffRetryPolicy` from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. - /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. - /// `RetryPolicy.defaultRetryableHTTPMethods` by default. - /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. - /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. - public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, - retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, - retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { - precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") - - self.retryLimit = retryLimit - self.exponentialBackoffBase = exponentialBackoffBase - self.exponentialBackoffScale = exponentialBackoffScale - self.retryableHTTPMethods = retryableHTTPMethods - self.retryableHTTPStatusCodes = retryableHTTPStatusCodes - self.retryableURLErrorCodes = retryableURLErrorCodes - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - if - request.retryCount < retryLimit, - let httpMethod = request.request?.method, - retryableHTTPMethods.contains(httpMethod), - shouldRetry(response: request.response, error: error) { - let timeDelay = pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale - completion(.retryWithDelay(timeDelay)) - } else { - completion(.doNotRetry) - } - } - - private func shouldRetry(response: HTTPURLResponse?, error: Error) -> Bool { - if let statusCode = response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { - return true - } else if let errorCode = (error as? URLError)?.code, retryableURLErrorCodes.contains(errorCode) { - return true - } - - return false - } -} - -// MARK: - - -/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more -/// information about retrying network connection lost errors, please refer to Apple's -/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). -open class ConnectionLostRetryPolicy: RetryPolicy { - /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. - /// `RetryPolicy.defaultRetryLimit` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. - /// `RetryPolicy.defaultExponentialBackoffBase` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. - /// `RetryPolicy.defaultExponentialBackoffScale` by default. - /// - retryableHTTPMethods: The idempotent http methods to retry. - /// `RetryPolicy.defaultRetryableHTTPMethods` by default. - public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { - super.init(retryLimit: retryLimit, - exponentialBackoffBase: exponentialBackoffBase, - exponentialBackoffScale: exponentialBackoffScale, - retryableHTTPMethods: retryableHTTPMethods, - retryableHTTPStatusCodes: [], - retryableURLErrorCodes: [.networkConnectionLost]) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/ServerTrustEvaluation.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/ServerTrustEvaluation.swift deleted file mode 100644 index e2a4d47..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/ServerTrustEvaluation.swift +++ /dev/null @@ -1,606 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. -open class ServerTrustManager { - /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. - public let allHostsMustBeEvaluated: Bool - - /// The dictionary of policies mapped to a particular host. - public let evaluators: [String: ServerTrustEvaluating] - - /// Initializes the `ServerTrustManager` instance with the given evaluators. - /// - /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This - /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key - /// pinning for host3 and disabling evaluation for host4. - /// - /// - Parameters: - /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` - /// by default. - /// - evaluators: A dictionary of evaluators mapped to hosts. - public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { - self.allHostsMustBeEvaluated = allHostsMustBeEvaluated - self.evaluators = evaluators - } - - /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. - /// - /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override - /// this method and implement more complex mapping implementations such as wildcards. - /// - /// - Parameter host: The host to use when searching for a matching policy. - /// - /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. - /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching - /// evaluators are found. - open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { - guard let evaluator = evaluators[host] else { - if allHostsMustBeEvaluated { - throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) - } - - return nil - } - - return evaluator - } -} - -/// A protocol describing the API used to evaluate server trusts. -public protocol ServerTrustEvaluating { -#if os(Linux) -// Implement this once Linux has API for evaluating server trusts. -#else - /// Evaluates the given `SecTrust` value for the given `host`. - /// - /// - Parameters: - /// - trust: The `SecTrust` value to evaluate. - /// - host: The host for which to evaluate the `SecTrust` value. - /// - /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. - func evaluate(_ trust: SecTrust, forHost host: String) throws -#endif -} - -// MARK: - Server Trust Evaluators - -/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -/// host provided by the challenge. Applications are encouraged to always validate the host in production environments -/// to guarantee the validity of the server's certificate chain. -public final class DefaultTrustEvaluator: ServerTrustEvaluating { - private let validateHost: Bool - - /// Creates a `DefaultTrustEvaluator`. - /// - /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. - public init(validateHost: Bool = true) { - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - if validateHost { - try trust.af.performValidation(forHost: host) - } - - try trust.af.performDefaultValidation(forHost: host) - } -} - -/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -/// environments to guarantee the validity of the server's certificate chain. -public final class RevocationTrustEvaluator: ServerTrustEvaluating { - /// Represents the options to be use when evaluating the status of a certificate. - /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). - public struct Options: OptionSet { - /// Perform revocation checking using the CRL (Certification Revocation List) method. - public static let crl = Options(rawValue: kSecRevocationCRLMethod) - /// Consult only locally cached replies; do not use network access. - public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) - /// Perform revocation checking using OCSP (Online Certificate Status Protocol). - public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) - /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. - public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) - /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a - /// "best attempt" basis, where failure to reach the server is not considered fatal. - public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) - /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the - /// certificate and the value of `preferCRL`. - public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) - - /// The raw value of the option. - public let rawValue: CFOptionFlags - - /// Creates an `Options` value with the given `CFOptionFlags`. - /// - /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. - public init(rawValue: CFOptionFlags) { - self.rawValue = rawValue - } - } - - private let performDefaultValidation: Bool - private let validateHost: Bool - private let options: Options - - /// Creates a `RevocationTrustEvaluator`. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition - /// to performing the default evaluation, even if `performDefaultValidation` is - /// `false`. `true` by default. - /// - options: The `Options` to use to check the revocation status of the certificate. `.any` - /// by default. - public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - self.options = options - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) - } else { - try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in - AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) - } - } - } -} - -/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate -/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate chain in production -/// environments. -public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { - private let certificates: [SecCertificate] - private let acceptSelfSignedCertificates: Bool - private let performDefaultValidation: Bool - private let validateHost: Bool - - /// Creates a `PinnedCertificatesTrustEvaluator`. - /// - /// - Parameters: - /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` - /// certificates in `Bundle.main` by default. - /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing - /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE - /// FALSE IN PRODUCTION! - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition - /// to performing the default evaluation, even if `performDefaultValidation` is - /// `false`. `true` by default. - public init(certificates: [SecCertificate] = Bundle.main.af.certificates, - acceptSelfSignedCertificates: Bool = false, - performDefaultValidation: Bool = true, - validateHost: Bool = true) { - self.certificates = certificates - self.acceptSelfSignedCertificates = acceptSelfSignedCertificates - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - guard !certificates.isEmpty else { - throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) - } - - if acceptSelfSignedCertificates { - try trust.af.setAnchorCertificates(certificates) - } - - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - let serverCertificatesData = Set(trust.af.certificateData) - let pinnedCertificatesData = Set(certificates.af.data) - let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) - if !pinnedCertificatesInServerData { - throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, - trust: trust, - pinnedCertificates: certificates, - serverCertificates: trust.af.certificates)) - } - } -} - -/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, -/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate chain in production -/// environments. -public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { - private let keys: [SecKey] - private let performDefaultValidation: Bool - private let validateHost: Bool - - /// Creates a `PublicKeysTrustEvaluator`. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all - /// certificates included in the main bundle. - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to - /// performing the default evaluation, even if `performDefaultValidation` is `false`. - /// `true` by default. - public init(keys: [SecKey] = Bundle.main.af.publicKeys, - performDefaultValidation: Bool = true, - validateHost: Bool = true) { - self.keys = keys - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - guard !keys.isEmpty else { - throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) - } - - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - let pinnedKeysInServerKeys: Bool = { - for serverPublicKey in trust.af.publicKeys { - for pinnedPublicKey in keys { - if serverPublicKey == pinnedPublicKey { - return true - } - } - } - return false - }() - - if !pinnedKeysInServerKeys { - throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, - trust: trust, - pinnedKeys: keys, - serverKeys: trust.af.publicKeys)) - } - } -} - -/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -/// evaluators consider it valid. -public final class CompositeTrustEvaluator: ServerTrustEvaluating { - private let evaluators: [ServerTrustEvaluating] - - /// Creates a `CompositeTrustEvaluator`. - /// - /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. - public init(evaluators: [ServerTrustEvaluating]) { - self.evaluators = evaluators - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - try evaluators.evaluate(trust, forHost: host) - } -} - -/// Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** -public final class DisabledEvaluator: ServerTrustEvaluating { - /// Creates an instance. - public init() {} - - public func evaluate(_ trust: SecTrust, forHost host: String) throws {} -} - -// MARK: - Extensions - -public extension Array where Element == ServerTrustEvaluating { -#if os(Linux) -// Add this same convenience method for Linux. -#else - /// Evaluates the given `SecTrust` value for the given `host`. - /// - /// - Parameters: - /// - trust: The `SecTrust` value to evaluate. - /// - host: The host for which to evaluate the `SecTrust` value. - /// - /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. - func evaluate(_ trust: SecTrust, forHost host: String) throws { - for evaluator in self { - try evaluator.evaluate(trust, forHost: host) - } - } -#endif -} - -extension Bundle: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType: Bundle { - /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. - var certificates: [SecCertificate] { - return paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in - guard - let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, - let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } - - return certificate - } - } - - /// Returns all public keys for the valid certificates in the bundle. - var publicKeys: [SecKey] { - return certificates.af.publicKeys - } - - /// Returns all pathnames for the resources identified by the provided file extensions. - /// - /// - Parameter types: The filename extensions locate. - /// - /// - Returns: All pathnames for the given filename extensions. - func paths(forResourcesOfTypes types: [String]) -> [String] { - return Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) - } -} - -extension SecTrust: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType == SecTrust { - /// Evaluates `self` after applying the `SecPolicy` value provided. - /// - /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. - /// - /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. - @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) - func evaluate(afterApplying policy: SecPolicy) throws { - try apply(policy: policy).af.evaluate() - } - - /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. - /// - /// - Parameters: - /// - policy: The `SecPolicy` used to evaluate `self`. - /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. - /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. - @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") - @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") - @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") - @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") - func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { - try apply(policy: policy).af.validate(errorProducer: errorProducer) - } - - /// Applies a `SecPolicy` to `self`, throwing if it fails. - /// - /// - Parameter policy: The `SecPolicy`. - /// - /// - Returns: `self`, with the policy applied. - /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. - func apply(policy: SecPolicy) throws -> SecTrust { - let status = SecTrustSetPolicies(type, policy) - - guard status.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, - policy: policy, - status: status)) - } - - return type - } - - /// Evaluate `self`, throwing an `Error` if evaluation fails. - /// - /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from - /// the underlying evaluation. - @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) - func evaluate() throws { - var error: CFError? - let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) - - if !evaluationSucceeded { - throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) - } - } - - /// Validate `self`, passing any failure values through `errorProducer`. - /// - /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an - /// `Error`. - /// - Throws: The `Error` produced by the `errorProducer` closure. - @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") - @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") - @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") - @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") - func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(type, &result) - - guard status.af.isSuccess && result.af.isSuccess else { - throw errorProducer(status, result) - } - } - - /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. - /// - /// - Parameter certificates: The `SecCertificate`s to add to the chain. - /// - Throws: Any error produced when applying the new certificate chain. - func setAnchorCertificates(_ certificates: [SecCertificate]) throws { - // Add additional anchor certificates. - let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) - guard status.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, - certificates: certificates)) - } - - // Reenable system anchor certificates. - let systemStatus = SecTrustSetAnchorCertificatesOnly(type, true) - guard systemStatus.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: systemStatus, - certificates: certificates)) - } - } - - /// The public keys contained in `self`. - var publicKeys: [SecKey] { - return certificates.af.publicKeys - } - - /// The `SecCertificate`s contained i `self`. - var certificates: [SecCertificate] { - return (0.. SecPolicy { - return SecPolicyCreateSSL(true, hostname as CFString) - } - - /// Creates a `SecPolicy` which checks the revocation of certificates. - /// - /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. - /// - /// - Returns: The `SecPolicy`. - /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` - /// if the policy cannot be created. - static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { - guard let policy = SecPolicyCreateRevocation(options.rawValue) else { - throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) - } - - return policy - } -} - -extension Array: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType == [SecCertificate] { - /// All `Data` values for the contained `SecCertificate`s. - var data: [Data] { - return type.map { SecCertificateCopyData($0) as Data } - } - - /// All public `SecKey` values for the contained `SecCertificate`s. - var publicKeys: [SecKey] { - return type.compactMap { $0.af.publicKey } - } -} - -extension SecCertificate: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType == SecCertificate { - /// The public key for `self`, if it can be extracted. - var publicKey: SecKey? { - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) - - guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } - - return SecTrustCopyPublicKey(createdTrust) - } -} - -extension OSStatus: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType == OSStatus { - /// Returns whether `self` is `errSecSuccess`. - var isSuccess: Bool { return type == errSecSuccess } -} - -extension SecTrustResultType: AlamofireExtended {} -public extension AlamofireExtension where ExtendedType == SecTrustResultType { - /// Returns whether `self is `.unspecified` or `.proceed`. - var isSuccess: Bool { - return (type == .unspecified || type == .proceed) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Session.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Session.swift deleted file mode 100644 index c73cfc1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Session.swift +++ /dev/null @@ -1,1039 +0,0 @@ -// -// Session.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common -/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response -/// cache handling. -open class Session { - /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. - public static let `default` = Session() - - /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's - /// `delegate` handles `URLSessionDelegate` callbacks. - public let session: URLSession - /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. - public let delegate: SessionDelegate - /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. - public let rootQueue: DispatchQueue - /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. - public let startRequestsImmediately: Bool - /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its - /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile - /// and test before introducing an additional queue. - public let requestQueue: DispatchQueue - /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this - /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined - /// to be a bottleneck. Always profile and test before introducing an additional queue. - public let serializationQueue: DispatchQueue - /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a - /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. - public let interceptor: RequestInterceptor? - /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. - public let serverTrustManager: ServerTrustManager? - /// `RedirectHandler` instance used to provide customization for request redirection. - public let redirectHandler: RedirectHandler? - /// `CachedResponseHandler` instance used to provide customization of cached response handling. - public let cachedResponseHandler: CachedResponseHandler? - /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. - public let eventMonitor: CompositeEventMonitor - /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. - public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] - - /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. - var requestTaskMap = RequestTaskMap() - /// Set of currently active `Request`s. - var activeRequests: Set = [] - - /// Creates a `Session` from a `URLSession` and other parameters. - /// - /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and - /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. - /// - /// - Parameters: - /// - session: Underlying `URLSession` for this instance. - /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` - /// interaction. - /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a - /// serial queue. - /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` - /// by default. If set to `false`, all `Request`s created must have `.resume()` called. - /// on them for them to start. - /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue - /// will use the `rootQueue` as its `target`. A separate queue can be used if it's - /// determined request creation is a bottleneck, but that should only be done after - /// careful testing and profiling. `nil` by default. - /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this - /// queue will use the `rootQueue` as its `target`. A separate queue can be used if - /// it's determined response serialization is a bottleneck, but that should only be - /// done after careful testing and profiling. `nil` by default. - /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` - /// by default. - /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` - /// by default. - /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by - /// default. - /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. - /// `nil` by default. - /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a - /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. - public init(session: URLSession, - delegate: SessionDelegate, - rootQueue: DispatchQueue, - startRequestsImmediately: Bool = true, - requestQueue: DispatchQueue? = nil, - serializationQueue: DispatchQueue? = nil, - interceptor: RequestInterceptor? = nil, - serverTrustManager: ServerTrustManager? = nil, - redirectHandler: RedirectHandler? = nil, - cachedResponseHandler: CachedResponseHandler? = nil, - eventMonitors: [EventMonitor] = []) { - precondition(session.configuration.identifier == nil, - "Alamofire does not support background URLSessionConfigurations.") - precondition(session.delegateQueue.underlyingQueue === rootQueue, - "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") - - self.session = session - self.delegate = delegate - self.rootQueue = rootQueue - self.startRequestsImmediately = startRequestsImmediately - self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) - self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) - self.interceptor = interceptor - self.serverTrustManager = serverTrustManager - self.redirectHandler = redirectHandler - self.cachedResponseHandler = cachedResponseHandler - eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) - delegate.eventMonitor = eventMonitor - delegate.stateProvider = self - } - - /// Creates a `Session` from a `URLSessionConfiguration`. - /// - /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its - /// `delegateQueue`, and is the recommended initializer for most uses. - /// - /// - Parameters: - /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes - /// to this value after being passed to this initializer will have no effect. - /// `URLSessionConfiguration.af.default` by default. - /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` - /// interaction. `SessionDelegate()` by default. - /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a - /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. - /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` - /// by default. If set to `false`, all `Request`s created must have `.resume()` called. - /// on them for them to start. - /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue - /// will use the `rootQueue` as its `target`. A separate queue can be used if it's - /// determined request creation is a bottleneck, but that should only be done after - /// careful testing and profiling. `nil` by default. - /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this - /// queue will use the `rootQueue` as its `target`. A separate queue can be used if - /// it's determined response serialization is a bottleneck, but that should only be - /// done after careful testing and profiling. `nil` by default. - /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` - /// by default. - /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` - /// by default. - /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by - /// default. - /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. - /// `nil` by default. - /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a - /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. - public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, - delegate: SessionDelegate = SessionDelegate(), - rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), - startRequestsImmediately: Bool = true, - requestQueue: DispatchQueue? = nil, - serializationQueue: DispatchQueue? = nil, - interceptor: RequestInterceptor? = nil, - serverTrustManager: ServerTrustManager? = nil, - redirectHandler: RedirectHandler? = nil, - cachedResponseHandler: CachedResponseHandler? = nil, - eventMonitors: [EventMonitor] = []) { - precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") - - let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue") - let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) - - self.init(session: session, - delegate: delegate, - rootQueue: rootQueue, - startRequestsImmediately: startRequestsImmediately, - requestQueue: requestQueue, - serializationQueue: serializationQueue, - interceptor: interceptor, - serverTrustManager: serverTrustManager, - redirectHandler: redirectHandler, - cachedResponseHandler: cachedResponseHandler, - eventMonitors: eventMonitors) - } - - deinit { - finishRequestsForDeinit() - session.invalidateAndCancel() - } - - // MARK: - Cancellation - - /// Cancel all active `Request`s, optionally calling a completion handler when complete. - /// - /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled - /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to - /// completion when cancelled. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. - /// - completion: Closure to be called when all `Request`s have been cancelled. - public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { - rootQueue.async { - self.activeRequests.forEach { $0.cancel() } - queue.async { completion?() } - } - } - - // MARK: - DataRequest - - struct RequestConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let parameters: Parameters? - let encoding: ParameterEncoding - let headers: HTTPHeaders? - - func asURLRequest() throws -> URLRequest { - let request = try URLRequest(url: url, method: method, headers: headers) - return try encoding.encode(request, with: parameters) - } - } - - /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default. - /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. - /// `URLEncoding.default` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil) -> DataRequest { - let convertible = RequestConvertible(url: convertible, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers) - - return request(convertible, interceptor: interceptor) - } - - struct RequestEncodableConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let parameters: Parameters? - let encoder: ParameterEncoder - let headers: HTTPHeaders? - - func asURLRequest() throws -> URLRequest { - let request = try URLRequest(url: url, method: method, headers: headers) - - return try parameters.map { try encoder.encode($0, into: request) } ?? request - } - } - - /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. - /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. - /// `URLEncodedFormParameterEncoder.default` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil) -> DataRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers) - - return request(convertible, interceptor: interceptor) - } - - /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { - let request = DataRequest(convertible: convertible, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self) - - perform(request) - - return request - } - - // MARK: - DownloadRequest - - /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and - /// `Destination`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default. - /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. Defaults - /// to `URLEncoding.default`. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let convertible = RequestConvertible(url: convertible, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers) - - return download(convertible, interceptor: interceptor, to: destination) - } - - /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and - /// a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. - /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. Defaults - /// to `URLEncodedFormParameterEncoder.default`. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers) - - return download(convertible, interceptor: interceptor, to: destination) - } - - /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. - /// - /// - Parameters: - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let request = DownloadRequest(downloadable: .request(convertible), - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self, - destination: destination ?? DownloadRequest.defaultDestination) - - perform(request) - - return request - } - - /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as - /// well as a `RequestInterceptor`, and a `Destination`. - /// - /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by - /// Alamofire. The file will not be deleted until the system purges the temporary files. - /// - /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), - /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` - /// generation logic where the data is written incorrectly and will always fail to resume the download. For more - /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). - /// - /// - Parameters: - /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(resumingWith data: Data, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let request = DownloadRequest(downloadable: .resumeData(data), - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self, - destination: destination ?? DownloadRequest.defaultDestination) - - perform(request) - - return request - } - - // MARK: - UploadRequest - - struct ParameterlessRequestConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let headers: HTTPHeaders? - - func asURLRequest() throws -> URLRequest { - return try URLRequest(url: url, method: method, headers: headers) - } - } - - struct Upload: UploadConvertible { - let request: URLRequestConvertible - let uploadable: UploadableConvertible - - func createUploadable() throws -> UploadRequest.Uploadable { - return try uploadable.createUploadable() - } - - func asURLRequest() throws -> URLRequest { - return try request.asURLRequest() - } - } - - // MARK: Data - - /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ data: Data, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) - - return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ data: Data, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: File - - /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided - /// components and `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ fileURL: URL, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) - - return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ fileURL: URL, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ stream: InputStream, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) - - return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ stream: InputStream, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - return upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: MultipartFormData - - /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided - /// `URLRequest` components and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) - - let formData = MultipartFormData(fileManager: fileManager) - multipartFormData(formData) - - return upload(multipartFormData: formData, - with: convertible, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` - /// value, and a `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let formData = MultipartFormData(fileManager: fileManager) - multipartFormData(formData) - - return upload(multipartFormData: formData, - with: request, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components - /// and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: MultipartFormData, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) - - let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil, - encodingMemoryThreshold: encodingMemoryThreshold, - request: convertible, - multipartFormData: multipartFormData) - - return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` - /// value and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: MultipartFormData, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil, - encodingMemoryThreshold: encodingMemoryThreshold, - request: request, - multipartFormData: multipartFormData) - - return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: - Internal API - - // MARK: Uploadable - - func upload(_ uploadable: UploadRequest.Uploadable, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor?, - fileManager: FileManager) -> UploadRequest { - let uploadable = Upload(request: convertible, uploadable: uploadable) - - return upload(uploadable, interceptor: interceptor, fileManager: fileManager) - } - - func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { - let request = UploadRequest(convertible: upload, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - fileManager: fileManager, - delegate: self) - - perform(request) - - return request - } - - // MARK: Perform - - /// Perform `Request`. - /// - /// - Note: Called during retry. - /// - /// - Parameter request: The `Request` to perform. - func perform(_ request: Request) { - switch request { - case let r as DataRequest: perform(r) - case let r as UploadRequest: perform(r) - case let r as DownloadRequest: perform(r) - default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") - } - } - - func perform(_ request: DataRequest) { - requestQueue.async { - guard !request.isCancelled else { return } - - self.activeRequests.insert(request) - - self.performSetupOperations(for: request, convertible: request.convertible) - } - } - - func perform(_ request: UploadRequest) { - requestQueue.async { - guard !request.isCancelled else { return } - - self.activeRequests.insert(request) - - do { - let uploadable = try request.upload.createUploadable() - self.rootQueue.async { request.didCreateUploadable(uploadable) } - - self.performSetupOperations(for: request, convertible: request.convertible) - } catch { - self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } - } - } - } - - func perform(_ request: DownloadRequest) { - requestQueue.async { - guard !request.isCancelled else { return } - - self.activeRequests.insert(request) - - switch request.downloadable { - case let .request(convertible): - self.performSetupOperations(for: request, convertible: convertible) - case let .resumeData(resumeData): - self.rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } - } - } - } - - func performSetupOperations(for request: Request, convertible: URLRequestConvertible) { - let initialRequest: URLRequest - - do { - initialRequest = try convertible.asURLRequest() - try initialRequest.validate() - } catch { - rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } - return - } - - rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } - - guard !request.isCancelled else { return } - - guard let adapter = adapter(for: request) else { - rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } - return - } - - adapter.adapt(initialRequest, for: self) { result in - do { - let adaptedRequest = try result.get() - try adaptedRequest.validate() - - self.rootQueue.async { - request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) - self.didCreateURLRequest(adaptedRequest, for: request) - } - } catch { - self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } - } - } - } - - // MARK: - Task Handling - - func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { - request.didCreateURLRequest(urlRequest) - - guard !request.isCancelled else { return } - - let task = request.task(for: urlRequest, using: session) - requestTaskMap[request] = task - request.didCreateTask(task) - - updateStatesForTask(task, request: request) - } - - func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { - guard !request.isCancelled else { return } - - let task = request.task(forResumeData: data, using: session) - requestTaskMap[request] = task - request.didCreateTask(task) - - updateStatesForTask(task, request: request) - } - - func updateStatesForTask(_ task: URLSessionTask, request: Request) { - request.withState { state in - switch state { - case .initialized, .finished: - // Do nothing. - break - case .resumed: - task.resume() - rootQueue.async { request.didResumeTask(task) } - case .suspended: - task.suspend() - rootQueue.async { request.didSuspendTask(task) } - case .cancelled: - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - rootQueue.async { request.didCancelTask(task) } - } - } - } - - // MARK: - Adapters and Retriers - - func adapter(for request: Request) -> RequestAdapter? { - if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { - return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) - } else { - return request.interceptor ?? interceptor - } - } - - func retrier(for request: Request) -> RequestRetrier? { - if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { - return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) - } else { - return request.interceptor ?? interceptor - } - } - - // MARK: - Invalidation - - func finishRequestsForDeinit() { - requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionDeinitialized) } - } -} - -// MARK: - RequestDelegate - -extension Session: RequestDelegate { - public var sessionConfiguration: URLSessionConfiguration { - return session.configuration - } - - public var startImmediately: Bool { return startRequestsImmediately } - - public func cleanup(after request: Request) { - activeRequests.remove(request) - } - - public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { - guard let retrier = retrier(for: request) else { - rootQueue.async { completion(.doNotRetry) } - return - } - - retrier.retry(request, for: self, dueTo: error) { retryResult in - self.rootQueue.async { - guard let retryResultError = retryResult.error else { completion(retryResult); return } - - let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) - completion(.doNotRetryWithError(retryError)) - } - } - } - - public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { - rootQueue.async { - let retry: () -> Void = { - guard !request.isCancelled else { return } - - request.prepareForRetry() - self.perform(request) - } - - if let retryDelay = timeDelay { - self.rootQueue.after(retryDelay) { retry() } - } else { - retry() - } - } - } -} - -// MARK: - SessionStateProvider - -extension Session: SessionStateProvider { - func request(for task: URLSessionTask) -> Request? { - return requestTaskMap[task] - } - - func didGatherMetricsForTask(_ task: URLSessionTask) { - requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) - } - - func didCompleteTask(_ task: URLSessionTask) { - requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) - } - - func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { - return requestTaskMap[task]?.credential ?? - session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) - } - - func cancelRequestsForSessionInvalidation(with error: Error?) { - requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/SessionDelegate.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/SessionDelegate.swift deleted file mode 100644 index 7103d8f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/SessionDelegate.swift +++ /dev/null @@ -1,305 +0,0 @@ -// -// SessionDelegate.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. -open class SessionDelegate: NSObject { - private let fileManager: FileManager - - weak var stateProvider: SessionStateProvider? - var eventMonitor: EventMonitor? - - /// Creates an instance from the given `FileManager`. - /// - /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. - /// `.default` by default. - public init(fileManager: FileManager = .default) { - self.fileManager = fileManager - } -} - -/// Type which provides various `Session` state values. -protocol SessionStateProvider: AnyObject { - var serverTrustManager: ServerTrustManager? { get } - var redirectHandler: RedirectHandler? { get } - var cachedResponseHandler: CachedResponseHandler? { get } - - func request(for task: URLSessionTask) -> Request? - func didGatherMetricsForTask(_ task: URLSessionTask) - func didCompleteTask(_ task: URLSessionTask) - func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? - func cancelRequestsForSessionInvalidation(with error: Error?) -} - -// MARK: URLSessionDelegate - -extension SessionDelegate: URLSessionDelegate { - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) - - stateProvider?.cancelRequestsForSessionInvalidation(with: error) - } -} - -// MARK: URLSessionTaskDelegate - -extension SessionDelegate: URLSessionTaskDelegate { - /// Result of a `URLAuthenticationChallenge` evaluation. - typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - eventMonitor?.urlSession(session, task: task, didReceive: challenge) - - let evaluation: ChallengeEvaluation - switch challenge.protectionSpace.authenticationMethod { - case NSURLAuthenticationMethodServerTrust: - evaluation = attemptServerTrustAuthentication(with: challenge) - case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate: - evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) - // case NSURLAuthenticationMethodClientCertificate: - // Alamofire doesn't currently support client certificate validation. - default: - evaluation = (.performDefaultHandling, nil, nil) - } - - if let error = evaluation.error { - stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) - } - - completionHandler(evaluation.disposition, evaluation.credential) - } - - /// Evaluates the server trust `URLAuthenticationChallenge` received. - /// - /// - Parameter challenge: The `URLAuthenticationChallenge`. - /// - /// - Returns: The `ChallengeEvaluation`. - func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { - let host = challenge.protectionSpace.host - - guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, - let trust = challenge.protectionSpace.serverTrust - else { - return (.performDefaultHandling, nil, nil) - } - - do { - guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { - return (.performDefaultHandling, nil, nil) - } - - try evaluator.evaluate(trust, forHost: host) - - return (.useCredential, URLCredential(trust: trust), nil) - } catch { - return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) - } - } - - /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. - /// - /// - Parameters: - /// - challenge: The `URLAuthenticationChallenge`. - /// - task: The `URLSessionTask` which received the challenge. - /// - /// - Returns: The `ChallengeEvaluation`. - func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, - belongingTo task: URLSessionTask) -> ChallengeEvaluation { - guard challenge.previousFailureCount == 0 else { - return (.rejectProtectionSpace, nil, nil) - } - - guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { - return (.performDefaultHandling, nil, nil) - } - - return (.useCredential, credential, nil) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - eventMonitor?.urlSession(session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - - stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) - - guard let request = stateProvider?.request(for: task) as? UploadRequest else { - fatalError("needNewBodyStream for request that isn't UploadRequest.") - } - - completionHandler(request.inputStream()) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) - - if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { - redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) - } else { - completionHandler(request) - } - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) - - stateProvider?.request(for: task)?.didGatherMetrics(metrics) - - stateProvider?.didGatherMetricsForTask(task) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) - - stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) - - stateProvider?.didCompleteTask(task) - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) - } -} - -// MARK: URLSessionDataDelegate - -extension SessionDelegate: URLSessionDataDelegate { - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) - - guard let request = stateProvider?.request(for: dataTask) as? DataRequest else { - fatalError("dataTask received data for incorrect Request subclass: \(String(describing: stateProvider?.request(for: dataTask)))") - } - - request.didReceive(data: data) - } - - open func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) - - if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { - handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) - } else { - completionHandler(proposedResponse) - } - } -} - -// MARK: URLSessionDownloadDelegate - -extension SessionDelegate: URLSessionDownloadDelegate { - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - eventMonitor?.urlSession(session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes) - - guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else { - fatalError("No DownloadRequest found for downloadTask: \(downloadTask)") - } - - downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, - totalBytesExpectedToWrite: expectedTotalBytes) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - eventMonitor?.urlSession(session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - - guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else { - fatalError("No DownloadRequest found for downloadTask: \(downloadTask)") - } - - downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - } - - open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { - eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) - - guard let request = stateProvider?.request(for: downloadTask) as? DownloadRequest else { - fatalError("Download finished but either no request found or request wasn't DownloadRequest") - } - - guard let response = request.response else { - fatalError("URLSessionDownloadTask finished downloading with no response.") - } - - let (destination, options) = (request.destination)(location, response) - - eventMonitor?.request(request, didCreateDestinationURL: destination) - - do { - if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { - try fileManager.removeItem(at: destination) - } - - if options.contains(.createIntermediateDirectories) { - let directory = destination.deletingLastPathComponent() - try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) - } - - try fileManager.moveItem(at: location, to: destination) - - request.didFinishDownloading(using: downloadTask, with: .success(destination)) - } catch { - request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination))) - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift deleted file mode 100644 index 9ac00ef..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLConvertible+URLRequestConvertible.swift +++ /dev/null @@ -1,105 +0,0 @@ -// -// URLConvertible+URLRequestConvertible.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct -/// `URLRequests`. -public protocol URLConvertible { - /// Returns a `URL` from the conforming instance or throws. - /// - /// - Returns: The `URL` created from the instance. - /// - Throws: Any error thrown while creating the `URL`. - func asURL() throws -> URL -} - -extension String: URLConvertible { - /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. - /// - /// - Returns: The `URL` initialized with `self`. - /// - Throws: An `AFError.invalidURL` instance. - public func asURL() throws -> URL { - guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } - - return url - } -} - -extension URL: URLConvertible { - /// Returns `self`. - public func asURL() throws -> URL { return self } -} - -extension URLComponents: URLConvertible { - /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. - /// - /// - Returns: The `URL` from the `url` property. - /// - Throws: An `AFError.invalidURL` instance. - public func asURL() throws -> URL { - guard let url = url else { throw AFError.invalidURL(url: self) } - - return url - } -} - -// MARK: - - -/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. -public protocol URLRequestConvertible { - /// Returns a `URLRequest` or throws if an `Error` was encountered. - /// - /// - Returns: A `URLRequest`. - /// - Throws: Any error thrown while constructing the `URLRequest`. - func asURLRequest() throws -> URLRequest -} - -extension URLRequestConvertible { - /// The `URLRequest` returned by discarding any `Error` encountered. - public var urlRequest: URLRequest? { return try? asURLRequest() } -} - -extension URLRequest: URLRequestConvertible { - /// Returns `self`. - public func asURLRequest() throws -> URLRequest { return self } -} - -// MARK: - - -extension URLRequest { - /// Creates an instance with the specified `url`, `method`, and `headers`. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. - public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { - let url = try url.asURL() - - self.init(url: url) - - httpMethod = method.rawValue - allHTTPHeaderFields = headers?.dictionary - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLEncodedFormEncoder.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/URLEncodedFormEncoder.swift deleted file mode 100644 index 86f520f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLEncodedFormEncoder.swift +++ /dev/null @@ -1,973 +0,0 @@ -// -// URLEncodedFormEncoder.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// An object that encodes instances into URL-encoded query strings. -/// -/// There is no published specification for how to encode collection types. By default, the convention of appending -/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for -/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the -/// square brackets appended to array keys. -/// -/// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode -/// `true` as 1 and `false` as 0. -/// -/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` -/// strategy is used, which formats dates from their structure. -/// -/// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (`%20`), -/// while older encodings may expect spaces to be replaced with `+`. -/// -/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. -public final class URLEncodedFormEncoder { - /// Encoding to use for `Array` values. - public enum ArrayEncoding { - /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. - case brackets - /// No brackets are appended to the key and the key is encoded as is. - case noBrackets - - /// Encodes the key according to the encoding. - /// - /// - Parameter key: The `key` to encode. - /// - Returns: The encoded key. - func encode(_ key: String) -> String { - switch self { - case .brackets: return "\(key)[]" - case .noBrackets: return key - } - } - } - - /// Encoding to use for `Bool` values. - public enum BoolEncoding { - /// Encodes `true` as `1`, `false` as `0`. - case numeric - /// Encodes `true` as "true", `false` as "false". This is the default encoding. - case literal - - /// Encodes the given `Bool` as a `String`. - /// - /// - Parameter value: The `Bool` to encode. - /// - /// - Returns: The encoded `String`. - func encode(_ value: Bool) -> String { - switch self { - case .numeric: return value ? "1" : "0" - case .literal: return value ? "true" : "false" - } - } - } - - /// Encoding to use for `Data` values. - public enum DataEncoding { - /// Defers encoding to the `Data` type. - case deferredToData - /// Encodes `Data` as a Base64-encoded string. This is the default encoding. - case base64 - /// Encode the `Data` as a custom value encoded by the given closure. - case custom((Data) throws -> String) - - /// Encodes `Data` according to the encoding. - /// - /// - Parameter data: The `Data` to encode. - /// - /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its - /// `Encodable` implementation. - func encode(_ data: Data) throws -> String? { - switch self { - case .deferredToData: return nil - case .base64: return data.base64EncodedString() - case let .custom(encoding): return try encoding(data) - } - } - } - - /// Encoding to use for `Date` values. - public enum DateEncoding { - /// ISO8601 and RFC3339 formatter. - private static let iso8601Formatter: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = .withInternetDateTime - return formatter - }() - - /// Defers encoding to the `Date` type. This is the default encoding. - case deferredToDate - /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. - case secondsSince1970 - /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. - case millisecondsSince1970 - /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. - case iso8601 - /// Encodes `Date`s using the given `DateFormatter`. - case formatted(DateFormatter) - /// Encodes `Date`s using the given closure. - case custom((Date) throws -> String) - - /// Encodes the date according to the encoding. - /// - /// - Parameter date: The `Date` to encode. - /// - /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its - /// `Encodable` implementation. - func encode(_ date: Date) throws -> String? { - switch self { - case .deferredToDate: - return nil - case .secondsSince1970: - return String(date.timeIntervalSince1970) - case .millisecondsSince1970: - return String(date.timeIntervalSince1970 * 1000.0) - case .iso8601: - return DateEncoding.iso8601Formatter.string(from: date) - case let .formatted(formatter): - return formatter.string(from: date) - case let .custom(closure): - return try closure(date) - } - } - } - - /// Encoding to use for keys. - /// - /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) - /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). - public enum KeyEncoding { - /// Use the keys specified by each type. This is the default encoding. - case useDefaultKeys - /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. - /// - /// Capital characters are determined by testing membership in - /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` - /// (Unicode General Categories Lu and Lt). - /// The conversion to lower case uses `Locale.system`, also known as - /// the ICU "root" locale. This means the result is consistent - /// regardless of the current user's locale and language preferences. - /// - /// Converting from camel case to snake case: - /// 1. Splits words at the boundary of lower-case to upper-case - /// 2. Inserts `_` between words - /// 3. Lowercases the entire string - /// 4. Preserves starting and ending `_`. - /// - /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. - /// - /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. - case convertToSnakeCase - /// Same as convertToSnakeCase, but using `-` instead of `_`. - /// For example `oneTwoThree` becomes `one-two-three`. - case convertToKebabCase - /// Capitalize the first letter only. - /// For example `oneTwoThree` becomes `OneTwoThree`. - case capitalized - /// Uppercase all letters. - /// For example `oneTwoThree` becomes `ONETWOTHREE`. - case uppercased - /// Lowercase all letters. - /// For example `oneTwoThree` becomes `onetwothree`. - case lowercased - /// A custom encoding using the provided closure. - case custom((String) -> String) - - func encode(_ key: String) -> String { - switch self { - case .useDefaultKeys: return key - case .convertToSnakeCase: return convertToSnakeCase(key) - case .convertToKebabCase: return convertToKebabCase(key) - case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) - case .uppercased: return key.uppercased() - case .lowercased: return key.lowercased() - case let .custom(encoding): return encoding(key) - } - } - - private func convertToSnakeCase(_ key: String) -> String { - return convert(key, usingSeparator: "_") - } - - private func convertToKebabCase(_ key: String) -> String { - return convert(key, usingSeparator: "-") - } - - private func convert(_ key: String, usingSeparator separator: String) -> String { - guard !key.isEmpty else { return key } - - var words: [Range] = [] - // The general idea of this algorithm is to split words on - // transition from lower to upper case, then on transition of >1 - // upper case characters to lowercase - // - // myProperty -> my_property - // myURLProperty -> my_url_property - // - // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. - var wordStart = key.startIndex - var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before the lower case character. - let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) - words.append(upperCaseRange.lowerBound.. String { - switch self { - case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") - case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") - } - } - } - - /// `URLEncodedFormEncoder` error. - public enum Error: Swift.Error { - /// An invalid root object was created by the encoder. Only keyed values are valid. - case invalidRootObject(String) - - var localizedDescription: String { - switch self { - case let .invalidRootObject(object): - return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." - } - } - } - - /// Whether or not to sort the encoded key value pairs. - /// - /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, - /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to - /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. - public let alphabetizeKeyValuePairs: Bool - /// The `ArrayEncoding` to use. - public let arrayEncoding: ArrayEncoding - /// The `BoolEncoding` to use. - public let boolEncoding: BoolEncoding - /// THe `DataEncoding` to use. - public let dataEncoding: DataEncoding - /// The `DateEncoding` to use. - public let dateEncoding: DateEncoding - /// The `KeyEncoding` to use. - public let keyEncoding: KeyEncoding - /// The `SpaceEncoding` to use. - public let spaceEncoding: SpaceEncoding - /// The `CharacterSet` of allowed (non-escaped) characters. - public var allowedCharacters: CharacterSet - - /// Creates an instance from the supplied parameters. - /// - /// - Parameters: - /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. - /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. - /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. - /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. - /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. - /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. - /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. - /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by - /// default. - public init(alphabetizeKeyValuePairs: Bool = true, - arrayEncoding: ArrayEncoding = .brackets, - boolEncoding: BoolEncoding = .numeric, - dataEncoding: DataEncoding = .base64, - dateEncoding: DateEncoding = .deferredToDate, - keyEncoding: KeyEncoding = .useDefaultKeys, - spaceEncoding: SpaceEncoding = .percentEscaped, - allowedCharacters: CharacterSet = .afURLQueryAllowed) { - self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.keyEncoding = keyEncoding - self.spaceEncoding = spaceEncoding - self.allowedCharacters = allowedCharacters - } - - func encode(_ value: Encodable) throws -> URLEncodedFormComponent { - let context = URLEncodedFormContext(.object([])) - let encoder = _URLEncodedFormEncoder(context: context, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - try value.encode(to: encoder) - - return context.component - } - - /// Encodes the `value` as a URL form encoded `String`. - /// - /// - Parameter value: The `Encodable` value.` - /// - /// - Returns: The encoded `String`. - /// - Throws: An `Error` or `EncodingError` instance if encoding fails. - public func encode(_ value: Encodable) throws -> String { - let component: URLEncodedFormComponent = try encode(value) - - guard case let .object(object) = component else { - throw Error.invalidRootObject("\(component)") - } - - let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, - arrayEncoding: arrayEncoding, - keyEncoding: keyEncoding, - spaceEncoding: spaceEncoding, - allowedCharacters: allowedCharacters) - let query = serializer.serialize(object) - - return query - } - - /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the - /// `.utf8` data. - /// - /// - Parameter value: The `Encodable` value. - /// - /// - Returns: The encoded `Data`. - /// - /// - Throws: An `Error` or `EncodingError` instance if encoding fails. - public func encode(_ value: Encodable) throws -> Data { - let string: String = try encode(value) - - return Data(string.utf8) - } -} - -final class _URLEncodedFormEncoder { - var codingPath: [CodingKey] - // Returns an empty dictionary, as this encoder doesn't support userInfo. - var userInfo: [CodingUserInfoKey: Any] { return [:] } - - let context: URLEncodedFormContext - - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - - public init(context: URLEncodedFormContext, - codingPath: [CodingKey] = [], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - } -} - -extension _URLEncodedFormEncoder: Encoder { - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - return KeyedEncodingContainer(container) - } - - func unkeyedContainer() -> UnkeyedEncodingContainer { - return _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } - - func singleValueContainer() -> SingleValueEncodingContainer { - return _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } -} - -final class URLEncodedFormContext { - var component: URLEncodedFormComponent - - init(_ component: URLEncodedFormComponent) { - self.component = component - } -} - -enum URLEncodedFormComponent { - typealias Object = [(key: String, value: URLEncodedFormComponent)] - - case string(String) - case array([URLEncodedFormComponent]) - case object(Object) - - /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. - var array: [URLEncodedFormComponent]? { - switch self { - case let .array(array): return array - default: return nil - } - } - - /// Converts self to an `Object` or returns `nil` if not convertible. - var object: Object? { - switch self { - case let .object(object): return object - default: return nil - } - } - - /// Sets self to the supplied value at a given path. - /// - /// data.set(to: "hello", at: ["path", "to", "value"]) - /// - /// - parameters: - /// - value: Value of `Self` to set at the supplied path. - /// - path: `CodingKey` path to update with the supplied value. - public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { - set(&self, to: value, at: path) - } - - /// Recursive backing method to `set(to:at:)`. - private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { - guard path.count >= 1 else { - context = value - return - } - - let end = path[0] - var child: URLEncodedFormComponent - switch path.count { - case 1: - child = value - case 2...: - if let index = end.intValue { - let array = context.array ?? [] - if array.count > index { - child = array[index] - } else { - child = .array([]) - } - set(&child, to: value, at: Array(path[1...])) - } else { - child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) - set(&child, to: value, at: Array(path[1...])) - } - default: fatalError("Unreachable") - } - - if let index = end.intValue { - if var array = context.array { - if array.count > index { - array[index] = child - } else { - array.append(child) - } - context = .array(array) - } else { - context = .array([child]) - } - } else { - if var object = context.object { - if let index = object.firstIndex(where: { $0.key == end.stringValue }) { - object[index] = (key: end.stringValue, value: child) - } else { - object.append((key: end.stringValue, value: child)) - } - context = .object(object) - } else { - context = .object([(key: end.stringValue, value: child)]) - } - } - } -} - -struct AnyCodingKey: CodingKey, Hashable { - let stringValue: String - let intValue: Int? - - init?(stringValue: String) { - self.stringValue = stringValue - intValue = nil - } - - init?(intValue: Int) { - stringValue = "\(intValue)" - self.intValue = intValue - } - - init(_ base: Key) where Key: CodingKey { - if let intValue = base.intValue { - self.init(intValue: intValue)! - } else { - self.init(stringValue: base.stringValue)! - } - } -} - -extension _URLEncodedFormEncoder { - final class KeyedContainer where Key: CodingKey { - var codingPath: [CodingKey] - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - } - - private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { - return codingPath + [key] - } - } -} - -extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { - func encodeNil(forKey key: Key) throws { - let context = EncodingError.Context(codingPath: codingPath, - debugDescription: "URLEncodedFormEncoder cannot encode nil values.") - throw EncodingError.invalidValue("\(key): nil", context) - } - - func encode(_ value: T, forKey key: Key) throws where T: Encodable { - var container = nestedSingleValueEncoder(for: key) - try container.encode(value) - } - - func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { - let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - - return container - } - - func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { - let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - - return container - } - - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - - return KeyedEncodingContainer(container) - } - - func superEncoder() -> Encoder { - return _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } - - func superEncoder(forKey key: Key) -> Encoder { - return _URLEncodedFormEncoder(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } -} - -extension _URLEncodedFormEncoder { - final class SingleValueContainer { - var codingPath: [CodingKey] - - private var canEncodeNewValue = true - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - } - - private func checkCanEncode(value: Any?) throws { - guard canEncodeNewValue else { - let context = EncodingError.Context(codingPath: codingPath, - debugDescription: "Attempt to encode value through single value container when previously value already encoded.") - throw EncodingError.invalidValue(value as Any, context) - } - } - } -} - -extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { - func encodeNil() throws { - try checkCanEncode(value: nil) - defer { canEncodeNewValue = false } - - let context = EncodingError.Context(codingPath: codingPath, - debugDescription: "URLEncodedFormEncoder cannot encode nil values.") - throw EncodingError.invalidValue("nil", context) - } - - func encode(_ value: Bool) throws { - try encode(value, as: String(boolEncoding.encode(value))) - } - - func encode(_ value: String) throws { - try encode(value, as: value) - } - - func encode(_ value: Double) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Float) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int8) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int16) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int32) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int64) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt8) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt16) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt32) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt64) throws { - try encode(value, as: String(value)) - } - - private func encode(_ value: T, as string: String) throws where T: Encodable { - try checkCanEncode(value: value) - defer { canEncodeNewValue = false } - - context.component.set(to: .string(string), at: codingPath) - } - - func encode(_ value: T) throws where T: Encodable { - switch value { - case let date as Date: - guard let string = try dateEncoding.encode(date) else { - try attemptToEncode(value) - return - } - - try encode(value, as: string) - case let data as Data: - guard let string = try dataEncoding.encode(data) else { - try attemptToEncode(value) - return - } - - try encode(value, as: string) - default: - try attemptToEncode(value) - } - } - - private func attemptToEncode(_ value: T) throws where T: Encodable { - try checkCanEncode(value: value) - defer { canEncodeNewValue = false } - - let encoder = _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - try value.encode(to: encoder) - } -} - -extension _URLEncodedFormEncoder { - final class UnkeyedContainer { - var codingPath: [CodingKey] - - var count = 0 - var nestedCodingPath: [CodingKey] { - return codingPath + [AnyCodingKey(intValue: count)!] - } - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - } - } -} - -extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { - func encodeNil() throws { - let context = EncodingError.Context(codingPath: codingPath, - debugDescription: "URLEncodedFormEncoder cannot encode nil values.") - throw EncodingError.invalidValue("nil", context) - } - - func encode(_ value: T) throws where T: Encodable { - var container = nestedSingleValueContainer() - try container.encode(value) - } - - func nestedSingleValueContainer() -> SingleValueEncodingContainer { - defer { count += 1 } - - return _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } - - func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { - defer { count += 1 } - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - - return KeyedEncodingContainer(container) - } - - func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { - defer { count += 1 } - - return _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } - - func superEncoder() -> Encoder { - defer { count += 1 } - - return _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding) - } -} - -final class URLEncodedFormSerializer { - private let alphabetizeKeyValuePairs: Bool - private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding - private let keyEncoding: URLEncodedFormEncoder.KeyEncoding - private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding - private let allowedCharacters: CharacterSet - - init(alphabetizeKeyValuePairs: Bool, - arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, - keyEncoding: URLEncodedFormEncoder.KeyEncoding, - spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, - allowedCharacters: CharacterSet) { - self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs - self.arrayEncoding = arrayEncoding - self.keyEncoding = keyEncoding - self.spaceEncoding = spaceEncoding - self.allowedCharacters = allowedCharacters - } - - func serialize(_ object: URLEncodedFormComponent.Object) -> String { - var output: [String] = [] - for (key, component) in object { - let value = serialize(component, forKey: key) - output.append(value) - } - output = alphabetizeKeyValuePairs ? output.sorted() : output - - return output.joinedWithAmpersands() - } - - func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { - switch component { - case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" - case let .array(array): return serialize(array, forKey: key) - case let .object(object): return serialize(object, forKey: key) - } - } - - func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { - var segments: [String] = object.map { subKey, value in - let keyPath = "[\(subKey)]" - return serialize(value, forKey: key + keyPath) - } - segments = alphabetizeKeyValuePairs ? segments.sorted() : segments - - return segments.joinedWithAmpersands() - } - - func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { - var segments: [String] = array.map { component in - let keyPath = arrayEncoding.encode(key) - return serialize(component, forKey: keyPath) - } - segments = alphabetizeKeyValuePairs ? segments.sorted() : segments - - return segments.joinedWithAmpersands() - } - - func escape(_ query: String) -> String { - var allowedCharactersWithSpace = allowedCharacters - allowedCharactersWithSpace.insert(charactersIn: " ") - let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query - let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) - - return spaceEncodedQuery - } -} - -extension Array where Element == String { - func joinedWithAmpersands() -> String { - return joined(separator: "&") - } -} - -public extension CharacterSet { - /// Creates a CharacterSet from RFC 3986 allowed characters. - /// - /// RFC 3986 states that the following characters are "reserved" characters. - /// - /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - /// - /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - /// should be percent-escaped in the query string. - static let afURLQueryAllowed: CharacterSet = { - let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 - let subDelimitersToEncode = "!$&'()*+,;=" - let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - - return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) - }() -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLRequest+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/URLRequest+Alamofire.swift deleted file mode 100644 index b198fe0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLRequest+Alamofire.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// URLRequest+Alamofire.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -public extension URLRequest { - /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. - var method: HTTPMethod? { - get { return httpMethod.flatMap(HTTPMethod.init) } - set { httpMethod = newValue?.rawValue } - } - - func validate() throws { - if method == .get, let bodyData = httpBody { - throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift deleted file mode 100644 index de3e290..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/URLSessionConfiguration+Alamofire.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// URLSessionConfiguration+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension URLSessionConfiguration: AlamofireExtended {} -extension AlamofireExtension where ExtendedType: URLSessionConfiguration { - /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default - /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. - public static var `default`: URLSessionConfiguration { - let configuration = URLSessionConfiguration.default - configuration.headers = .default - - return configuration - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Source/Validation.swift b/Lesson12/Carthage/Checkouts/Alamofire/Source/Validation.swift deleted file mode 100644 index 1f702b9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Source/Validation.swift +++ /dev/null @@ -1,247 +0,0 @@ -// -// Validation.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Request { - // MARK: Helper Types - - fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason - - /// Used to represent whether a validation succeeded or failed. - public typealias ValidationResult = Result - - fileprivate struct MIMEType { - let type: String - let subtype: String - - var isWildcard: Bool { return type == "*" && subtype == "*" } - - init?(_ string: String) { - let components: [String] = { - let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) - let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] - - return split.components(separatedBy: "/") - }() - - if let type = components.first, let subtype = components.last { - self.type = type - self.subtype = subtype - } else { - return nil - } - } - - func matches(_ mime: MIMEType) -> Bool { - switch (type, subtype) { - case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): - return true - default: - return false - } - } - } - - // MARK: Properties - - fileprivate var acceptableStatusCodes: Range { return 200..<300 } - - fileprivate var acceptableContentTypes: [String] { - if let accept = request?.value(forHTTPHeaderField: "Accept") { - return accept.components(separatedBy: ",") - } - - return ["*/*"] - } - - // MARK: Status Code - - fileprivate func validate(statusCode acceptableStatusCodes: S, - response: HTTPURLResponse) - -> ValidationResult - where S.Iterator.Element == Int { - if acceptableStatusCodes.contains(response.statusCode) { - return .success(Void()) - } else { - let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) - return .failure(AFError.responseValidationFailed(reason: reason)) - } - } - - // MARK: Content Type - - fileprivate func validate(contentType acceptableContentTypes: S, - response: HTTPURLResponse, - data: Data?) - -> ValidationResult - where S.Iterator.Element == String { - guard let data = data, data.count > 0 else { return .success(Void()) } - - guard - let responseContentType = response.mimeType, - let responseMIMEType = MIMEType(responseContentType) - else { - for contentType in acceptableContentTypes { - if let mimeType = MIMEType(contentType), mimeType.isWildcard { - return .success(Void()) - } - } - - let error: AFError = { - let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } - - for contentType in acceptableContentTypes { - if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { - return .success(Void()) - } - } - - let error: AFError = { - let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), - responseContentType: responseContentType) - - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } -} - -// MARK: - - -extension DataRequest { - /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the - /// request was valid. - public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _ in - self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, data in - self.validate(contentType: acceptableContentTypes(), response: response, data: data) - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes: () -> [String] = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} - -// MARK: - - -extension DownloadRequest { - /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a - /// destination URL, and returns whether the request was valid. - public typealias Validation = (_ request: URLRequest?, - _ response: HTTPURLResponse, - _ fileURL: URL?) - -> ValidationResult - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _ in - self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, fileURL in - guard let validFileURL = fileURL else { - return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) - } - - do { - let data = try Data(contentsOf: validFileURL) - return self.validate(contentType: acceptableContentTypes(), response: response, data: data) - } catch { - return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) - } - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/AFError+AlamofireTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/AFError+AlamofireTests.swift deleted file mode 100644 index 588b0c5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/AFError+AlamofireTests.swift +++ /dev/null @@ -1,394 +0,0 @@ -// -// AFError+AlamofireTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire - -extension AFError { - // ParameterEncodingFailureReason - - var isMissingURLFailed: Bool { - if case let .parameterEncodingFailed(reason) = self, reason.isMissingURL { return true } - return false - } - - var isJSONEncodingFailed: Bool { - if case let .parameterEncodingFailed(reason) = self, reason.isJSONEncodingFailed { return true } - return false - } - - // MultipartEncodingFailureReason - - var isBodyPartURLInvalid: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartURLInvalid { return true } - return false - } - - var isBodyPartFilenameInvalid: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFilenameInvalid { return true } - return false - } - - var isBodyPartFileNotReachable: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileNotReachable { return true } - return false - } - - var isBodyPartFileNotReachableWithError: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileNotReachableWithError { return true } - return false - } - - var isBodyPartFileIsDirectory: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileIsDirectory { return true } - return false - } - - var isBodyPartFileSizeNotAvailable: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileSizeNotAvailable { return true } - return false - } - - var isBodyPartFileSizeQueryFailedWithError: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartFileSizeQueryFailedWithError { return true } - return false - } - - var isBodyPartInputStreamCreationFailed: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isBodyPartInputStreamCreationFailed { return true } - return false - } - - var isOutputStreamCreationFailed: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamCreationFailed { return true } - return false - } - - var isOutputStreamFileAlreadyExists: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamFileAlreadyExists { return true } - return false - } - - var isOutputStreamURLInvalid: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamURLInvalid { return true } - return false - } - - var isOutputStreamWriteFailed: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isOutputStreamWriteFailed { return true } - return false - } - - var isInputStreamReadFailed: Bool { - if case let .multipartEncodingFailed(reason) = self, reason.isInputStreamReadFailed { return true } - return false - } - - // ResponseSerializationFailureReason - - var isInputDataNilOrZeroLength: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isInputDataNilOrZeroLength { return true } - return false - } - - var isInputFileNil: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isInputFileNil { return true } - return false - } - - var isInputFileReadFailed: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isInputFileReadFailed { return true } - return false - } - - var isStringSerializationFailed: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isStringSerializationFailed { return true } - return false - } - - var isJSONSerializationFailed: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isJSONSerializationFailed { return true } - return false - } - - var isJSONDecodingFailed: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isDecodingFailed { return true } - return false - } - - var isInvalidEmptyResponse: Bool { - if case let .responseSerializationFailed(reason) = self, reason.isInvalidEmptyResponse { return true } - return false - } - - // ResponseValidationFailureReason - - var isDataFileNil: Bool { - if case let .responseValidationFailed(reason) = self, reason.isDataFileNil { return true } - return false - } - - var isDataFileReadFailed: Bool { - if case let .responseValidationFailed(reason) = self, reason.isDataFileReadFailed { return true } - return false - } - - var isMissingContentType: Bool { - if case let .responseValidationFailed(reason) = self, reason.isMissingContentType { return true } - return false - } - - var isUnacceptableContentType: Bool { - if case let .responseValidationFailed(reason) = self, reason.isUnacceptableContentType { return true } - return false - } - - var isUnacceptableStatusCode: Bool { - if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true } - return false - } - - // URLRequestValidationFailure - - var isBodyDataInGETRequest: Bool { - if case let .urlRequestValidationFailed(reason) = self, reason.isBodyDataInGETRequest { return true } - return false - } -} - -// MARK: - - -extension AFError.ParameterEncodingFailureReason { - var isMissingURL: Bool { - if case .missingURL = self { return true } - return false - } - - var isJSONEncodingFailed: Bool { - if case .jsonEncodingFailed = self { return true } - return false - } -} - -// MARK: - - -extension AFError.MultipartEncodingFailureReason { - var isBodyPartURLInvalid: Bool { - if case .bodyPartURLInvalid = self { return true } - return false - } - - var isBodyPartFilenameInvalid: Bool { - if case .bodyPartFilenameInvalid = self { return true } - return false - } - - var isBodyPartFileNotReachable: Bool { - if case .bodyPartFileNotReachable = self { return true } - return false - } - - var isBodyPartFileNotReachableWithError: Bool { - if case .bodyPartFileNotReachableWithError = self { return true } - return false - } - - var isBodyPartFileIsDirectory: Bool { - if case .bodyPartFileIsDirectory = self { return true } - return false - } - - var isBodyPartFileSizeNotAvailable: Bool { - if case .bodyPartFileSizeNotAvailable = self { return true } - return false - } - - var isBodyPartFileSizeQueryFailedWithError: Bool { - if case .bodyPartFileSizeQueryFailedWithError = self { return true } - return false - } - - var isBodyPartInputStreamCreationFailed: Bool { - if case .bodyPartInputStreamCreationFailed = self { return true } - return false - } - - var isOutputStreamCreationFailed: Bool { - if case .outputStreamCreationFailed = self { return true } - return false - } - - var isOutputStreamFileAlreadyExists: Bool { - if case .outputStreamFileAlreadyExists = self { return true } - return false - } - - var isOutputStreamURLInvalid: Bool { - if case .outputStreamURLInvalid = self { return true } - return false - } - - var isOutputStreamWriteFailed: Bool { - if case .outputStreamWriteFailed = self { return true } - return false - } - - var isInputStreamReadFailed: Bool { - if case .inputStreamReadFailed = self { return true } - return false - } -} - -// MARK: - - -extension AFError.ResponseSerializationFailureReason { - var isInputDataNilOrZeroLength: Bool { - if case .inputDataNilOrZeroLength = self { return true } - return false - } - - var isInputFileNil: Bool { - if case .inputFileNil = self { return true } - return false - } - - var isInputFileReadFailed: Bool { - if case .inputFileReadFailed = self { return true } - return false - } - - var isStringSerializationFailed: Bool { - if case .stringSerializationFailed = self { return true } - return false - } - - var isJSONSerializationFailed: Bool { - if case .jsonSerializationFailed = self { return true } - return false - } - - var isDecodingFailed: Bool { - if case .decodingFailed = self { return true } - return false - } - - var isInvalidEmptyResponse: Bool { - if case .invalidEmptyResponse = self { return true } - return false - } -} - -// MARK: - - -extension AFError.ResponseValidationFailureReason { - var isDataFileNil: Bool { - if case .dataFileNil = self { return true } - return false - } - - var isDataFileReadFailed: Bool { - if case .dataFileReadFailed = self { return true } - return false - } - - var isMissingContentType: Bool { - if case .missingContentType = self { return true } - return false - } - - var isUnacceptableContentType: Bool { - if case .unacceptableContentType = self { return true } - return false - } - - var isUnacceptableStatusCode: Bool { - if case .unacceptableStatusCode = self { return true } - return false - } -} - -// MARK: - - -extension AFError.ServerTrustFailureReason { - var isNoRequiredEvaluator: Bool { - if case .noRequiredEvaluator = self { return true } - return false - } - - var isNoCertificatesFound: Bool { - if case .noCertificatesFound = self { return true } - return false - } - - var isNoPublicKeysFound: Bool { - if case .noPublicKeysFound = self { return true } - return false - } - - var isPolicyApplicationFailed: Bool { - if case .policyApplicationFailed = self { return true } - return false - } - - var isRevocationPolicyCreationFailed: Bool { - if case .revocationPolicyCreationFailed = self { return true } - return false - } - - var isTrustEvaluationFailed: Bool { - if case .trustEvaluationFailed = self { return true } - return false - } - - var isDefaultEvaluationFailed: Bool { - if case .defaultEvaluationFailed = self { return true } - return false - } - - var isHostValidationFailed: Bool { - if case .hostValidationFailed = self { return true } - return false - } - - var isRevocationCheckFailed: Bool { - if case .revocationCheckFailed = self { return true } - return false - } - - var isCertificatePinningFailed: Bool { - if case .certificatePinningFailed = self { return true } - return false - } - - var isPublicKeyPinningFailed: Bool { - if case .publicKeyPinningFailed = self { return true } - return false - } -} - -extension AFError.URLRequestValidationFailureReason { - var isBodyDataInGETRequest: Bool { - if case .bodyDataInGETRequest = self { return true } - return false - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/AuthenticationTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/AuthenticationTests.swift deleted file mode 100644 index 1b2fc24..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/AuthenticationTests.swift +++ /dev/null @@ -1,195 +0,0 @@ -// -// AuthenticationTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class AuthenticationTestCase: BaseTestCase { - let user = "user" - let password = "password" - var urlString = "" - - var manager: Session! - - override func setUp() { - super.setUp() - - manager = Session(configuration: .default) - - // Clear out credentials - let credentialStorage = URLCredentialStorage.shared - - for (protectionSpace, credentials) in credentialStorage.allCredentials { - for (_, credential) in credentials { - credentialStorage.remove(credential, for: protectionSpace) - } - } - - // Clear out cookies - let cookieStorage = HTTPCookieStorage.shared - cookieStorage.cookies?.forEach { cookieStorage.deleteCookie($0) } - } -} - -// MARK: - - -class BasicAuthenticationTestCase: AuthenticationTestCase { - override func setUp() { - super.setUp() - urlString = "https://httpbin.org/basic-auth/\(user)/\(password)" - } - - func testHTTPBasicAuthenticationWithInvalidCredentials() { - // Given - let expectation = self.expectation(description: "\(urlString) 401") - - var response: DataResponse? - - // When - manager.request(urlString) - .authenticate(username: "invalid", password: "credentials") - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertEqual(response?.response?.statusCode, 401) - XCTAssertNil(response?.data) - XCTAssertNil(response?.error) - } - - func testHTTPBasicAuthenticationWithValidCredentials() { - // Given - let expectation = self.expectation(description: "\(urlString) 200") - - var response: DataResponse? - - // When - manager.request(urlString) - .authenticate(username: user, password: password) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertEqual(response?.response?.statusCode, 200) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - } - - func testHiddenHTTPBasicAuthentication() { - // Given - let urlString = "http://httpbin.org/hidden-basic-auth/\(user)/\(password)" - let expectation = self.expectation(description: "\(urlString) 200") - let headers: HTTPHeaders = [.authorization(username: user, password: password)] - - var response: DataResponse? - - // When - manager.request(urlString, headers: headers) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertEqual(response?.response?.statusCode, 200) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - } -} - -// MARK: - - -class HTTPDigestAuthenticationTestCase: AuthenticationTestCase { - let qop = "auth" - - override func setUp() { - super.setUp() - urlString = "https://httpbin.org/digest-auth/\(qop)/\(user)/\(password)" - } - - func testHTTPDigestAuthenticationWithInvalidCredentials() { - // Given - let expectation = self.expectation(description: "\(urlString) 401") - - var response: DataResponse? - - // When - manager.request(urlString) - .authenticate(username: "invalid", password: "credentials") - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertEqual(response?.response?.statusCode, 401) - XCTAssertNil(response?.data) - XCTAssertNil(response?.error) - } - - func testHTTPDigestAuthenticationWithValidCredentials() { - // Given - let expectation = self.expectation(description: "\(urlString) 200") - - var response: DataResponse? - - // When - manager.request(urlString) - .authenticate(username: user, password: password) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertEqual(response?.response?.statusCode, 200) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/BaseTestCase.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/BaseTestCase.swift deleted file mode 100644 index 9ce3b79..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/BaseTestCase.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// BaseTestCase.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class BaseTestCase: XCTestCase { - let timeout: TimeInterval = 10 - - static var testDirectoryURL: URL { return FileManager.temporaryDirectoryURL.appendingPathComponent("org.alamofire.tests") } - var testDirectoryURL: URL { return BaseTestCase.testDirectoryURL } - - override func setUp() { - super.setUp() - - FileManager.removeAllItemsInsideDirectory(at: testDirectoryURL) - FileManager.createDirectory(at: testDirectoryURL) - } - - func url(forResource fileName: String, withExtension ext: String) -> URL { - let bundle = Bundle(for: BaseTestCase.self) - return bundle.url(forResource: fileName, withExtension: ext)! - } - - /// Runs assertions on a particular `DispatchQueue`. - /// - /// - Parameters: - /// - queue: The `DispatchQueue` on which to run the assertions. - /// - assertions: Closure containing assertions to run - func assert(on queue: DispatchQueue, assertions: @escaping () -> Void) { - let expect = expectation(description: "all assertions are complete") - - queue.async { - assertions() - expect.fulfill() - } - - waitForExpectations(timeout: timeout) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/CacheTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/CacheTests.swift deleted file mode 100644 index 5307f81..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/CacheTests.swift +++ /dev/null @@ -1,324 +0,0 @@ -// -// CacheTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -/// This test case tests all implemented cache policies against various `Cache-Control` header values. These tests -/// are meant to cover the main cases of `Cache-Control` header usage, but are by no means exhaustive. -/// -/// These tests work as follows: -/// -/// - Set up an `URLCache` -/// - Set up an `Alamofire.SessionManager` -/// - Execute requests for all `Cache-Control` header values to prime the `NSURLCache` with cached responses -/// - Start up a new test -/// - Execute another round of the same requests with a given `URLRequestCachePolicy` -/// - Verify whether the response came from the cache or from the network -/// - This is determined by whether the cached response timestamp matches the new response timestamp -/// -/// An important thing to note is the difference in behavior between iOS and macOS. On iOS, a response with -/// a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on macOS, it is not. -/// The different tests below reflect and demonstrate this behavior. -/// -/// For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9. -class CacheTestCase: BaseTestCase { - // MARK: - - - struct CacheControl { - static let publicControl = "public" - static let privateControl = "private" - static let maxAgeNonExpired = "max-age=3600" - static let maxAgeExpired = "max-age=0" - static let noCache = "no-cache" - static let noStore = "no-store" - - static var allValues: [String] { - return [CacheControl.publicControl, - CacheControl.privateControl, - CacheControl.maxAgeNonExpired, - CacheControl.maxAgeExpired, - CacheControl.noCache, - CacheControl.noStore] - } - } - - // MARK: - Properties - - var urlCache: URLCache! - var manager: Session! - - let urlString = "https://httpbin.org/response-headers" - let requestTimeout: TimeInterval = 30 - - var requests: [String: URLRequest] = [:] - var timestamps: [String: String] = [:] - - // MARK: - Setup and Teardown - - override func setUp() { - super.setUp() - - urlCache = { - let capacity = 50 * 1024 * 1024 // MBs - // swiftformat:disable indent - #if swift(>=5.1) - if #available(OSX 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { - return URLCache(memoryCapacity: capacity, diskCapacity: capacity) - } else { - return URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil) - } - #else - return URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil) - #endif - // swiftformat:enable indent - }() - - manager = { - let configuration: URLSessionConfiguration = { - let configuration = URLSessionConfiguration.default - configuration.headers = HTTPHeaders.default - configuration.requestCachePolicy = .useProtocolCachePolicy - configuration.urlCache = urlCache - - return configuration - }() - - let manager = Session(configuration: configuration) - - return manager - }() - - primeCachedResponses() - } - - override func tearDown() { - super.tearDown() - - requests.removeAll() - timestamps.removeAll() - - urlCache.removeAllCachedResponses() - } - - // MARK: - Cache Priming Methods - - /** - Executes a request for all `Cache-Control` header values to load the response into the `URLCache`. - - This implementation leverages dispatch groups to execute all the requests as well as wait an additional - second before returning. This ensures the cache contains responses for all requests that are at least - one second old. This allows the tests to distinguish whether the subsequent responses come from the cache - or the network based on the timestamp of the response. - */ - func primeCachedResponses() { - let dispatchGroup = DispatchGroup() - let serialQueue = DispatchQueue(label: "org.alamofire.cache-tests") - - for cacheControl in CacheControl.allValues { - dispatchGroup.enter() - - let request = startRequest(cacheControl: cacheControl, - queue: serialQueue, - completion: { _, response in - let timestamp = response!.allHeaderFields["Date"] as! String - self.timestamps[cacheControl] = timestamp - - dispatchGroup.leave() - }) - - requests[cacheControl] = request - } - - // Wait for all requests to complete - _ = dispatchGroup.wait(timeout: .now() + 30) - - // Pause for 1 additional second to ensure all timestamps will be different - dispatchGroup.enter() - serialQueue.asyncAfter(deadline: .now() + 1) { - dispatchGroup.leave() - } - - // Wait for our 1 second pause to complete - _ = dispatchGroup.wait(timeout: .now() + 1.25) - } - - // MARK: - Request Helper Methods - - func urlRequest(cacheControl: String, cachePolicy: URLRequest.CachePolicy) -> URLRequest { - let parameters = ["Cache-Control": cacheControl] - let url = URL(string: urlString)! - - var urlRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: requestTimeout) - urlRequest.httpMethod = HTTPMethod.get.rawValue - - do { - return try URLEncoding.default.encode(urlRequest, with: parameters) - } catch { - return urlRequest - } - } - - @discardableResult - func startRequest(cacheControl: String, - cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy, - queue: DispatchQueue = .main, - completion: @escaping (URLRequest?, HTTPURLResponse?) -> Void) - -> URLRequest { - let urlRequest = self.urlRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) - let request = manager.request(urlRequest) - - request.response(queue: queue, - completionHandler: { response in - completion(response.request, response.response) - }) - - return urlRequest - } - - // MARK: - Test Execution and Verification - - func executeTest(cachePolicy: URLRequest.CachePolicy, - cacheControl: String, - shouldReturnCachedResponse: Bool) { - // Given - let expectation = self.expectation(description: "GET request to httpbin") - var response: HTTPURLResponse? - - // When - startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in - response = responseResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse) - } - - func verifyResponse(_ response: HTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) { - guard let cachedResponseTimestamp = timestamps[cacheControl] else { - XCTFail("cached response timestamp should not be nil") - return - } - - if let response = response, let timestamp = response.allHeaderFields["Date"] as? String { - if isCachedResponse { - XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal") - } else { - XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal") - } - } else { - XCTFail("response should not be nil") - } - } - - // MARK: - Tests - - func testURLCacheContainsCachedResponsesForAllRequests() { - // Given - let publicRequest = requests[CacheControl.publicControl]! - let privateRequest = requests[CacheControl.privateControl]! - let maxAgeNonExpiredRequest = requests[CacheControl.maxAgeNonExpired]! - let maxAgeExpiredRequest = requests[CacheControl.maxAgeExpired]! - let noCacheRequest = requests[CacheControl.noCache]! - let noStoreRequest = requests[CacheControl.noStore]! - - // When - let publicResponse = urlCache.cachedResponse(for: publicRequest) - let privateResponse = urlCache.cachedResponse(for: privateRequest) - let maxAgeNonExpiredResponse = urlCache.cachedResponse(for: maxAgeNonExpiredRequest) - let maxAgeExpiredResponse = urlCache.cachedResponse(for: maxAgeExpiredRequest) - let noCacheResponse = urlCache.cachedResponse(for: noCacheRequest) - let noStoreResponse = urlCache.cachedResponse(for: noStoreRequest) - - // Then - XCTAssertNotNil(publicResponse, "\(CacheControl.publicControl) response should not be nil") - XCTAssertNotNil(privateResponse, "\(CacheControl.privateControl) response should not be nil") - XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.maxAgeNonExpired) response should not be nil") - XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.maxAgeExpired) response should not be nil") - XCTAssertNotNil(noCacheResponse, "\(CacheControl.noCache) response should not be nil") - XCTAssertNil(noStoreResponse, "\(CacheControl.noStore) response should be nil") - } - - func testDefaultCachePolicy() { - let cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy - - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false) - } - - func testIgnoreLocalCacheDataPolicy() { - let cachePolicy: URLRequest.CachePolicy = .reloadIgnoringLocalCacheData - - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: false) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false) - } - - func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() { - let cachePolicy: URLRequest.CachePolicy = .returnCacheDataElseLoad - - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noStore, shouldReturnCachedResponse: false) - } - - func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() { - let cachePolicy: URLRequest.CachePolicy = .returnCacheDataDontLoad - - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.publicControl, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.privateControl, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeNonExpired, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.maxAgeExpired, shouldReturnCachedResponse: true) - executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.noCache, shouldReturnCachedResponse: true) - - // Given - let expectation = self.expectation(description: "GET request to httpbin") - var response: HTTPURLResponse? - - // When - startRequest(cacheControl: CacheControl.noStore, cachePolicy: cachePolicy) { _, responseResponse in - response = responseResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response, "response should be nil") - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/CachedResponseHandlerTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/CachedResponseHandlerTests.swift deleted file mode 100644 index 505bc4b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/CachedResponseHandlerTests.swift +++ /dev/null @@ -1,231 +0,0 @@ -// -// CachedResponseHandlerTests.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -final class CachedResponseHandlerTestCase: BaseTestCase { - // MARK: Properties - - private let urlString = "https://httpbin.org/get" - - // MARK: Tests - Per Request - - func testThatRequestCachedResponseHandlerCanCacheResponse() { - // Given - let session = self.session() - - var response: DataResponse? - let expectation = self.expectation(description: "Request should cache response") - - // When - let request = session.request(urlString).cacheResponse(using: ResponseCacher.cache).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertTrue(session.cachedResponseExists(for: request)) - } - - func testThatRequestCachedResponseHandlerCanNotCacheResponse() { - // Given - let session = self.session() - - var response: DataResponse? - let expectation = self.expectation(description: "Request should not cache response") - - // When - let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertFalse(session.cachedResponseExists(for: request)) - } - - func testThatRequestCachedResponseHandlerCanModifyCacheResponse() { - // Given - let session = self.session() - - var response: DataResponse? - let expectation = self.expectation(description: "Request should cache response") - - // When - let cacher = ResponseCacher(behavior: .modify { _, response in - CachedURLResponse(response: response.response, - data: response.data, - userInfo: ["key": "value"], - storagePolicy: .allowed) - }) - - let request = session.request(urlString).cacheResponse(using: cacher).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertTrue(session.cachedResponseExists(for: request)) - XCTAssertEqual(session.cachedResponse(for: request)?.userInfo?["key"] as? String, "value") - } - - // MARK: Tests - Per Session - - func testThatSessionCachedResponseHandlerCanCacheResponse() { - // Given - let session = self.session(using: ResponseCacher.cache) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should cache response") - - // When - let request = session.request(urlString).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertTrue(session.cachedResponseExists(for: request)) - } - - func testThatSessionCachedResponseHandlerCanNotCacheResponse() { - // Given - let session = self.session(using: ResponseCacher.doNotCache) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should not cache response") - - // When - let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertFalse(session.cachedResponseExists(for: request)) - } - - func testThatSessionCachedResponseHandlerCanModifyCacheResponse() { - // Given - let cacher = ResponseCacher(behavior: .modify { _, response in - CachedURLResponse(response: response.response, - data: response.data, - userInfo: ["key": "value"], - storagePolicy: .allowed) - }) - - let session = self.session(using: cacher) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should cache response") - - // When - let request = session.request(urlString).cacheResponse(using: cacher).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertTrue(session.cachedResponseExists(for: request)) - XCTAssertEqual(session.cachedResponse(for: request)?.userInfo?["key"] as? String, "value") - } - - // MARK: Tests - Per Request Prioritization - - func testThatRequestCachedResponseHandlerIsPrioritizedOverSessionCachedResponseHandler() { - // Given - let session = self.session(using: ResponseCacher.cache) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should cache response") - - // When - let request = session.request(urlString).cacheResponse(using: ResponseCacher.doNotCache).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertFalse(session.cachedResponseExists(for: request)) - } - - // MARK: Private - Test Helpers - - private func session(using handler: CachedResponseHandler? = nil) -> Session { - let configuration = URLSessionConfiguration.af.default - let capacity = 100_000_000 - let cache: URLCache - // swiftformat:disable indent - #if swift(>=5.1) - if #available(OSX 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - cache = URLCache(memoryCapacity: capacity, diskCapacity: capacity, directory: directory) - } else { - cache = URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: UUID().uuidString) - } - #else - cache = URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: UUID().uuidString) - #endif - // swiftformat:enable indent - configuration.urlCache = cache - - return Session(configuration: configuration, cachedResponseHandler: handler) - } -} - -// MARK: - - -extension Session { - fileprivate func cachedResponse(for request: Request) -> CachedURLResponse? { - guard let urlRequest = request.request else { return nil } - return session.configuration.urlCache?.cachedResponse(for: urlRequest) - } - - fileprivate func cachedResponseExists(for request: Request) -> Bool { - return cachedResponse(for: request) != nil - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift deleted file mode 100644 index 5dd213b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift +++ /dev/null @@ -1,978 +0,0 @@ -// -// DownloadTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class DownloadInitializationTestCase: BaseTestCase { - func testDownloadClassMethodWithMethodURLAndDestination() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "download should complete") - - // When - let request = AF.download(urlString).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request) - XCTAssertEqual(request.request?.httpMethod, "GET") - XCTAssertEqual(request.request?.url?.absoluteString, urlString) - XCTAssertNotNil(request.response) - } - - func testDownloadClassMethodWithMethodURLHeadersAndDestination() { - // Given - let urlString = "https://httpbin.org/get" - let headers: HTTPHeaders = ["Authorization": "123456"] - let expectation = self.expectation(description: "download should complete") - - // When - let request = AF.download(urlString, headers: headers).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request) - XCTAssertEqual(request.request?.httpMethod, "GET") - XCTAssertEqual(request.request?.url?.absoluteString, urlString) - XCTAssertEqual(request.request?.headers["Authorization"], "123456") - XCTAssertNotNil(request.response) - } -} - -// MARK: - - -class DownloadResponseTestCase: BaseTestCase { - private var randomCachesFileURL: URL { - return testDirectoryURL.appendingPathComponent("\(UUID().uuidString).json") - } - - func testDownloadRequest() { - // Given - let fileURL = randomCachesFileURL - let numberOfLines = 10 - let urlString = "https://httpbin.org/stream/\(numberOfLines)" - let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) } - - let expectation = self.expectation(description: "Download request should download data to file: \(urlString)") - var response: DownloadResponse? - - // When - AF.download(urlString, to: destination) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - - if let destinationURL = response?.fileURL { - XCTAssertTrue(FileManager.default.fileExists(atPath: destinationURL.path)) - - if let data = try? Data(contentsOf: destinationURL) { - XCTAssertGreaterThan(data.count, 0) - } else { - XCTFail("data should exist for contents of destinationURL") - } - } - } - - func testCancelledDownloadRequest() { - // Given - let fileURL = randomCachesFileURL - let numberOfLines = 10 - let urlString = "https://httpbin.org/stream/\(numberOfLines)" - let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) } - - let expectation = self.expectation(description: "Cancelled download request should not download data to file") - var response: DownloadResponse? - - // When - AF.download(urlString, to: destination) - .response { resp in - response = resp - expectation.fulfill() - } - .cancel() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isExplicitlyCancelledError, true) - } - - func testDownloadRequestWithProgress() { - // Given - let randomBytes = 1 * 1024 * 1024 - let urlString = "https://httpbin.org/bytes/\(randomBytes)" - - let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)") - - var progressValues: [Double] = [] - var response: DownloadResponse? - - // When - AF.download(urlString) - .downloadProgress { progress in - progressValues.append(progress.fractionCompleted) - } - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - - var previousProgress: Double = progressValues.first ?? 0.0 - - for progress in progressValues { - XCTAssertGreaterThanOrEqual(progress, previousProgress) - previousProgress = progress - } - - if let lastProgressValue = progressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in progressValues should not be nil") - } - } - - func testDownloadRequestWithParameters() { - // Given - let fileURL = randomCachesFileURL - let urlString = "https://httpbin.org/get" - let parameters = ["foo": "bar"] - let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) } - - let expectation = self.expectation(description: "Download request should download data to file") - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: parameters, to: destination) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - - if - let data = try? Data(contentsOf: fileURL), - let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), - let json = jsonObject as? [String: Any], - let args = json["args"] as? [String: String] { - XCTAssertEqual(args["foo"], "bar") - } else { - XCTFail("args parameter in JSON should not be nil") - } - } - - func testDownloadRequestWithHeaders() { - // Given - let fileURL = randomCachesFileURL - let urlString = "https://httpbin.org/get" - let headers: HTTPHeaders = ["Authorization": "123456"] - let destination: DownloadRequest.Destination = { _, _ in (fileURL, []) } - - let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)") - var response: DownloadResponse? - - // When - AF.download(urlString, headers: headers, to: destination) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - - if - let data = try? Data(contentsOf: fileURL), - let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), - let json = jsonObject as? [String: Any], - let headers = json["headers"] as? [String: String] { - XCTAssertEqual(headers["Authorization"], "123456") - } else { - XCTFail("headers parameter in JSON should not be nil") - } - } - - func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() { - // Given - let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json") - - let expectation = self.expectation(description: "Download request should download data but fail to move file") - var response: DownloadResponse? - - // When - AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, []) }) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileNoSuchFile) - } - - func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() { - // Given - let fileURL = testDirectoryURL.appendingPathComponent("some/random/folder/test_output.json") - - let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)") - var response: DownloadResponse? - - // When - AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.createIntermediateDirectories]) }) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - } - - func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() throws { - // Given - let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder") - let directoryCreated = FileManager.createDirectory(at: directoryURL) - - let fileURL = directoryURL.appendingPathComponent("test_output.json") - try "random_data".write(to: fileURL, atomically: true, encoding: .utf8) - - let expectation = self.expectation(description: "Download should complete but fail to move file") - var response: DownloadResponse? - - // When - AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, []) }) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertTrue(directoryCreated) - - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .fileWriteFileExists) - } - - func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() { - // Given - let directoryURL = testDirectoryURL.appendingPathComponent("some/random/folder") - let directoryCreated = FileManager.createDirectory(at: directoryURL) - - let fileURL = directoryURL.appendingPathComponent("test_output.json") - - let expectation = self.expectation(description: "Download should complete and move file to URL: \(fileURL)") - var response: DownloadResponse? - - // When - AF.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.removePreviousFile, .createIntermediateDirectories]) }) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertTrue(directoryCreated) - - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - } -} - -final class DownloadRequestEventsTestCase: BaseTestCase { - func testThatDownloadRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didWriteData = expectation(description: "didWriteData should fire") - let didFinishDownloading = expectation(description: "didFinishDownloading should fire") - let didFinishWithResult = expectation(description: "didFinishWithResult should fire") - let didCreate = expectation(description: "didCreate should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - var wroteData = false - - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() } - eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.downloadTaskDidWriteData = { _, _, _, _, _ in - guard !wroteData else { return } - - wroteData = true - didWriteData.fulfill() - } - eventMonitor.downloadTaskDidFinishDownloadingToURL = { _, _, _ in didFinishDownloading.fulfill() } - eventMonitor.requestDidFinishDownloadingUsingTaskWithResult = { _, _, _ in didFinishWithResult.fulfill() } - eventMonitor.requestDidCreateDestinationURL = { _, _ in didCreate.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() } - eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() } - - // When - let request = session.download(URLRequest.makeHTTPBinRequest()).response { _ in - responseHandler.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatCancelledDownloadRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let didCancel = expectation(description: "didCancel should fire") - let didCancelTask = expectation(description: "didCancelTask should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() } - eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidParseDownloadResponse = { _, _ in didParseResponse.fulfill() } - eventMonitor.requestDidCancel = { _ in didCancel.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() } - - // When - let request = session.download(URLRequest.makeHTTPBinRequest()).response { _ in - responseHandler.fulfill() - } - - eventMonitor.requestDidResumeTask = { _, _ in - request.cancel() - didResumeTask.fulfill() - } - - request.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } -} - -// MARK: - - -final class DownloadResumeDataTestCase: BaseTestCase { - let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg" - - func testThatCancelledDownloadRequestDoesNotProduceResumeData() { - // Given - let expectation = self.expectation(description: "Download should be cancelled") - var cancelled = false - - var response: DownloadResponse? - - // When - let download = AF.download(urlString) - download.downloadProgress { progress in - guard !cancelled else { return } - - if progress.fractionCompleted > 0.1 { - download.cancel() - cancelled = true - } - } - download.response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNotNil(response?.error) - - XCTAssertNil(response?.resumeData) - XCTAssertNil(download.resumeData) - } - - func testThatCancelledDownloadResponseDataMatchesResumeData() { - // Given - let expectation = self.expectation(description: "Download should be cancelled") - var cancelled = false - - var response: DownloadResponse? - - // When - let download = AF.download(urlString) - download.downloadProgress { progress in - guard !cancelled else { return } - - if progress.fractionCompleted > 0.1 { - download.cancel(producingResumeData: true) - cancelled = true - } - } - download.response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNotNil(response?.error) - - XCTAssertNotNil(response?.resumeData) - XCTAssertNotNil(download.resumeData) - - XCTAssertEqual(response?.resumeData, download.resumeData) - } - - func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() { - // Given - let expectation = self.expectation(description: "Download should be cancelled") - var cancelled = false - - var response: DownloadResponse? - - // When - let download = AF.download(urlString) - download.downloadProgress { progress in - guard !cancelled else { return } - - if progress.fractionCompleted > 0.1 { - download.cancel(producingResumeData: true) - cancelled = true - } - } - download.responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertNotNil(response?.result.failure) - - XCTAssertNotNil(response?.resumeData) - XCTAssertNotNil(download.resumeData) - - XCTAssertEqual(response?.resumeData, download.resumeData) - } - - func testThatCancelledDownloadCanBeResumedWithResumeData() { - // Given - let expectation1 = expectation(description: "Download should be cancelled") - var cancelled = false - - var response1: DownloadResponse? - - // When - let download = AF.download(urlString) - download.downloadProgress { progress in - guard !cancelled else { return } - - if progress.fractionCompleted > 0.4 { - download.cancel(producingResumeData: true) - cancelled = true - } - } - download.responseData { resp in - response1 = resp - expectation1.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - guard let resumeData = download.resumeData else { - XCTFail("resumeData should not be nil") - return - } - - let expectation2 = expectation(description: "Download should complete") - - var progressValues: [Double] = [] - var response2: DownloadResponse? - - AF.download(resumingWith: resumeData) - .downloadProgress { progress in - progressValues.append(progress.fractionCompleted) - } - .responseData { resp in - response2 = resp - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response1?.request) - XCTAssertNotNil(response1?.response) - XCTAssertNil(response1?.fileURL) - XCTAssertEqual(response1?.result.isFailure, true) - XCTAssertNotNil(response1?.result.failure) - - XCTAssertNotNil(response2?.response) - XCTAssertNotNil(response2?.fileURL) - XCTAssertEqual(response2?.result.isSuccess, true) - XCTAssertNil(response2?.result.failure) - - progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.4) } - } - - func testThatCancelledDownloadProducesMatchingResumeData() { - // Given - let expectation = self.expectation(description: "Download should be cancelled") - var cancelled = false - var receivedResumeData: Data? - var response: DownloadResponse? - - // When - let download = AF.download(urlString) - download.downloadProgress { progress in - guard !cancelled else { return } - - if progress.fractionCompleted > 0.1 { - download.cancel { receivedResumeData = $0 } - cancelled = true - } - } - download.response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNotNil(response?.error) - - XCTAssertNotNil(response?.resumeData) - XCTAssertNotNil(download.resumeData) - - XCTAssertEqual(response?.resumeData, download.resumeData) - XCTAssertEqual(response?.resumeData, receivedResumeData) - XCTAssertEqual(download.resumeData, receivedResumeData) - } -} - -// MARK: - - -class DownloadResponseMapTestCase: BaseTestCase { - func testThatMapTransformsSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.map { json in - // json["args"]["foo"] is "bar": use this invariant to test the map function - ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - XCTAssertEqual(response?.result.success, "bar") - XCTAssertNotNil(response?.metrics) - } - - func testThatMapPreservesFailureError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.map { _ in "ignored" } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -class DownloadResponseTryMapTestCase: BaseTestCase { - func testThatTryMapTransformsSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.tryMap { json in - // json["args"]["foo"] is "bar": use this invariant to test the map function - ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - XCTAssertEqual(response?.result.success, "bar") - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapCatchesTransformationError() { - // Given - struct TransformError: Error {} - - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.tryMap { _ in - throw TransformError() - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - if let error = response?.result.failure { - XCTAssertTrue(error is TransformError) - } else { - XCTFail("flatMap should catch the transformation error") - } - - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapPreservesFailureError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DownloadResponse? - - // When - AF.download(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.tryMap { _ in "ignored" } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertNotNil(response?.metrics) - } -} - -class DownloadResponseMapErrorTestCase: BaseTestCase { - func testThatMapErrorTransformsFailureValue() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should not succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString).responseJSON { resp in - response = resp.mapError { error in - TestError.error(error: error) - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.result.isFailure, true) - - guard let error = response?.error, case .error = error else { XCTFail(); return } - - XCTAssertNotNil(response?.metrics) - } - - func testThatMapErrorPreservesSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString).responseData { resp in - response = resp.mapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -class DownloadResponseTryMapErrorTestCase: BaseTestCase { - func testThatTryMapErrorPreservesSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DownloadResponse? - - // When - AF.download(urlString).responseData { resp in - response = resp.tryMapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNil(response?.error) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapErrorCatchesTransformationError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DownloadResponse? - - // When - AF.download(urlString).responseData { resp in - response = resp.tryMapError { _ in try TransformationError.error.alwaysFails() } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.result.isFailure, true) - - if let error = response?.result.failure { - XCTAssertTrue(error is TransformationError) - } else { - XCTFail("flatMapError should catch the transformation error") - } - - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapErrorTransformsError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DownloadResponse? - - // When - AF.download(urlString).responseData { resp in - response = resp.tryMapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.result.isFailure, true) - guard let error = response?.error, case TestError.error = error else { XCTFail(); return } - - XCTAssertNotNil(response?.metrics) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/FileManager+AlamofireTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/FileManager+AlamofireTests.swift deleted file mode 100644 index f7c037f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/FileManager+AlamofireTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// FileManager+AlamofireTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension FileManager { - // MARK: - Common Directories - - static var temporaryDirectoryPath: String { - return NSTemporaryDirectory() - } - - static var temporaryDirectoryURL: URL { - return URL(fileURLWithPath: FileManager.temporaryDirectoryPath, isDirectory: true) - } - - // MARK: - File System Modification - - @discardableResult - static func createDirectory(atPath path: String) -> Bool { - do { - try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) - return true - } catch { - return false - } - } - - @discardableResult - static func createDirectory(at url: URL) -> Bool { - return createDirectory(atPath: url.path) - } - - @discardableResult - static func removeItem(atPath path: String) -> Bool { - do { - try FileManager.default.removeItem(atPath: path) - return true - } catch { - return false - } - } - - @discardableResult - static func removeItem(at url: URL) -> Bool { - return removeItem(atPath: url.path) - } - - @discardableResult - static func removeAllItemsInsideDirectory(atPath path: String) -> Bool { - let enumerator = FileManager.default.enumerator(atPath: path) - var result = true - - while let fileName = enumerator?.nextObject() as? String { - let success = removeItem(atPath: path + "/\(fileName)") - if !success { result = false } - } - - return result - } - - @discardableResult - static func removeAllItemsInsideDirectory(at url: URL) -> Bool { - return removeAllItemsInsideDirectory(atPath: url.path) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPBin.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPBin.swift deleted file mode 100644 index 4ce112c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPBin.swift +++ /dev/null @@ -1,82 +0,0 @@ -// -// HTTPBin.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation - -extension String { - static let httpBinURLString = "https://httpbin.org" -} - -extension URL { - static func makeHTTPBinURL(path: String = "get") -> URL { - let url = URL(string: .httpBinURLString)! - return url.appendingPathComponent(path) - } -} - -extension URLRequest { - static func makeHTTPBinRequest(path: String = "get", - method: HTTPMethod = .get, - headers: HTTPHeaders = .init(), - timeout: TimeInterval = 60, - cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> URLRequest { - var request = URLRequest(url: .makeHTTPBinURL(path: path)) - request.httpMethod = method.rawValue - request.headers = headers - request.timeoutInterval = timeout - request.cachePolicy = cachePolicy - - return request - } - - static func make(url: URL = URL(string: "https://httpbin.org/get")!, method: HTTPMethod = .get, headers: HTTPHeaders = .init()) -> URLRequest { - var request = URLRequest(url: url) - request.method = method - request.headers = headers - - return request - } -} - -extension Data { - var asString: String { - return String(data: self, encoding: .utf8)! - } -} - -struct HTTPBinResponse: Decodable { - let headers: [String: String] - let origin: String - let url: String - let data: String? - let form: [String: String]? - let args: [String: String] -} - -struct HTTPBinParameters: Encodable { - static let `default` = HTTPBinParameters(property: "property") - - let property: String -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPHeadersTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPHeadersTests.swift deleted file mode 100644 index 3661bc8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/HTTPHeadersTests.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// HTTPHeadersTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import XCTest - -class HTTPHeadersTests: BaseTestCase { - func testHeadersAreStoreUniquelyByCaseInsensitiveName() { - // Given - let headersFromDictionaryLiteral: HTTPHeaders = ["key": "", "Key": "", "KEY": ""] - let headersFromDictionary = HTTPHeaders(["key": "", "Key": "", "KEY": ""]) - let headersFromArrayLiteral: HTTPHeaders = [HTTPHeader(name: "key", value: ""), - HTTPHeader(name: "Key", value: ""), - HTTPHeader(name: "KEY", value: "")] - let headersFromArray = HTTPHeaders([HTTPHeader(name: "key", value: ""), - HTTPHeader(name: "Key", value: ""), - HTTPHeader(name: "KEY", value: "")]) - var headersCreatedManually = HTTPHeaders() - headersCreatedManually.update(HTTPHeader(name: "key", value: "")) - headersCreatedManually.update(name: "Key", value: "") - headersCreatedManually.update(name: "KEY", value: "") - - // When, Then - XCTAssertEqual(headersFromDictionaryLiteral.count, 1) - XCTAssertEqual(headersFromDictionary.count, 1) - XCTAssertEqual(headersFromArrayLiteral.count, 1) - XCTAssertEqual(headersFromArray.count, 1) - XCTAssertEqual(headersCreatedManually.count, 1) - } - - func testHeadersPreserveOrderOfInsertion() { - // Given - let headersFromDictionaryLiteral: HTTPHeaders = ["c": "", "a": "", "b": ""] - // Dictionary initializer can't preserve order. - let headersFromArrayLiteral: HTTPHeaders = [HTTPHeader(name: "b", value: ""), - HTTPHeader(name: "a", value: ""), - HTTPHeader(name: "c", value: "")] - let headersFromArray = HTTPHeaders([HTTPHeader(name: "b", value: ""), - HTTPHeader(name: "a", value: ""), - HTTPHeader(name: "c", value: "")]) - var headersCreatedManually = HTTPHeaders() - headersCreatedManually.update(HTTPHeader(name: "c", value: "")) - headersCreatedManually.update(name: "b", value: "") - headersCreatedManually.update(name: "a", value: "") - - // When - let dictionaryLiteralNames = headersFromDictionaryLiteral.map { $0.name } - let arrayLiteralNames = headersFromArrayLiteral.map { $0.name } - let arrayNames = headersFromArray.map { $0.name } - let manualNames = headersCreatedManually.map { $0.name } - - // Then - XCTAssertEqual(dictionaryLiteralNames, ["c", "a", "b"]) - XCTAssertEqual(arrayLiteralNames, ["b", "a", "c"]) - XCTAssertEqual(arrayNames, ["b", "a", "c"]) - XCTAssertEqual(manualNames, ["c", "b", "a"]) - } - - func testHeadersCanBeProperlySortedByName() { - // Given - let headers: HTTPHeaders = ["c": "", "a": "", "b": ""] - - // When - let sortedHeaders = headers.sorted() - - // Then - XCTAssertEqual(headers.map { $0.name }, ["c", "a", "b"]) - XCTAssertEqual(sortedHeaders.map { $0.name }, ["a", "b", "c"]) - } - - func testHeadersCanInsensitivelyGetAndSetThroughSubscript() { - // Given - var headers: HTTPHeaders = ["c": "", "a": "", "b": ""] - - // When - headers["C"] = "c" - headers["a"] = "a" - headers["b"] = "b" - - // Then - XCTAssertEqual(headers["c"], "c") - XCTAssertEqual(headers.map { $0.value }, ["c", "a", "b"]) - XCTAssertEqual(headers.count, 3) - } - - func testHeadersPreserveLastFormAndValueOfAName() { - // Given - var headers: HTTPHeaders = ["c": "a"] - - // When - headers["C"] = "c" - - // Then - XCTAssertEqual(headers.description, "C: c") - } - - func testHeadersHaveUnsortedDescription() { - // Given - let headers: HTTPHeaders = ["c": "c", "a": "a", "b": "b"] - - // When - let description = headers.description - let expectedDescription = """ - c: c - a: a - b: b - """ - - // Then - XCTAssertEqual(description, expectedDescription) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Info.plist b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Info.plist deleted file mode 100644 index ba72822..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Info.plist +++ /dev/null @@ -1,24 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - BNDL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1 - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/MultipartFormDataTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/MultipartFormDataTests.swift deleted file mode 100644 index b9e3596..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/MultipartFormDataTests.swift +++ /dev/null @@ -1,917 +0,0 @@ -// -// MultipartFormDataTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -struct EncodingCharacters { - static let crlf = "\r\n" -} - -struct BoundaryGenerator { - enum BoundaryType { - case initial, encapsulated, final - } - - static func boundary(forBoundaryType boundaryType: BoundaryType, boundaryKey: String) -> String { - let boundary: String - - switch boundaryType { - case .initial: - boundary = "--\(boundaryKey)\(EncodingCharacters.crlf)" - case .encapsulated: - boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)\(EncodingCharacters.crlf)" - case .final: - boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)--\(EncodingCharacters.crlf)" - } - - return boundary - } - - static func boundaryData(boundaryType: BoundaryType, boundaryKey: String) -> Data { - return Data(BoundaryGenerator.boundary(forBoundaryType: boundaryType, - boundaryKey: boundaryKey).utf8) - } -} - -private func temporaryFileURL() -> URL { return BaseTestCase.testDirectoryURL.appendingPathComponent(UUID().uuidString) } - -// MARK: - - -class MultipartFormDataPropertiesTestCase: BaseTestCase { - func testThatContentTypeContainsBoundary() { - // Given - let multipartFormData = MultipartFormData() - - // When - let boundary = multipartFormData.boundary - - // Then - let expectedContentType = "multipart/form-data; boundary=\(boundary)" - XCTAssertEqual(multipartFormData.contentType, expectedContentType, "contentType should match expected value") - } - - func testThatContentLengthMatchesTotalBodyPartSize() { - // Given - let multipartFormData = MultipartFormData() - let data1 = Data("Lorem ipsum dolor sit amet.".utf8) - let data2 = Data("Vim at integre alterum.".utf8) - - // When - multipartFormData.append(data1, withName: "data1") - multipartFormData.append(data2, withName: "data2") - - // Then - let expectedContentLength = UInt64(data1.count + data2.count) - XCTAssertEqual(multipartFormData.contentLength, expectedContentLength, "content length should match expected value") - } -} - -// MARK: - - -class MultipartFormDataEncodingTestCase: BaseTestCase { - let crlf = EncodingCharacters.crlf - - func testEncodingDataBodyPart() { - // Given - let multipartFormData = MultipartFormData() - - let data = Data("Lorem ipsum dolor sit amet.".utf8) - multipartFormData.append(data, withName: "data") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - let expectedString = ( - BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + - "Lorem ipsum dolor sit amet." + - BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) - ) - let expectedData = Data(expectedString.utf8) - - XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") - } - } - - func testEncodingMultipleDataBodyParts() { - // Given - let multipartFormData = MultipartFormData() - - let frenchData = Data("français".utf8) - let japaneseData = Data("日本語".utf8) - let emojiData = Data("😃👍🏻🍻🎉".utf8) - - multipartFormData.append(frenchData, withName: "french") - multipartFormData.append(japaneseData, withName: "japanese", mimeType: "text/plain") - multipartFormData.append(emojiData, withName: "emoji", mimeType: "text/plain") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - let expectedString = ( - BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + - "français" + - BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"japanese\"\(crlf)" + - "Content-Type: text/plain\(crlf)\(crlf)" + - "日本語" + - BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"emoji\"\(crlf)" + - "Content-Type: text/plain\(crlf)\(crlf)" + - "😃👍🏻🍻🎉" + - BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) - ) - let expectedData = Data(expectedString.utf8) - - XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") - } - } - - func testEncodingFileBodyPart() { - // Given - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - multipartFormData.append(unicornImageURL, withName: "unicorn") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - var expectedData = Data() - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: unicornImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(encodedData, expectedData, "data should match expected data") - } - } - - func testEncodingMultipleFileBodyParts() { - // Given - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - - multipartFormData.append(unicornImageURL, withName: "unicorn") - multipartFormData.append(rainbowImageURL, withName: "rainbow") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - var expectedData = Data() - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: unicornImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: rainbowImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(encodedData, expectedData, "data should match expected data") - } - } - - func testEncodingStreamBodyPart() { - // Given - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) - let unicornStream = InputStream(url: unicornImageURL)! - - multipartFormData.append(unicornStream, - withLength: unicornDataLength, - name: "unicorn", - fileName: "unicorn.png", - mimeType: "image/png") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - var expectedData = Data() - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: unicornImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(encodedData, expectedData, "data should match expected data") - } - } - - func testEncodingMultipleStreamBodyParts() { - // Given - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) - let unicornStream = InputStream(url: unicornImageURL)! - - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) - let rainbowStream = InputStream(url: rainbowImageURL)! - - multipartFormData.append(unicornStream, - withLength: unicornDataLength, - name: "unicorn", - fileName: "unicorn.png", - mimeType: "image/png") - multipartFormData.append(rainbowStream, - withLength: rainbowDataLength, - name: "rainbow", - fileName: "rainbow.jpg", - mimeType: "image/jpeg") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - var expectedData = Data() - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: unicornImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: rainbowImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(encodedData, expectedData, "data should match expected data") - } - } - - func testEncodingMultipleBodyPartsWithVaryingTypes() { - // Given - let multipartFormData = MultipartFormData() - - let loremData = Data("Lorem ipsum.".utf8) - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) - let rainbowStream = InputStream(url: rainbowImageURL)! - - multipartFormData.append(loremData, withName: "lorem") - multipartFormData.append(unicornImageURL, withName: "unicorn") - multipartFormData.append(rainbowStream, - withLength: rainbowDataLength, - name: "rainbow", - fileName: "rainbow.jpg", - mimeType: "image/jpeg") - - var encodedData: Data? - - // When - do { - encodedData = try multipartFormData.encode() - } catch { - // No-op - } - - // Then - XCTAssertNotNil(encodedData, "encoded data should not be nil") - - if let encodedData = encodedData { - let boundary = multipartFormData.boundary - - var expectedData = Data() - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedData.append(Data( - "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)".utf8 - ) - ) - expectedData.append(loremData) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: unicornImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedData.append(try! Data(contentsOf: rainbowImageURL)) - expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(encodedData, expectedData, "data should match expected data") - } - } -} - -// MARK: - - -class MultipartFormDataWriteEncodedDataToDiskTestCase: BaseTestCase { - let crlf = EncodingCharacters.crlf - - func testWritingEncodedDataBodyPartToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let data = Data("Lorem ipsum dolor sit amet.".utf8) - multipartFormData.append(data, withName: "data") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - let expectedString = BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + - "Lorem ipsum dolor sit amet." + - BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) - let expectedFileData = Data(expectedString.utf8) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingMultipleEncodedDataBodyPartsToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let frenchData = Data("français".utf8) - let japaneseData = Data("日本語".utf8) - let emojiData = Data("😃👍🏻🍻🎉".utf8) - - multipartFormData.append(frenchData, withName: "french") - multipartFormData.append(japaneseData, withName: "japanese") - multipartFormData.append(emojiData, withName: "emoji") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - let expectedString = ( - BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + - "français" + - BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"japanese\"\(crlf)\(crlf)" + - "日本語" + - BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + - "Content-Disposition: form-data; name=\"emoji\"\(crlf)\(crlf)" + - "😃👍🏻🍻🎉" + - BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) - ) - let expectedFileData = Data(expectedString.utf8) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingEncodedFileBodyPartToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - multipartFormData.append(unicornImageURL, withName: "unicorn") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - var expectedFileData = Data() - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: unicornImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingMultipleEncodedFileBodyPartsToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - - multipartFormData.append(unicornImageURL, withName: "unicorn") - multipartFormData.append(rainbowImageURL, withName: "rainbow") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - var expectedFileData = Data() - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: unicornImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingEncodedStreamBodyPartToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) - let unicornStream = InputStream(url: unicornImageURL)! - - multipartFormData.append(unicornStream, - withLength: unicornDataLength, - name: "unicorn", - fileName: "unicorn.png", - mimeType: "image/png") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - var expectedFileData = Data() - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: unicornImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingMultipleEncodedStreamBodyPartsToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) - let unicornStream = InputStream(url: unicornImageURL)! - - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) - let rainbowStream = InputStream(url: rainbowImageURL)! - - multipartFormData.append(unicornStream, - withLength: unicornDataLength, - name: "unicorn", - fileName: "unicorn.png", - mimeType: "image/png") - multipartFormData.append(rainbowStream, - withLength: rainbowDataLength, - name: "rainbow", - fileName: "rainbow.jpg", - mimeType: "image/jpeg") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - var expectedFileData = Data() - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: unicornImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } - - func testWritingMultipleEncodedBodyPartsWithVaryingTypesToDisk() { - // Given - let fileURL = temporaryFileURL() - let multipartFormData = MultipartFormData() - - let loremData = Data("Lorem ipsum.".utf8) - - let unicornImageURL = url(forResource: "unicorn", withExtension: "png") - - let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") - let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) - let rainbowStream = InputStream(url: rainbowImageURL)! - - multipartFormData.append(loremData, withName: "lorem") - multipartFormData.append(unicornImageURL, withName: "unicorn") - multipartFormData.append(rainbowStream, - withLength: rainbowDataLength, - name: "rainbow", - fileName: "rainbow.jpg", - mimeType: "image/jpeg") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(encodingError, "encoding error should be nil") - - if let fileData = try? Data(contentsOf: fileURL) { - let boundary = multipartFormData.boundary - - var expectedFileData = Data() - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) - expectedFileData.append(Data( - "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)".utf8 - ) - ) - expectedFileData.append(loremData) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)" + - "Content-Type: image/png\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: unicornImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) - expectedFileData.append(Data(( - "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)" + - "Content-Type: image/jpeg\(crlf)\(crlf)").utf8 - ) - ) - expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) - expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) - - XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") - } else { - XCTFail("file data should not be nil") - } - } -} - -// MARK: - - -class MultipartFormDataFailureTestCase: BaseTestCase { - func testThatAppendingFileBodyPartWithInvalidLastPathComponentReturnsError() { - // Given - let fileURL = NSURL(string: "")! as URL - let multipartFormData = MultipartFormData() - multipartFormData.append(fileURL, withName: "empty_data") - - var encodingError: Error? - - // When - do { - _ = try multipartFormData.encode() - } catch { - encodingError = error - } - - // Then - XCTAssertNotNil(encodingError, "encoding error should not be nil") - - XCTAssertEqual(encodingError?.asAFError?.isBodyPartFilenameInvalid, true) - XCTAssertEqual(encodingError?.asAFError?.url, fileURL) - } - - func testThatAppendingFileBodyPartThatIsNotFileURLReturnsError() { - // Given - let fileURL = URL(string: "https://example.com/image.jpg")! - let multipartFormData = MultipartFormData() - multipartFormData.append(fileURL, withName: "empty_data") - - var encodingError: Error? - - // When - do { - _ = try multipartFormData.encode() - } catch { - encodingError = error - } - - // Then - XCTAssertNotNil(encodingError, "encoding error should not be nil") - XCTAssertEqual(encodingError?.asAFError?.isBodyPartURLInvalid, true) - XCTAssertEqual(encodingError?.asAFError?.url, fileURL) - } - - func testThatAppendingFileBodyPartThatIsNotReachableReturnsError() { - // Given - let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("does_not_exist.jpg") - let fileURL = URL(fileURLWithPath: filePath) - let multipartFormData = MultipartFormData() - multipartFormData.append(fileURL, withName: "empty_data") - - var encodingError: Error? - - // When - do { - _ = try multipartFormData.encode() - } catch { - encodingError = error - } - - // Then - XCTAssertNotNil(encodingError, "encoding error should not be nil") - - XCTAssertEqual(encodingError?.asAFError?.isBodyPartFileNotReachableWithError, true) - XCTAssertEqual(encodingError?.asAFError?.url, fileURL) - } - - func testThatAppendingFileBodyPartThatIsDirectoryReturnsError() { - // Given - let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) - let multipartFormData = MultipartFormData() - multipartFormData.append(directoryURL, withName: "empty_data", fileName: "empty", mimeType: "application/octet") - - var encodingError: Error? - - // When - do { - _ = try multipartFormData.encode() - } catch { - encodingError = error - } - - // Then - XCTAssertNotNil(encodingError, "encoding error should not be nil") - XCTAssertEqual(encodingError?.asAFError?.isBodyPartFileIsDirectory, true) - XCTAssertEqual(encodingError?.asAFError?.url, directoryURL) - } - - func testThatWritingEncodedDataToExistingFileURLFails() { - // Given - let fileURL = temporaryFileURL() - - var writerError: Error? - - do { - try "dummy data".write(to: fileURL, atomically: true, encoding: .utf8) - } catch { - writerError = error - } - - let multipartFormData = MultipartFormData() - let data = Data("Lorem ipsum dolor sit amet.".utf8) - multipartFormData.append(data, withName: "data") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNil(writerError, "writer error should be nil") - XCTAssertNotNil(encodingError, "encoding error should not be nil") - XCTAssertEqual(encodingError?.asAFError?.isOutputStreamFileAlreadyExists, true) - } - - func testThatWritingEncodedDataToBadURLFails() { - // Given - let fileURL = URL(string: "/this/is/not/a/valid/url")! - - let multipartFormData = MultipartFormData() - let data = Data("Lorem ipsum dolor sit amet.".utf8) - multipartFormData.append(data, withName: "data") - - var encodingError: Error? - - // When - do { - try multipartFormData.writeEncodedData(to: fileURL) - } catch { - encodingError = error - } - - // Then - XCTAssertNotNil(encodingError, "encoding error should not be nil") - XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/NSLoggingEventMonitor.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/NSLoggingEventMonitor.swift deleted file mode 100644 index 65cd101..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/NSLoggingEventMonitor.swift +++ /dev/null @@ -1,214 +0,0 @@ -// -// NSLoggingEventMonitor.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation - -public final class NSLoggingEventMonitor: EventMonitor { - public let queue = DispatchQueue(label: "org.alamofire.nsLoggingEventMonitorQueue", qos: .background) - - public init() {} - - public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - NSLog("URLSession: \(session), didBecomeInvalidWithError: \(error?.localizedDescription ?? "None")") - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { - NSLog("URLSession: \(session), task: \(task), didReceiveChallenge: \(challenge)") - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - NSLog("URLSession: \(session), task: \(task), didSendBodyData: \(bytesSent), totalBytesSent: \(totalBytesSent), totalBytesExpectedToSent: \(totalBytesExpectedToSend)") - } - - public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { - NSLog("URLSession: \(session), taskNeedsNewBodyStream: \(task)") - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) { - NSLog("URLSession: \(session), task: \(task), willPerformHTTPRedirection: \(response), newRequest: \(request)") - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - NSLog("URLSession: \(session), task: \(task), didFinishCollecting: \(metrics)") - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - NSLog("URLSession: \(session), task: \(task), didCompleteWithError: \(error?.localizedDescription ?? "None")") - } - - public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - NSLog("URLSession: \(session), taskIsWaitingForConnectivity: \(task)") - } - - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - NSLog("URLSession: \(session), dataTask: \(dataTask), didReceiveDataOfLength: \(data.count)") - } - - public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse) { - NSLog("URLSession: \(session), dataTask: \(dataTask), willCacheResponse: \(proposedResponse)") - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - NSLog("URLSession: \(session), downloadTask: \(downloadTask), didResumeAtOffset: \(fileOffset), expectedTotalBytes: \(expectedTotalBytes)") - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - NSLog("URLSession: \(session), downloadTask: \(downloadTask), didWriteData bytesWritten: \(bytesWritten), totalBytesWritten: \(totalBytesWritten), totalBytesExpectedToWrite: \(totalBytesExpectedToWrite)") - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - NSLog("URLSession: \(session), downloadTask: \(downloadTask), didFinishDownloadingTo: \(location)") - } - - public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { - NSLog("Request: \(request) didCreateInitialURLRequest: \(urlRequest)") - } - - public func request(_ request: Request, didFailToCreateURLRequestWithError error: Error) { - NSLog("Request: \(request) didFailToCreateURLRequestWithError: \(error)") - } - - public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { - NSLog("Request: \(request) didAdaptInitialRequest \(initialRequest) to \(adaptedRequest)") - } - - public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: Error) { - NSLog("Request: \(request) didFailToAdaptURLRequest \(initialRequest) withError \(error)") - } - - public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { - NSLog("Request: \(request) didCreateURLRequest: \(urlRequest)") - } - - public func request(_ request: Request, didCreateTask task: URLSessionTask) { - NSLog("Request: \(request) didCreateTask \(task)") - } - - public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { - NSLog("Request: \(request) didGatherMetrics \(metrics)") - } - - public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: Error) { - NSLog("Request: \(request) didFailTask \(task) earlyWithError \(error)") - } - - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: Error?) { - NSLog("Request: \(request) didCompleteTask \(task) withError: \(error?.localizedDescription ?? "None")") - } - - public func requestDidFinish(_ request: Request) { - NSLog("Request: \(request) didFinish") - } - - public func requestDidResume(_ request: Request) { - NSLog("Request: \(request) didResume") - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - NSLog("Request: \(request) didResumeTask: \(task)") - } - - public func requestDidSuspend(_ request: Request) { - NSLog("Request: \(request) didSuspend") - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - NSLog("Request: \(request) didSuspendTask: \(task)") - } - - public func requestDidCancel(_ request: Request) { - NSLog("Request: \(request) didCancel") - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - NSLog("Request: \(request) didCancelTask: \(task)") - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - NSLog("Request: \(request), didParseResponse: \(response)") - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - NSLog("Request: \(request), didParseResponse: \(response)") - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - NSLog("Request: \(request), didParseResponse: \(response)") - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - NSLog("Request: \(request), didParseResponse: \(response)") - } - - public func requestIsRetrying(_ request: Request) { - NSLog("Request: \(request), isRetrying") - } - - public func request(_ request: DataRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, data: Data?, withResult result: Request.ValidationResult) { - NSLog("Request: \(request), didValidateRequestWithResult: \(result)") - } - - public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { - NSLog("Request: \(request), didCreateUploadable: \(uploadable)") - } - - public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: Error) { - NSLog("Request: \(request), didFailToCreateUploadableWithError: \(error)") - } - - public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { - NSLog("Request: \(request), didProvideInputStream: \(stream)") - } - - public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { - NSLog("Request: \(request), didFinishDownloadingUsing: \(task), withResult: \(result)") - } - - public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { - NSLog("Request: \(request), didCreateDestinationURL: \(url)") - } - - public func request(_ request: DownloadRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, temporaryURL: URL?, destinationURL: URL?, withResult result: Request.ValidationResult) { - NSLog("Request: \(request), didValidateRequestWithResult: \(result)") - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/NetworkReachabilityManagerTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/NetworkReachabilityManagerTests.swift deleted file mode 100644 index f7d9e19..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/NetworkReachabilityManagerTests.swift +++ /dev/null @@ -1,283 +0,0 @@ -// -// NetworkReachabilityManagerTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import SystemConfiguration -import XCTest - -final class NetworkReachabilityManagerTestCase: BaseTestCase { - // MARK: - Tests - Initialization - - func testThatManagerCanBeInitializedFromHost() { - // Given, When - let manager = NetworkReachabilityManager(host: "localhost") - - // Then - XCTAssertNotNil(manager) - } - - func testThatManagerCanBeInitializedFromAddress() { - // Given, When - let manager = NetworkReachabilityManager() - - // Then - XCTAssertNotNil(manager) - } - - func testThatHostManagerIsReachableOnWiFi() { - // Given, When - let manager = NetworkReachabilityManager(host: "localhost") - - // Then - XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) - XCTAssertEqual(manager?.isReachable, true) - XCTAssertEqual(manager?.isReachableOnCellular, false) - XCTAssertEqual(manager?.isReachableOnEthernetOrWiFi, true) - } - - func testThatHostManagerStartsWithReachableStatus() { - // Given, When - let manager = NetworkReachabilityManager(host: "localhost") - - // Then - XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) - XCTAssertEqual(manager?.isReachable, true) - XCTAssertEqual(manager?.isReachableOnCellular, false) - XCTAssertEqual(manager?.isReachableOnEthernetOrWiFi, true) - } - - func testThatAddressManagerStartsWithReachableStatus() { - // Given, When - let manager = NetworkReachabilityManager() - - // Then - XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) - XCTAssertEqual(manager?.isReachable, true) - XCTAssertEqual(manager?.isReachableOnCellular, false) - XCTAssertEqual(manager?.isReachableOnEthernetOrWiFi, true) - } - - func testThatZeroManagerCanBeProperlyRestarted() { - // Given - let manager = NetworkReachabilityManager() - let first = expectation(description: "first listener notified") - let second = expectation(description: "second listener notified") - - // When - manager?.startListening { _ in - first.fulfill() - } - wait(for: [first], timeout: timeout) - - manager?.stopListening() - - manager?.startListening { _ in - second.fulfill() - } - wait(for: [second], timeout: timeout) - - // Then - XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) - } - - func testThatHostManagerCanBeProperlyRestarted() { - // Given - let manager = NetworkReachabilityManager(host: "localhost") - let first = expectation(description: "first listener notified") - let second = expectation(description: "second listener notified") - - // When - manager?.startListening { _ in - first.fulfill() - } - wait(for: [first], timeout: timeout) - - manager?.stopListening() - - manager?.startListening { _ in - second.fulfill() - } - wait(for: [second], timeout: timeout) - - // Then - XCTAssertEqual(manager?.status, .reachable(.ethernetOrWiFi)) - } - - func testThatHostManagerCanBeDeinitialized() { - // Given - var manager: NetworkReachabilityManager? = NetworkReachabilityManager(host: "localhost") - - // When - manager = nil - - // Then - XCTAssertNil(manager) - } - - func testThatAddressManagerCanBeDeinitialized() { - // Given - var manager: NetworkReachabilityManager? = NetworkReachabilityManager() - - // When - manager = nil - - // Then - XCTAssertNil(manager) - } - - // MARK: - Listener - - func testThatHostManagerIsNotifiedWhenStartListeningIsCalled() { - // Given - guard let manager = NetworkReachabilityManager(host: "store.apple.com") else { - XCTFail("manager should NOT be nil") - return - } - - let expectation = self.expectation(description: "listener closure should be executed") - var networkReachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus? - - // When - manager.startListening { status in - guard networkReachabilityStatus == nil else { return } - networkReachabilityStatus = status - expectation.fulfill() - } - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(networkReachabilityStatus, .reachable(.ethernetOrWiFi)) - } - - func testThatAddressManagerIsNotifiedWhenStartListeningIsCalled() { - // Given - let manager = NetworkReachabilityManager() - let expectation = self.expectation(description: "listener closure should be executed") - - var networkReachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus? - - // When - manager?.startListening { status in - networkReachabilityStatus = status - expectation.fulfill() - } - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(networkReachabilityStatus, .reachable(.ethernetOrWiFi)) - } - - // MARK: - NetworkReachabilityStatus - - func testThatStatusIsNotReachableStatusWhenReachableFlagIsAbsent() { - // Given - let flags: SCNetworkReachabilityFlags = [.connectionOnDemand] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .notReachable) - } - - func testThatStatusIsNotReachableStatusWhenConnectionIsRequired() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .connectionRequired] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .notReachable) - } - - func testThatStatusIsNotReachableStatusWhenInterventionIsRequired() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .connectionRequired, .interventionRequired] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .notReachable) - } - - func testThatStatusIsReachableOnWiFiStatusWhenConnectionIsNotRequired() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .reachable(.ethernetOrWiFi)) - } - - func testThatStatusIsReachableOnWiFiStatusWhenConnectionIsOnDemand() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .connectionRequired, .connectionOnDemand] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .reachable(.ethernetOrWiFi)) - } - - func testThatStatusIsReachableOnWiFiStatusWhenConnectionIsOnTraffic() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .connectionRequired, .connectionOnTraffic] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .reachable(.ethernetOrWiFi)) - } - -#if os(iOS) || os(tvOS) - func testThatStatusIsReachableOnCellularStatusWhenIsWWAN() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .isWWAN] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .reachable(.cellular)) - } - - func testThatStatusIsNotReachableOnCellularStatusWhenIsWWANAndConnectionIsRequired() { - // Given - let flags: SCNetworkReachabilityFlags = [.reachable, .isWWAN, .connectionRequired] - - // When - let status = NetworkReachabilityManager.NetworkReachabilityStatus(flags) - - // Then - XCTAssertEqual(status, .notReachable) - } -#endif -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncoderTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncoderTests.swift deleted file mode 100644 index d025879..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncoderTests.swift +++ /dev/null @@ -1,994 +0,0 @@ -// -// ParameterEncoderTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import XCTest - -final class JSONParameterEncoderTests: BaseTestCase { - func testThatDataIsProperlyEncodedAndProperContentTypeIsSet() throws { - // Given - let encoder = JSONParameterEncoder() - let request = URLRequest.makeHTTPBinRequest() - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - XCTAssertEqual(newRequest.headers["Content-Type"], "application/json") - XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}") - } - - func testThatDataIsProperlyEncodedButContentTypeIsNotSetIfRequestAlreadyHasAContentType() throws { - // Given - let encoder = JSONParameterEncoder() - var request = URLRequest.makeHTTPBinRequest() - request.headers.update(.contentType("type")) - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - XCTAssertEqual(newRequest.headers["Content-Type"], "type") - XCTAssertEqual(newRequest.httpBody?.asString, "{\"property\":\"property\"}") - } - - func testThatJSONEncoderCanBeCustomized() throws { - // Given - let jsonEncoder = JSONEncoder() - jsonEncoder.outputFormatting = .prettyPrinted - let encoder = JSONParameterEncoder(encoder: jsonEncoder) - let request = URLRequest.makeHTTPBinRequest() - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - let expected = """ - { - "property" : "property" - } - """ - XCTAssertEqual(newRequest.httpBody?.asString, expected) - } - - func testThatJSONEncoderDefaultWorks() throws { - // Given - let encoder = JSONParameterEncoder.default - let request = URLRequest.makeHTTPBinRequest() - - // When - let encoded = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - let expected = """ - {"property":"property"} - """ - XCTAssertEqual(encoded.httpBody?.asString, expected) - } - - func testThatJSONEncoderPrettyPrintedPrintsPretty() throws { - // Given - let encoder = JSONParameterEncoder.prettyPrinted - let request = URLRequest.makeHTTPBinRequest() - - // When - let encoded = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - let expected = """ - { - "property" : "property" - } - """ - XCTAssertEqual(encoded.httpBody?.asString, expected) - } -} - -final class SortedKeysJSONParameterEncoderTests: BaseTestCase { - func testTestJSONEncoderSortedKeysHasSortedKeys() throws { - guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) else { return } - // Given - let encoder = JSONParameterEncoder.sortedKeys - let request = URLRequest.makeHTTPBinRequest() - - // When - let encoded = try encoder.encode(["z": "z", "a": "a", "p": "p"], into: request) - - // Then - let expected = """ - {"a":"a","p":"p","z":"z"} - """ - XCTAssertEqual(encoded.httpBody?.asString, expected) - } -} - -final class URLEncodedFormParameterEncoderTests: BaseTestCase { - func testThatQueryIsBodyEncodedAndProperContentTypeIsSetForPOSTRequest() throws { - // Given - let encoder = URLEncodedFormParameterEncoder() - let request = URLRequest.makeHTTPBinRequest(method: .post) - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - XCTAssertEqual(newRequest.headers["Content-Type"], "application/x-www-form-urlencoded; charset=utf-8") - XCTAssertEqual(newRequest.httpBody?.asString, "property=property") - } - - func testThatQueryIsBodyEncodedButContentTypeIsNotSetWhenRequestAlreadyHasContentType() throws { - // Given - let encoder = URLEncodedFormParameterEncoder() - var request = URLRequest.makeHTTPBinRequest(method: .post) - request.headers.update(.contentType("type")) - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - XCTAssertEqual(newRequest.headers["Content-Type"], "type") - XCTAssertEqual(newRequest.httpBody?.asString, "property=property") - } - - func testThatEncoderCanBeCustomized() throws { - // Given - let urlEncoder = URLEncodedFormEncoder(boolEncoding: .literal) - let encoder = URLEncodedFormParameterEncoder(encoder: urlEncoder) - let request = URLRequest.makeHTTPBinRequest() - - // When - let newRequest = try encoder.encode(["bool": true], into: request) - - // Then - let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false) - XCTAssertEqual(components?.percentEncodedQuery, "bool=true") - } - - func testThatQueryIsInURLWhenDestinationIsURLAndMethodIsPOST() throws { - // Given - let encoder = URLEncodedFormParameterEncoder(destination: .queryString) - let request = URLRequest.makeHTTPBinRequest(method: .post) - - // When - let newRequest = try encoder.encode(HTTPBinParameters.default, into: request) - - // Then - let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false) - XCTAssertEqual(components?.percentEncodedQuery, "property=property") - } - - func testThatQueryIsNilWhenEncodableResultsInAnEmptyString() throws { - // Given - let encoder = URLEncodedFormParameterEncoder(destination: .queryString) - let request = URLRequest.makeHTTPBinRequest() - - // When - let newRequest = try encoder.encode([String: String](), into: request) - - // Then - let components = URLComponents(url: newRequest.url!, resolvingAgainstBaseURL: false) - XCTAssertNil(components?.percentEncodedQuery) - } -} - -final class URLEncodedFormEncoderTests: BaseTestCase { - func testEncoderThrowsErrorWhenAttemptingToEncodeNilInKeyedContainer() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = FailingOptionalStruct(testedContainer: .keyed) - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertTrue(result.isFailure) - } - - func testEncoderThrowsErrorWhenAttemptingToEncodeNilInUnkeyedContainer() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = FailingOptionalStruct(testedContainer: .unkeyed) - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertTrue(result.isFailure) - } - - func testEncoderCanEncodeDictionary() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["a": "a"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=a") - } - - func testEncoderCanEncodeDouble() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["a": 1.0] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1.0") - } - - func testEncoderCanEncodeFloat() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: Float] = ["a": 1.0] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1.0") - } - - func testEncoderCanEncodeInt8() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: Int8] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeInt16() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: Int16] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeInt32() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: Int32] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeInt64() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: Int64] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeUInt() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: UInt] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeUInt8() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: UInt8] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeUInt16() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: UInt16] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeUInt32() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: UInt32] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testEncoderCanEncodeUInt64() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: UInt64] = ["a": 1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a=1") - } - - func testThatNestedDictionariesHaveBracketedKeys() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["a": ["b": "b"]] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "a%5Bb%5D=b") - } - - func testThatEncodableStructCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = EncodableStruct() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "five%5Ba%5D=a&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&seven%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&three=1&two=2" - XCTAssertEqual(result.success, expected) - } - - func testThatManuallyEncodableStructCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ManuallyEncodableStruct() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "root%5B%5D%5B%5D%5B%5D=1&root%5B%5D%5B%5D%5B%5D=2&root%5B%5D%5B%5D%5B%5D=3&root%5B%5D%5B%5D=1&root%5B%5D%5B%5D=2&root%5B%5D%5B%5D=3&root%5B%5D%5Ba%5D%5Bstring%5D=string" - XCTAssertEqual(result.success, expected) - } - - func testThatEncodableClassWithNoInheritanceCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = EncodableSuperclass() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "one=one&three=1&two=2") - } - - func testThatEncodableSubclassCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = EncodableSubclass() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&one=one&three=1&two=2" - XCTAssertEqual(result.success, expected) - } - - func testThatEncodableSubclassCanBeEncodedInImplementationOrderWhenAlphabetizeKeysIsFalse() { - // Given - let encoder = URLEncodedFormEncoder(alphabetizeKeyValuePairs: false) - let parameters = EncodableStruct() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "one=one&two=2&three=1&four%5B%5D=1&four%5B%5D=2&four%5B%5D=3&five%5Ba%5D=a&six%5Ba%5D%5Bb%5D=b&seven%5Ba%5D=a" - XCTAssertEqual(result.success, expected) - } - - func testThatManuallyEncodableSubclassCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ManuallyEncodableSubclass() - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "five%5Ba%5D=a&five%5Bb%5D=b&four%5Bfive%5D=2&four%5Bfour%5D=one" - XCTAssertEqual(result.success, expected) - } - - func testThatARootArrayCannotBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = [1] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertFalse(result.isSuccess) - } - - func testThatARootValueCannotBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = "string" - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertFalse(result.isSuccess) - } - - func testThatOptionalValuesCannotBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters: [String: String?] = ["string": nil] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertFalse(result.isSuccess) - } - - func testThatArraysCanBeEncodedWithoutBrackets() { - // Given - let encoder = URLEncodedFormEncoder(arrayEncoding: .noBrackets) - let parameters = ["array": [1, 2]] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "array=1&array=2") - } - - func testThatBoolsCanBeLiteralEncoded() { - // Given - let encoder = URLEncodedFormEncoder(boolEncoding: .literal) - let parameters = ["bool": true] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "bool=true") - } - - func testThatDataCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["data": Data("data".utf8)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "data=ZGF0YQ%3D%3D") - } - - func testThatCustomDataEncodingFailsWhenErrorIsThrown() { - // Given - struct DataEncodingError: Error {} - - let encoder = URLEncodedFormEncoder(dataEncoding: .custom { _ in throw DataEncodingError() }) - let parameters = ["data": Data("data".utf8)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertTrue(result.failure is DataEncodingError) - } - - func testThatDatesCanBeEncoded() { - // Given - let encoder = URLEncodedFormEncoder(dateEncoding: .deferredToDate) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=123.456") - } - - func testThatDatesCanBeEncodedAsSecondsSince1970() { - // Given - let encoder = URLEncodedFormEncoder(dateEncoding: .secondsSince1970) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=978307323.456") - } - - func testThatDatesCanBeEncodedAsMillisecondsSince1970() { - // Given - let encoder = URLEncodedFormEncoder(dateEncoding: .millisecondsSince1970) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=978307323456.0") - } - - func testThatDatesCanBeEncodedAsISO8601Formatted() { - // Given - let encoder = URLEncodedFormEncoder(dateEncoding: .iso8601) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=2001-01-01T00%3A02%3A03Z") - } - - func testThatDatesCanBeEncodedAsFormatted() { - // Given - let dateFormatter = DateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS" - dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) - - let encoder = URLEncodedFormEncoder(dateEncoding: .formatted(dateFormatter)) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=2001-01-01%2000%3A02%3A03.4560") - } - - func testThatDatesCanBeEncodedAsCustomFormatted() { - // Given - let encoder = URLEncodedFormEncoder(dateEncoding: .custom { "\($0.timeIntervalSinceReferenceDate)" }) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "date=123.456") - } - - func testEncoderThrowsErrorWhenCustomDateEncodingFails() { - // Given - struct DateEncodingError: Error {} - - let encoder = URLEncodedFormEncoder(dateEncoding: .custom { _ in throw DateEncodingError() }) - let parameters = ["date": Date(timeIntervalSinceReferenceDate: 123.456)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertTrue(result.failure is DateEncodingError) - } - - func testThatKeysCanBeEncodedIntoSnakeCase() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .convertToSnakeCase) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "one_two_three=oneTwoThree") - } - - func testThatKeysCanBeEncodedIntoKebabCase() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .convertToKebabCase) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "one-two-three=oneTwoThree") - } - - func testThatKeysCanBeEncodedIntoACapitalizedString() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .capitalized) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "OneTwoThree=oneTwoThree") - } - - func testThatKeysCanBeEncodedIntoALowercasedString() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .lowercased) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "onetwothree=oneTwoThree") - } - - func testThatKeysCanBeEncodedIntoAnUppercasedString() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .uppercased) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "ONETWOTHREE=oneTwoThree") - } - - func testThatKeysCanBeCustomEncoded() { - // Given - let encoder = URLEncodedFormEncoder(keyEncoding: .custom { _ in "A" }) - let parameters = ["oneTwoThree": "oneTwoThree"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "A=oneTwoThree") - } - - func testThatSpacesCanBeEncodedAsPluses() { - // Given - let encoder = URLEncodedFormEncoder(spaceEncoding: .plusReplaced) - let parameters = ["spaces": "replace with spaces"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "spaces=replace+with+spaces") - } - - func testThatEscapedCharactersCanBeCustomized() { - // Given - var allowed = CharacterSet.afURLQueryAllowed - allowed.remove(charactersIn: "?/") - let encoder = URLEncodedFormEncoder(allowedCharacters: allowed) - let parameters = ["allowed": "?/"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "allowed=%3F%2F") - } - - func testThatUnreservedCharactersAreNotPercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz", - "numbers": "0123456789", - "uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expected = "lowercase=abcdefghijklmnopqrstuvwxyz&numbers=0123456789&uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ" - XCTAssertEqual(result.success, expected) - } - - func testThatReservedCharactersArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let generalDelimiters = ":#[]@" - let subDelimiters = "!$&'()*+,;=" - let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D") - } - - func testThatIllegalASCIICharactersArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["illegal": " \"#%<>[]\\^`{}|"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C") - } - - func testThatAmpersandsInKeysAndValuesArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "foo%26bar=baz%26qux&foobar=bazqux") - } - - func testThatQuestionMarksInKeysAndValuesAreNotPercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["?foo?": "?bar?"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "?foo?=?bar?") - } - - func testThatSlashesInKeysAndValuesAreNotPercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["foo": "/bar/baz/qux"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "foo=/bar/baz/qux") - } - - func testThatSpacesInKeysAndValuesArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = [" foo ": " bar "] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "%20foo%20=%20bar%20") - } - - func testThatPlusesInKeysAndValuesArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["+foo+": "+bar+"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "%2Bfoo%2B=%2Bbar%2B") - } - - func testThatPercentsInKeysAndValuesArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["percent%": "%25"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - XCTAssertEqual(result.success, "percent%25=%2525") - } - - func testThatNonLatinCharactersArePercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let parameters = ["french": "français", - "japanese": "日本語", - "arabic": "العربية", - "emoji": "😃"] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let expectedParameterValues = ["arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9", - "emoji=%F0%9F%98%83", - "french=fran%C3%A7ais", - "japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E"].joined(separator: "&") - XCTAssertEqual(result.success, expectedParameterValues) - } - - func testStringWithThousandsOfChineseCharactersIsPercentEscaped() { - // Given - let encoder = URLEncodedFormEncoder() - let repeatedCount = 2000 - let parameters = ["chinese": String(repeating: "一二三四五六七八九十", count: repeatedCount)] - - // When - let result = Result { try encoder.encode(parameters) } - - // Then - let escaped = String(repeating: "%E4%B8%80%E4%BA%8C%E4%B8%89%E5%9B%9B%E4%BA%94%E5%85%AD%E4%B8%83%E5%85%AB%E4%B9%9D%E5%8D%81", - count: repeatedCount) - let expected = "chinese=\(escaped)" - XCTAssertEqual(result.success, expected) - } -} - -private struct EncodableStruct: Encodable { - let one = "one" - let two = 2 - let three = true - let four = [1, 2, 3] - let five = ["a": "a"] - let six = ["a": ["b": "b"]] - let seven = NestedEncodableStruct() -} - -private struct NestedEncodableStruct: Encodable { - let a = "a" -} - -private class EncodableSuperclass: Encodable { - let one = "one" - let two = 2 - let three = true -} - -private final class EncodableSubclass: EncodableSuperclass { - let four = [1, 2, 3] - let five = ["a": "a", "b": "b"] - - private enum CodingKeys: String, CodingKey { - case four, five - } - - override func encode(to encoder: Encoder) throws { - try super.encode(to: encoder) - - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(four, forKey: .four) - try container.encode(five, forKey: .five) - } -} - -private final class ManuallyEncodableSubclass: EncodableSuperclass { - let four = [1, 2, 3] - let five = ["a": "a", "b": "b"] - - private enum CodingKeys: String, CodingKey { - case four, five - } - - override func encode(to encoder: Encoder) throws { - var keyedContainer = encoder.container(keyedBy: CodingKeys.self) - - try keyedContainer.encode(four, forKey: .four) - try keyedContainer.encode(five, forKey: .five) - - let superEncoder = keyedContainer.superEncoder() - var superContainer = superEncoder.container(keyedBy: CodingKeys.self) - try superContainer.encode(one, forKey: .four) - - let keyedSuperEncoder = keyedContainer.superEncoder(forKey: .four) - var superKeyedContainer = keyedSuperEncoder.container(keyedBy: CodingKeys.self) - try superKeyedContainer.encode(two, forKey: .five) - - var unkeyedContainer = keyedContainer.nestedUnkeyedContainer(forKey: .four) - let unkeyedSuperEncoder = unkeyedContainer.superEncoder() - var keyedUnkeyedSuperContainer = unkeyedSuperEncoder.container(keyedBy: CodingKeys.self) - try keyedUnkeyedSuperContainer.encode(one, forKey: .four) - } -} - -private struct ManuallyEncodableStruct: Encodable { - let a = ["string": "string"] - let b = [1, 2, 3] - - private enum RootKey: String, CodingKey { - case root - } - - private enum TypeKeys: String, CodingKey { - case a, b - } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: RootKey.self) - - var nestedKeyedContainer = container.nestedContainer(keyedBy: TypeKeys.self, forKey: .root) - try nestedKeyedContainer.encode(a, forKey: .a) - - var nestedUnkeyedContainer = container.nestedUnkeyedContainer(forKey: .root) - try nestedUnkeyedContainer.encode(b) - - var nestedUnkeyedKeyedContainer = nestedUnkeyedContainer.nestedContainer(keyedBy: TypeKeys.self) - try nestedUnkeyedKeyedContainer.encode(a, forKey: .a) - - var nestedUnkeyedUnkeyedContainer = nestedUnkeyedContainer.nestedUnkeyedContainer() - try nestedUnkeyedUnkeyedContainer.encode(b) - } -} - -private struct FailingOptionalStruct: Encodable { - enum TestedContainer { - case keyed, unkeyed - } - - enum CodingKeys: String, CodingKey { case a } - - let testedContainer: TestedContainer - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - - switch testedContainer { - case .keyed: - var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .a) - try nested.encodeNil(forKey: .a) - case .unkeyed: - var nested = container.nestedUnkeyedContainer(forKey: .a) - try nested.encodeNil() - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncodingTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncodingTests.swift deleted file mode 100644 index f70cf4e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ParameterEncodingTests.swift +++ /dev/null @@ -1,759 +0,0 @@ -// -// ParameterEncodingTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class ParameterEncodingTestCase: BaseTestCase { - let urlRequest = URLRequest(url: URL(string: "https://example.com/")!) -} - -// MARK: - - -class URLParameterEncodingTestCase: ParameterEncodingTestCase { - // MARK: Properties - - let encoding = URLEncoding.default - - // MARK: Tests - Parameter Types - - func testURLParameterEncodeNilParameters() { - do { - // Given, When - let urlRequest = try encoding.encode(self.urlRequest, with: nil) - - // Then - XCTAssertNil(urlRequest.url?.query) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeEmptyDictionaryParameter() { - do { - // Given - let parameters: [String: Any] = [:] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertNil(urlRequest.url?.query) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeOneStringKeyStringValueParameter() { - do { - // Given - let parameters = ["foo": "bar"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=bar") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeOneStringKeyStringValueParameterAppendedToQuery() { - do { - // Given - var mutableURLRequest = self.urlRequest - var urlComponents = URLComponents(url: mutableURLRequest.url!, resolvingAgainstBaseURL: false)! - urlComponents.query = "baz=qux" - mutableURLRequest.url = urlComponents.url - - let parameters = ["foo": "bar"] - - // When - let urlRequest = try encoding.encode(mutableURLRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "baz=qux&foo=bar") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeTwoStringKeyStringValueParameters() { - do { - // Given - let parameters = ["foo": "bar", "baz": "qux"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "baz=qux&foo=bar") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNSNumberIntegerValueParameter() { - do { - // Given - let parameters = ["foo": NSNumber(value: 25)] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=25") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNSNumberBoolValueParameter() { - do { - // Given - let parameters = ["foo": NSNumber(value: false)] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=0") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyIntegerValueParameter() { - do { - // Given - let parameters = ["foo": 1] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyDoubleValueParameter() { - do { - // Given - let parameters = ["foo": 1.1] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=1.1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyBoolValueParameter() { - do { - // Given - let parameters = ["foo": true] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyArrayValueParameter() { - do { - // Given - let parameters = ["foo": ["a", 1, true]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo%5B%5D=a&foo%5B%5D=1&foo%5B%5D=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyArrayValueParameterWithoutBrackets() { - do { - // Given - let encoding = URLEncoding(arrayEncoding: .noBrackets) - let parameters = ["foo": ["a", 1, true]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=a&foo=1&foo=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyDictionaryValueParameter() { - do { - // Given - let parameters = ["foo": ["bar": 1]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo%5Bbar%5D=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNestedDictionaryValueParameter() { - do { - // Given - let parameters = ["foo": ["bar": ["baz": 1]]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo%5Bbar%5D%5Bbaz%5D=1") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameter() { - do { - // Given - let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - let expectedQuery = "foo%5Bbar%5D%5Bbaz%5D%5B%5D=a&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1" - XCTAssertEqual(urlRequest.url?.query, expectedQuery) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameterWithoutBrackets() { - do { - // Given - let encoding = URLEncoding(arrayEncoding: .noBrackets) - let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - let expectedQuery = "foo%5Bbar%5D%5Bbaz%5D=a&foo%5Bbar%5D%5Bbaz%5D=1&foo%5Bbar%5D%5Bbaz%5D=1" - XCTAssertEqual(urlRequest.url?.query, expectedQuery) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterLiteralBoolEncodingWorksAndDoesNotAffectNumbers() { - do { - // Given - let encoding = URLEncoding(boolEncoding: .literal) - let parameters: [String: Any] = [// Must still encode to numbers - "a": 1, - "b": 0, - "c": 1.0, - "d": 0.0, - "e": NSNumber(value: 1), - "f": NSNumber(value: 0), - "g": NSNumber(value: 1.0), - "h": NSNumber(value: 0.0), - - // Must encode to literals - "i": true, - "j": false, - "k": NSNumber(value: true), - "l": NSNumber(value: false)] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "a=1&b=0&c=1&d=0&e=1&f=0&g=1&h=0&i=true&j=false&k=true&l=false") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - // MARK: Tests - All Reserved / Unreserved / Illegal Characters According to RFC 3986 - - func testThatReservedCharactersArePercentEscapedMinusQuestionMarkAndForwardSlash() { - do { - // Given - let generalDelimiters = ":#[]@" - let subDelimiters = "!$&'()*+,;=" - let parameters = ["reserved": "\(generalDelimiters)\(subDelimiters)"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - let expectedQuery = "reserved=%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D" - XCTAssertEqual(urlRequest.url?.query, expectedQuery) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testThatReservedCharactersQuestionMarkAndForwardSlashAreNotPercentEscaped() { - do { - // Given - let parameters = ["reserved": "?/"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "reserved=?/") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testThatUnreservedNumericCharactersAreNotPercentEscaped() { - do { - // Given - let parameters = ["numbers": "0123456789"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "numbers=0123456789") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testThatUnreservedLowercaseCharactersAreNotPercentEscaped() { - do { - // Given - let parameters = ["lowercase": "abcdefghijklmnopqrstuvwxyz"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "lowercase=abcdefghijklmnopqrstuvwxyz") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testThatUnreservedUppercaseCharactersAreNotPercentEscaped() { - do { - // Given - let parameters = ["uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "uppercase=ABCDEFGHIJKLMNOPQRSTUVWXYZ") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testThatIllegalASCIICharactersArePercentEscaped() { - do { - // Given - let parameters = ["illegal": " \"#%<>[]\\^`{}|"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - let expectedQuery = "illegal=%20%22%23%25%3C%3E%5B%5D%5C%5E%60%7B%7D%7C" - XCTAssertEqual(urlRequest.url?.query, expectedQuery) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - // MARK: Tests - Special Character Queries - - func testURLParameterEncodeStringWithAmpersandKeyStringWithAmpersandValueParameter() { - do { - // Given - let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo%26bar=baz%26qux&foobar=bazqux") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() { - do { - // Given - let parameters = ["?foo?": "?bar?"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "?foo?=?bar?") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithSlashKeyStringWithQuestionMarkValueParameter() { - do { - // Given - let parameters = ["foo": "/bar/baz/qux"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "foo=/bar/baz/qux") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithSpaceKeyStringWithSpaceValueParameter() { - do { - // Given - let parameters = [" foo ": " bar "] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "%20foo%20=%20bar%20") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameter() { - do { - // Given - let parameters = ["+foo+": "+bar+"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "%2Bfoo%2B=%2Bbar%2B") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyPercentEncodedStringValueParameter() { - do { - // Given - let parameters = ["percent": "%25"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "percent=%2525") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringKeyNonLatinStringValueParameter() { - do { - // Given - let parameters = ["french": "français", - "japanese": "日本語", - "arabic": "العربية", - "emoji": "😃"] - - // When - let urlRequest = try encoding.encode(self.urlRequest, with: parameters) - - // Then - let expectedParameterValues = ["arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9", - "emoji=%F0%9F%98%83", - "french=fran%C3%A7ais", - "japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E"] - - let expectedQuery = expectedParameterValues.joined(separator: "&") - XCTAssertEqual(urlRequest.url?.query, expectedQuery) - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringForRequestWithPrecomposedQuery() { - do { - // Given - let url = URL(string: "https://example.com/movies?hd=[1]")! - let parameters = ["page": "0"] - - // When - let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "hd=%5B1%5D&page=0") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameterForRequestWithPrecomposedQuery() { - do { - // Given - let url = URL(string: "https://example.com/movie?hd=[1]")! - let parameters = ["+foo+": "+bar+"] - - // When - let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) - - // Then - XCTAssertEqual(urlRequest.url?.query, "hd=%5B1%5D&%2Bfoo%2B=%2Bbar%2B") - } catch { - XCTFail("Test encountered unexpected error: \(error)") - } - } - - func testURLParameterEncodeStringWithThousandsOfChineseCharacters() { - do { - // Given - let repeatedCount = 2000 - let url = URL(string: "https://example.com/movies")! - let parameters = ["chinese": String(repeating: "一二三四五六七八九十", count: repeatedCount)] - - // When - let urlRequest = try encoding.encode(URLRequest(url: url), with: parameters) - - // Then - var expected = "chinese=" - - for _ in 0..? - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - // When - session.request(urlString).redirect(using: Redirector.follow).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - func testThatRequestRedirectHandlerCanNotFollowRedirects() { - // Given - let session = Session() - - var response: DataResponse? - let expectation = self.expectation(description: "Request should NOT redirect to \(redirectURLString)") - - // When - session.request(urlString).redirect(using: Redirector.doNotFollow).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, urlString) - XCTAssertEqual(response?.response?.statusCode, 302) - } - - func testThatRequestRedirectHandlerCanModifyRedirects() { - // Given - let session = Session() - let redirectURLString = "https://www.nike.com" - let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - // When - let redirector = Redirector(behavior: .modify { _, _, _ in redirectURLRequest }) - - session.request(urlString).redirect(using: redirector).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - // MARK: - Tests - Per Session - - func testThatSessionRedirectHandlerCanFollowRedirects() { - // Given - let session = Session(redirectHandler: Redirector.follow) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - // When - session.request(urlString).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - func testThatSessionRedirectHandlerCanNotFollowRedirects() { - // Given - let session = Session(redirectHandler: Redirector.doNotFollow) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should NOT redirect to \(redirectURLString)") - - // When - session.request(urlString).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, urlString) - XCTAssertEqual(response?.response?.statusCode, 302) - } - - func testThatSessionRedirectHandlerCanModifyRedirects() { - // Given - let redirectURLString = "https://www.nike.com" - let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!) - - let redirector = Redirector(behavior: .modify { _, _, _ in redirectURLRequest }) - let session = Session(redirectHandler: redirector) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - // When - session.request(urlString).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - // MARK: - Tests - Per Request Prioritization - - func testThatRequestRedirectHandlerIsPrioritizedOverSessionRedirectHandler() { - // Given - let session = Session(redirectHandler: Redirector.doNotFollow) - - var response: DataResponse? - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - // When - session.request(urlString).redirect(using: Redirector.follow).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestInterceptorTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestInterceptorTests.swift deleted file mode 100644 index 5ae4af0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestInterceptorTests.swift +++ /dev/null @@ -1,517 +0,0 @@ -// -// RequestInterceptorTests.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import XCTest - -private struct MockError: Error {} -private struct RetryError: Error {} - -// MARK: - - -final class RetryResultTestCase: BaseTestCase { - func testRetryRequiredProperty() { - // Given, When - let retry = RetryResult.retry - let retryWithDelay = RetryResult.retryWithDelay(1.0) - let doNotRetry = RetryResult.doNotRetry - let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) - - // Then - XCTAssertTrue(retry.retryRequired) - XCTAssertTrue(retryWithDelay.retryRequired) - XCTAssertFalse(doNotRetry.retryRequired) - XCTAssertFalse(doNotRetryWithError.retryRequired) - } - - func testDelayProperty() { - // Given, When - let retry = RetryResult.retry - let retryWithDelay = RetryResult.retryWithDelay(1.0) - let doNotRetry = RetryResult.doNotRetry - let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) - - // Then - XCTAssertEqual(retry.delay, nil) - XCTAssertEqual(retryWithDelay.delay, 1.0) - XCTAssertEqual(doNotRetry.delay, nil) - XCTAssertEqual(doNotRetryWithError.delay, nil) - } - - func testErrorProperty() { - // Given, When - let retry = RetryResult.retry - let retryWithDelay = RetryResult.retryWithDelay(1.0) - let doNotRetry = RetryResult.doNotRetry - let doNotRetryWithError = RetryResult.doNotRetryWithError(MockError()) - - // Then - XCTAssertNil(retry.error) - XCTAssertNil(retryWithDelay.error) - XCTAssertNil(doNotRetry.error) - XCTAssertTrue(doNotRetryWithError.error is MockError) - } -} - -// MARK: - - -final class AdapterTestCase: BaseTestCase { - func testThatAdapterCallsAdaptHandler() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - var adapted = false - - let adapter = Adapter { request, _, completion in - adapted = true - completion(.success(request)) - } - - var result: Result! - - // When - adapter.adapt(urlRequest, for: session) { result = $0 } - - // Then - XCTAssertTrue(adapted) - XCTAssertTrue(result.isSuccess) - } - - func testThatAdapterCallsRequestRetrierDefaultImplementationInProtocolExtension() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - let adapter = Adapter { request, _, completion in - completion(.success(request)) - } - - var result: RetryResult! - - // When - adapter.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .doNotRetry) - } - - func testThatAdapterCanBeImplementedAsynchronously() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - var adapted = false - - let adapter = Adapter { request, _, completion in - adapted = true - DispatchQueue.main.async { - completion(.success(request)) - } - } - - var result: Result! - - let completesExpectation = expectation(description: "adapter completes") - - // When - adapter.adapt(urlRequest, for: session) { - result = $0 - completesExpectation.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertTrue(adapted) - XCTAssertTrue(result.isSuccess) - } -} - -// MARK: - - -final class RetrierTestCase: BaseTestCase { - func testThatRetrierCallsRetryHandler() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - var retried = false - - let retrier = Retrier { _, _, _, completion in - retried = true - completion(.retry) - } - - var result: RetryResult! - - // When - retrier.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertTrue(retried) - XCTAssertEqual(result, .retry) - } - - func testThatRetrierCallsRequestAdapterDefaultImplementationInProtocolExtension() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - - let retrier = Retrier { _, _, _, completion in - completion(.retry) - } - - var result: Result! - - // When - retrier.adapt(urlRequest, for: session) { result = $0 } - - // Then - XCTAssertTrue(result.isSuccess) - } - - func testThatRetrierCanBeImplementedAsynchronously() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - var retried = false - - let retrier = Retrier { _, _, _, completion in - retried = true - DispatchQueue.main.async { - completion(.retry) - } - } - - var result: RetryResult! - - let completesExpectation = expectation(description: "retrier completes") - - // When - retrier.retry(request, for: session, dueTo: MockError()) { - result = $0 - completesExpectation.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertTrue(retried) - XCTAssertEqual(result, .retry) - } -} - -// MARK: - - -final class InterceptorTestCase: BaseTestCase { - func testAdaptHandlerAndRetryHandlerDefaultInitializer() { - // Given - let adaptHandler: AdaptHandler = { urlRequest, _, completion in completion(.success(urlRequest)) } - let retryHandler: RetryHandler = { _, _, _, completion in completion(.doNotRetry) } - - // When - let interceptor = Interceptor(adaptHandler: adaptHandler, retryHandler: retryHandler) - - // Then - XCTAssertEqual(interceptor.adapters.count, 1) - XCTAssertEqual(interceptor.retriers.count, 1) - } - - func testAdapterAndRetrierDefaultInitializer() { - // Given - let adapter = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } - let retrier = Retrier { _, _, _, completion in completion(.doNotRetry) } - - // When - let interceptor = Interceptor(adapter: adapter, retrier: retrier) - - // Then - XCTAssertEqual(interceptor.adapters.count, 1) - XCTAssertEqual(interceptor.retriers.count, 1) - } - - func testAdaptersAndRetriersDefaultInitializer() { - // Given - let adapter = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } - let retrier = Retrier { _, _, _, completion in completion(.doNotRetry) } - - // When - let interceptor = Interceptor(adapters: [adapter, adapter], retriers: [retrier, retrier]) - - // Then - XCTAssertEqual(interceptor.adapters.count, 2) - XCTAssertEqual(interceptor.retriers.count, 2) - } - - func testThatInterceptorCanAdaptRequestWithNoAdapters() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - let interceptor = Interceptor() - - var result: Result! - - // When - interceptor.adapt(urlRequest, for: session) { result = $0 } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertEqual(result.success, urlRequest) - } - - func testThatInterceptorCanAdaptRequestWithOneAdapter() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - - let adapter = Adapter { _, _, completion in completion(.failure(MockError())) } - let interceptor = Interceptor(adapters: [adapter]) - - var result: Result! - - // When - interceptor.adapt(urlRequest, for: session) { result = $0 } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertTrue(result.failure is MockError) - } - - func testThatInterceptorCanAdaptRequestWithMultipleAdapters() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - - let adapter1 = Adapter { urlRequest, _, completion in completion(.success(urlRequest)) } - let adapter2 = Adapter { _, _, completion in completion(.failure(MockError())) } - let interceptor = Interceptor(adapters: [adapter1, adapter2]) - - var result: Result! - - // When - interceptor.adapt(urlRequest, for: session) { result = $0 } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertTrue(result.failure is MockError) - } - - func testThatInterceptorCanAdaptRequestAsynchronously() { - // Given - let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) - let session = Session() - - let adapter = Adapter { _, _, completion in - DispatchQueue.main.async { - completion(.failure(MockError())) - } - } - let interceptor = Interceptor(adapters: [adapter]) - - var result: Result! - - let completesExpectation = expectation(description: "interceptor completes") - - // When - interceptor.adapt(urlRequest, for: session) { - result = $0 - completesExpectation.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertTrue(result.failure is MockError) - } - - func testThatInterceptorCanRetryRequestWithNoRetriers() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - let interceptor = Interceptor() - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .doNotRetry) - } - - func testThatInterceptorCanRetryRequestWithOneRetrier() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - let retrier = Retrier { _, _, _, completion in completion(.retry) } - let interceptor = Interceptor(retriers: [retrier]) - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .retry) - } - - func testThatInterceptorCanRetryRequestWithMultipleRetriers() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - let retrier1 = Retrier { _, _, _, completion in completion(.doNotRetry) } - let retrier2 = Retrier { _, _, _, completion in completion(.retry) } - let interceptor = Interceptor(retriers: [retrier1, retrier2]) - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .retry) - } - - func testThatInterceptorCanRetryRequestAsynchronously() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - let retrier = Retrier { _, _, _, completion in - DispatchQueue.main.async { - completion(.retry) - } - } - let interceptor = Interceptor(retriers: [retrier]) - - var result: RetryResult! - - let completesExpectation = expectation(description: "interceptor completes") - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { - result = $0 - completesExpectation.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertEqual(result, .retry) - } - - func testThatInterceptorStopsIteratingThroughPendingRetriersWithRetryResult() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - var retrier2Called = false - - let retrier1 = Retrier { _, _, _, completion in completion(.retry) } - let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } - let interceptor = Interceptor(retriers: [retrier1, retrier2]) - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .retry) - XCTAssertFalse(retrier2Called) - } - - func testThatInterceptorStopsIteratingThroughPendingRetriersWithRetryWithDelayResult() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - var retrier2Called = false - - let retrier1 = Retrier { _, _, _, completion in completion(.retryWithDelay(1.0)) } - let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } - let interceptor = Interceptor(retriers: [retrier1, retrier2]) - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, .retryWithDelay(1.0)) - XCTAssertEqual(result.delay, 1.0) - XCTAssertFalse(retrier2Called) - } - - func testThatInterceptorStopsIteratingThroughPendingRetriersWithDoNotRetryResult() { - // Given - let url = URL(string: "https://httpbin.org/get")! - let session = Session(startRequestsImmediately: false) - let request = session.request(url) - - var retrier2Called = false - - let retrier1 = Retrier { _, _, _, completion in completion(.doNotRetryWithError(RetryError())) } - let retrier2 = Retrier { _, _, _, completion in retrier2Called = true; completion(.doNotRetry) } - let interceptor = Interceptor(retriers: [retrier1, retrier2]) - - var result: RetryResult! - - // When - interceptor.retry(request, for: session, dueTo: MockError()) { result = $0 } - - // Then - XCTAssertEqual(result, RetryResult.doNotRetryWithError(RetryError())) - XCTAssertTrue(result.error is RetryError) - XCTAssertFalse(retrier2Called) - } -} - -// MARK: - - -extension RetryResult: Equatable { - public static func ==(lhs: RetryResult, rhs: RetryResult) -> Bool { - switch (lhs, rhs) { - case (.retry, .retry), - (.retryWithDelay, .retryWithDelay), - (.doNotRetry, .doNotRetry), - (.doNotRetryWithError, .doNotRetryWithError): - return true - default: - return false - } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestTests.swift deleted file mode 100644 index 3eb8c81..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RequestTests.swift +++ /dev/null @@ -1,1105 +0,0 @@ -// -// RequestTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -final class RequestResponseTestCase: BaseTestCase { - func testRequestResponse() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "GET request should succeed: \(urlString)") - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - } - - func testRequestResponseWithProgress() { - // Given - let randomBytes = 1 * 1024 * 1024 - let urlString = "https://httpbin.org/bytes/\(randomBytes)" - - let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)") - - var progressValues: [Double] = [] - var response: DataResponse? - - // When - AF.request(urlString) - .downloadProgress { progress in - progressValues.append(progress.fractionCompleted) - } - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - var previousProgress: Double = progressValues.first ?? 0.0 - - for progress in progressValues { - XCTAssertGreaterThanOrEqual(progress, previousProgress) - previousProgress = progress - } - - if let lastProgressValue = progressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in progressValues should not be nil") - } - } - - func testPOSTRequestWithUnicodeParameters() { - // Given - let urlString = "https://httpbin.org/post" - let parameters = ["french": "français", - "japanese": "日本語", - "arabic": "العربية", - "emoji": "😃"] - - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, method: .post, parameters: parameters) - .responseJSON { closureResponse in - response = closureResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - - if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] { - XCTAssertEqual(form["french"], parameters["french"]) - XCTAssertEqual(form["japanese"], parameters["japanese"]) - XCTAssertEqual(form["arabic"], parameters["arabic"]) - XCTAssertEqual(form["emoji"], parameters["emoji"]) - } else { - XCTFail("form parameter in JSON should not be nil") - } - } - - func testPOSTRequestWithBase64EncodedImages() { - // Given - let urlString = "https://httpbin.org/post" - - let pngBase64EncodedString: String = { - let URL = url(forResource: "unicorn", withExtension: "png") - let data = try! Data(contentsOf: URL) - - return data.base64EncodedString(options: .lineLength64Characters) - }() - - let jpegBase64EncodedString: String = { - let URL = url(forResource: "rainbow", withExtension: "jpg") - let data = try! Data(contentsOf: URL) - - return data.base64EncodedString(options: .lineLength64Characters) - }() - - let parameters = ["email": "user@alamofire.org", - "png_image": pngBase64EncodedString, - "jpeg_image": jpegBase64EncodedString] - - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, method: .post, parameters: parameters) - .responseJSON { closureResponse in - response = closureResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - - if let json = response?.result.success as? [String: Any], let form = json["form"] as? [String: String] { - XCTAssertEqual(form["email"], parameters["email"]) - XCTAssertEqual(form["png_image"], parameters["png_image"]) - XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"]) - } else { - XCTFail("form parameter in JSON should not be nil") - } - } - - // MARK: Queues - - func testThatResponseSerializationWorksWithSerializationQueue() { - // Given - let queue = DispatchQueue(label: "org.alamofire.testSerializationQueue") - let manager = Session(serializationQueue: queue) - let expectation = self.expectation(description: "request should complete") - var response: DataResponse? - - // When - manager.request("https://httpbin.org/get").responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - } - - func testThatRequestsWorksWithRequestAndSerializationQueue() { - // Given - let requestQueue = DispatchQueue(label: "org.alamofire.testRequestQueue") - let serializationQueue = DispatchQueue(label: "org.alamofire.testSerializationQueue") - let manager = Session(requestQueue: requestQueue, serializationQueue: serializationQueue) - let expectation = self.expectation(description: "request should complete") - var response: DataResponse? - - // When - manager.request("https://httpbin.org/get").responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response?.result.isSuccess, true) - } - - // MARK: Encodable Parameters - - func testThatRequestsCanPassEncodableParametersAsJSONBodyData() { - // Given - let parameters = HTTPBinParameters(property: "one") - let expect = expectation(description: "request should complete") - var receivedResponse: DataResponse? - - // When - AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default) - .responseDecodable(of: HTTPBinResponse.self) { response in - receivedResponse = response - expect.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(receivedResponse?.result.success?.data, "{\"property\":\"one\"}") - } - - func testThatRequestsCanPassEncodableParametersAsAURLQuery() { - // Given - let parameters = HTTPBinParameters(property: "one") - let expect = expectation(description: "request should complete") - var receivedResponse: DataResponse? - - // When - AF.request("https://httpbin.org/get", method: .get, parameters: parameters) - .responseDecodable(of: HTTPBinResponse.self) { response in - receivedResponse = response - expect.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(receivedResponse?.result.success?.args, ["property": "one"]) - } - - func testThatRequestsCanPassEncodableParametersAsURLEncodedBodyData() { - // Given - let parameters = HTTPBinParameters(property: "one") - let expect = expectation(description: "request should complete") - var receivedResponse: DataResponse? - - // When - AF.request("https://httpbin.org/post", method: .post, parameters: parameters) - .responseDecodable(of: HTTPBinResponse.self) { response in - receivedResponse = response - expect.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(receivedResponse?.result.success?.form, ["property": "one"]) - } - - // MARK: Lifetime Events - - func testThatAutomaticallyResumedRequestReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 4 - - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidFinish = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatAutomaticallyAndManuallyResumedRequestReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 3 - - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidFinish = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - for _ in 0..<100 { - request.resume() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatManuallyResumedRequestReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 3 - - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidFinish = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - for _ in 0..<100 { - request.resume() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatRequestManuallyResumedManyTimesOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 3 - - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidFinish = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - for _ in 0..<100 { - request.resume() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatRequestManuallySuspendedManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 2 - - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - for _ in 0..<100 { - request.suspend() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .suspended) - } - - func testThatRequestManuallySuspendedManyTimesOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 2 - - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - for _ in 0..<100 { - request.suspend() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .suspended) - } - - func testThatRequestManuallyCancelledManyTimesAfterAutomaticResumeOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 2 - - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - // Cancellation stops task creation, so don't cancel the request until the task has been created. - eventMonitor.requestDidCreateTask = { _, _ in - for _ in 0..<100 { - request.cancel() - } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } - - func testThatRequestManuallyCancelledManyTimesOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 2 - - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - // Cancellation stops task creation, so don't cancel the request until the task has been created. - eventMonitor.requestDidCreateTask = { _, _ in - for _ in 0..<100 { - request.cancel() - } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } - - func testThatRequestManuallyCancelledManyTimesOnManyQueuesOnlyReceivesAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let expect = expectation(description: "request should receive appropriate lifetime events") - expect.expectedFulfillmentCount = 6 - - eventMonitor.requestDidCancelTask = { _, _ in expect.fulfill() } - eventMonitor.requestDidCancel = { _ in expect.fulfill() } - eventMonitor.requestDidResume = { _ in expect.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in expect.fulfill() } - // Fulfill other events that would exceed the expected count. Inverted expectations require the full timeout. - eventMonitor.requestDidSuspend = { _ in expect.fulfill() } - eventMonitor.requestDidSuspendTask = { _, _ in expect.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in expect.fulfill() } - // Cancellation stops task creation, so don't cancel the request until the task has been created. - eventMonitor.requestDidCreateTask = { _, _ in - DispatchQueue.concurrentPerform(iterations: 100) { i in - request.cancel() - - if i == 99 { expect.fulfill() } - } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } - - func testThatRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let didReceiveChallenge = expectation(description: "didReceiveChallenge should fire") - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didReceiveData = expectation(description: "didReceiveData should fire") - let willCacheResponse = expectation(description: "willCacheResponse should fire") - let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - var dataReceived = false - - eventMonitor.taskDidReceiveChallenge = { _, _, _ in didReceiveChallenge.fulfill() } - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.dataTaskDidReceiveData = { _, _, _ in - guard !dataReceived else { return } - // Data may be received many times, fulfill only once. - dataReceived = true - didReceiveData.fulfill() - } - eventMonitor.dataTaskWillCacheResponse = { _, _, _ in willCacheResponse.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() } - eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in - responseHandler.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatCancelledRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didCreateURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let didCancel = expectation(description: "didCancel should fire") - let didCancelTask = expectation(description: "didCancelTask should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() } - eventMonitor.requestDidCancel = { _ in didCancel.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() } - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()).response { _ in - responseHandler.fulfill() - } - - eventMonitor.requestDidResumeTask = { _, _ in - request.cancel() - didResumeTask.fulfill() - } - - request.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } - - func testThatAppendingResponseSerializerToCancelledRequestCallsCompletion() { - // Given - let session = Session() - - var response1: DataResponse? - var response2: DataResponse? - - let expect = expectation(description: "both response serializer completions should be called") - expect.expectedFulfillmentCount = 2 - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - - request.responseJSON { resp in - response1 = resp - expect.fulfill() - - request.responseJSON { resp in - response2 = resp - expect.fulfill() - } - } - - request.cancel() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(response1?.error?.isExplicitlyCancelledError, true) - XCTAssertEqual(response2?.error?.isExplicitlyCancelledError, true) - } - - func testThatAppendingResponseSerializerToCompletedRequestInsideCompletionResumesRequest() { - // Given - let session = Session() - - var response1: DataResponse? - var response2: DataResponse? - var response3: DataResponse? - - let expect = expectation(description: "all response serializer completions should be called") - expect.expectedFulfillmentCount = 3 - - // When - let request = session.request(URLRequest.makeHTTPBinRequest()) - - request.responseJSON { resp in - response1 = resp - expect.fulfill() - - request.responseJSON { resp in - response2 = resp - expect.fulfill() - - request.responseJSON { resp in - response3 = resp - expect.fulfill() - } - } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response1?.value) - XCTAssertNotNil(response2?.value) - XCTAssertNotNil(response3?.value) - } - - func testThatAppendingResponseSerializerToCompletedRequestOutsideCompletionResumesRequest() { - // Given - let session = Session() - let request = session.request(URLRequest.makeHTTPBinRequest()) - - var response1: DataResponse? - var response2: DataResponse? - var response3: DataResponse? - - // When - let expect1 = expectation(description: "response serializer 1 completion should be called") - request.responseJSON { response1 = $0; expect1.fulfill() } - waitForExpectations(timeout: timeout, handler: nil) - - let expect2 = expectation(description: "response serializer 2 completion should be called") - request.responseJSON { response2 = $0; expect2.fulfill() } - waitForExpectations(timeout: timeout, handler: nil) - - let expect3 = expectation(description: "response serializer 3 completion should be called") - request.responseJSON { response3 = $0; expect3.fulfill() } - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response1?.value) - XCTAssertNotNil(response2?.value) - XCTAssertNotNil(response3?.value) - } -} - -// MARK: - - -class RequestDescriptionTestCase: BaseTestCase { - func testRequestDescription() { - // Given - let urlString = "https://httpbin.org/get" - let manager = Session(startRequestsImmediately: false) - let request = manager.request(urlString) - - let expectation = self.expectation(description: "Request description should update: \(urlString)") - - var response: HTTPURLResponse? - - // When - request.response { resp in - response = resp.response - - expectation.fulfill() - }.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.description, "GET https://httpbin.org/get (\(response?.statusCode ?? -1))") - } -} - -// MARK: - - -final class RequestCURLDescriptionTestCase: BaseTestCase { - // MARK: Properties - - let manager: Session = { - let manager = Session() - - return manager - }() - - let managerWithAcceptLanguageHeader: Session = { - var headers = HTTPHeaders.default - headers["Accept-Language"] = "en-US" - - let configuration = URLSessionConfiguration.af.default - configuration.headers = headers - - let manager = Session(configuration: configuration) - - return manager - }() - - let managerWithContentTypeHeader: Session = { - var headers = HTTPHeaders.default - headers["Content-Type"] = "application/json" - - let configuration = URLSessionConfiguration.af.default - configuration.headers = headers - - let manager = Session(configuration: configuration) - - return manager - }() - - func managerWithCookie(_ cookie: HTTPCookie) -> Session { - let configuration = URLSessionConfiguration.af.default - configuration.httpCookieStorage?.setCookie(cookie) - - return Session(configuration: configuration) - } - - let managerDisallowingCookies: Session = { - let configuration = URLSessionConfiguration.af.default - configuration.httpShouldSetCookies = false - - let manager = Session(configuration: configuration) - - return manager - }() - - // MARK: Tests - - func testGETRequestCURLDescription() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should complete") - var components: [String]? - - // When - manager.request(urlString).cURLDescription { - components = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertTrue(components?.contains("-X") == true) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - } - - func testGETRequestCURLDescriptionSynchronous() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should complete") - var components: [String]? - var syncComponents: [String]? - - // When - let request = manager.request(urlString) - request.cURLDescription { - components = self.cURLCommandComponents(from: $0) - syncComponents = self.cURLCommandComponents(from: request.cURLDescription()) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertTrue(components?.contains("-X") == true) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - XCTAssertEqual(components?.sorted(), syncComponents?.sorted()) - } - - func testGETRequestCURLDescriptionCanBeRequestedManyTimes() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should complete") - var components: [String]? - var secondComponents: [String]? - - // When - let request = manager.request(urlString) - request.cURLDescription { - components = self.cURLCommandComponents(from: $0) - request.cURLDescription { - secondComponents = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - } - // Trigger the overwrite behavior. - request.cURLDescription { - components = self.cURLCommandComponents(from: $0) - request.cURLDescription { - secondComponents = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertTrue(components?.contains("-X") == true) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - XCTAssertEqual(components?.sorted(), secondComponents?.sorted()) - } - - func testGETRequestWithCustomHeaderCURLDescription() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should complete") - var cURLDescription: String? - - // When - let headers: HTTPHeaders = ["X-Custom-Header": "{\"key\": \"value\"}"] - manager.request(urlString, headers: headers).cURLDescription { - cURLDescription = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(cURLDescription?.range(of: "-H \"X-Custom-Header: {\\\"key\\\": \\\"value\\\"}\"")) - } - - func testGETRequestWithDuplicateHeadersDebugDescription() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should complete") - var cURLDescription: String? - var components: [String]? - - // When - let headers: HTTPHeaders = ["Accept-Language": "en-GB"] - managerWithAcceptLanguageHeader.request(urlString, headers: headers).cURLDescription { - components = self.cURLCommandComponents(from: $0) - cURLDescription = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertTrue(components?.contains("-X") == true) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - - let acceptLanguageCount = components?.filter { $0.contains("Accept-Language") }.count - XCTAssertEqual(acceptLanguageCount, 1, "command should contain a single Accept-Language header") - - XCTAssertNotNil(cURLDescription?.range(of: "-H \"Accept-Language: en-GB\"")) - } - - func testPOSTRequestCURLDescription() { - // Given - let urlString = "https://httpbin.org/post" - let expectation = self.expectation(description: "request should complete") - var components: [String]? - - // When - manager.request(urlString, method: .post).cURLDescription { - components = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertEqual(components?[3..<5], ["-X", "POST"]) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - } - - func testPOSTRequestWithJSONParametersCURLDescription() { - // Given - let urlString = "https://httpbin.org/post" - let expectation = self.expectation(description: "request should complete") - var cURLDescription: String? - var components: [String]? - - let parameters = ["foo": "bar", - "fo\"o": "b\"ar", - "f'oo": "ba'r"] - - // When - manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).cURLDescription { - components = self.cURLCommandComponents(from: $0) - cURLDescription = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertEqual(components?[3..<5], ["-X", "POST"]) - - XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: application/json\"")) - XCTAssertNotNil(cURLDescription?.range(of: "-d \"{")) - XCTAssertNotNil(cURLDescription?.range(of: "\\\"f'oo\\\":\\\"ba'r\\\"")) - XCTAssertNotNil(cURLDescription?.range(of: "\\\"fo\\\\\\\"o\\\":\\\"b\\\\\\\"ar\\\"")) - XCTAssertNotNil(cURLDescription?.range(of: "\\\"foo\\\":\\\"bar\\")) - - XCTAssertEqual(components?.last, "\"\(urlString)\"") - } - - func testPOSTRequestWithCookieCURLDescription() { - // Given - let urlString = "https://httpbin.org/post" - - let properties = [HTTPCookiePropertyKey.domain: "httpbin.org", - HTTPCookiePropertyKey.path: "/post", - HTTPCookiePropertyKey.name: "foo", - HTTPCookiePropertyKey.value: "bar"] - - let cookie = HTTPCookie(properties: properties)! - let cookieManager = managerWithCookie(cookie) - let expectation = self.expectation(description: "request should complete") - var components: [String]? - - // When - cookieManager.request(urlString, method: .post).cURLDescription { - components = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertEqual(components?[3..<5], ["-X", "POST"]) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - XCTAssertEqual(components?[5..<6], ["-b"]) - } - - func testPOSTRequestWithCookiesDisabledCURLDescriptionHasNoCookies() { - // Given - let urlString = "https://httpbin.org/post" - - let properties = [HTTPCookiePropertyKey.domain: "httpbin.org", - HTTPCookiePropertyKey.path: "/post", - HTTPCookiePropertyKey.name: "foo", - HTTPCookiePropertyKey.value: "bar"] - - let cookie = HTTPCookie(properties: properties)! - managerDisallowingCookies.session.configuration.httpCookieStorage?.setCookie(cookie) - let expectation = self.expectation(description: "request should complete") - var components: [String]? - - // When - managerDisallowingCookies.request(urlString, method: .post).cURLDescription { - components = self.cURLCommandComponents(from: $0) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - let cookieComponents = components?.filter { $0 == "-b" } - XCTAssertTrue(cookieComponents?.isEmpty == true) - } - - func testMultipartFormDataRequestWithDuplicateHeadersCURLDescriptionHasOneContentTypeHeader() { - // Given - let urlString = "https://httpbin.org/post" - let japaneseData = Data("日本語".utf8) - let expectation = self.expectation(description: "multipart form data encoding should succeed") - var cURLDescription: String? - var components: [String]? - - // When - managerWithContentTypeHeader.upload(multipartFormData: { data in - data.append(japaneseData, withName: "japanese") - }, to: urlString).cURLDescription { - components = self.cURLCommandComponents(from: $0) - cURLDescription = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(components?[0..<3], ["$", "curl", "-v"]) - XCTAssertTrue(components?.contains("-X") == true) - XCTAssertEqual(components?.last, "\"\(urlString)\"") - - let contentTypeCount = components?.filter { $0.contains("Content-Type") }.count - XCTAssertEqual(contentTypeCount, 1, "command should contain a single Content-Type header") - - XCTAssertNotNil(cURLDescription?.range(of: "-H \"Content-Type: multipart/form-data;")) - } - - func testThatRequestWithInvalidURLDebugDescription() { - // Given - let urlString = "invalid_url" - let expectation = self.expectation(description: "request should complete") - var cURLDescription: String? - - // When - manager.request(urlString).cURLDescription { - cURLDescription = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(cURLDescription, "debugDescription should not crash") - } - - // MARK: Test Helper Methods - - private func cURLCommandComponents(from cURLString: String) -> [String] { - return cURLString.components(separatedBy: .whitespacesAndNewlines) - .filter { $0 != "" && $0 != "\\" } - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-root-ca.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-root-ca.cer deleted file mode 100644 index b5ae743..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-root-ca.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca1.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca1.cer deleted file mode 100644 index 38596c5..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca1.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca2.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca2.cer deleted file mode 100644 index edd135c..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/alamofire-signing-ca2.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/expired.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/expired.cer deleted file mode 100644 index af5e484..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/expired.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/missing-dns-name-and-uri.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/missing-dns-name-and-uri.cer deleted file mode 100644 index 9e4ef3c..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/missing-dns-name-and-uri.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/multiple-dns-names.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/multiple-dns-names.cer deleted file mode 100644 index 39828eb..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/multiple-dns-names.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca1.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca1.cer deleted file mode 100644 index 1acfcfc..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca1.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca2.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca2.cer deleted file mode 100644 index 709889d..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/signed-by-ca2.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/test.alamofire.org.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/test.alamofire.org.cer deleted file mode 100644 index 01c404b..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/test.alamofire.org.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-dns-name.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-dns-name.cer deleted file mode 100644 index a5da56d..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-dns-name.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-uri.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-uri.cer deleted file mode 100644 index 80838d4..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/valid-uri.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/wildcard.alamofire.org.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/wildcard.alamofire.org.cer deleted file mode 100644 index 959a5d8..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/alamofire.org/wildcard.alamofire.org.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-1.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-1.cer deleted file mode 100644 index ad75f0f..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-1.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-2.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-2.cer deleted file mode 100644 index 7d7e8f2..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-intermediate-ca-2.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-leaf.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-leaf.cer deleted file mode 100644 index a82e960..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-leaf.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-root-ca.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-root-ca.cer deleted file mode 100644 index 8a99c54..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/expired.badssl.com/expired.badssl.com-root-ca.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.cer deleted file mode 100644 index a9a2bdb..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.cer and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.crt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.crt deleted file mode 100644 index a9a2bdb..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.crt and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.der b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.der deleted file mode 100644 index a9a2bdb..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certDER.der and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.cer b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.cer deleted file mode 100644 index d22b9ab..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.cer +++ /dev/null @@ -1,24 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID9DCCAtygAwIBAgIJAIqBVOBRW4qMMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV -BAYTAlVTMQswCQYDVQQIEwJDQTERMA8GA1UEBxMIQmVya2VsZXkxKjAoBgNVBAoT -IVRlc3RpbmcgQ2VydGlmaWNhdGVzIGluIEFsYW1vRmlyZTAeFw0xNTEyMTEwMjA5 -MDlaFw0xNjEyMTAwMjA5MDlaMFkxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTER -MA8GA1UEBxMIQmVya2VsZXkxKjAoBgNVBAoTIVRlc3RpbmcgQ2VydGlmaWNhdGVz -IGluIEFsYW1vRmlyZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJy9 -FTR4QzhYyo2v2yv8SwlBQ32MHQF8Ez1J+YBsyZjcTVOGJtyPxrbJxGuRhyDzKUqz -X/zTsT+JPvZQXXBmyq0l0DhCcK84cHyVLcdEAzukam85EpJRWzSg8kDKzuTx2oLk -X8Zdcj7EEtYWV/5+/YahM4tXYhg+Lqm6koJEVHMld6zfedC7HN+jsTb73IrAY0dd -BPl7WPgDIPEl0kcGI6F7NS0+CKsgX412E5+TGUkvA8VI+e9+cn/EXBdklVQQGSOu -rHpcoOi1VqnQI0hGXlFi4MpamwMG2yArIUU0TXZ7G+/AbUYiGdB6ogvg5UTCfyZy -UXVljSJyzYmLs7hXQK8CAwEAAaOBvjCBuzAdBgNVHQ4EFgQU9EaWHrJGYvpCEW5f -CUEMRk9DlN8wgYsGA1UdIwSBgzCBgIAU9EaWHrJGYvpCEW5fCUEMRk9DlN+hXaRb -MFkxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTERMA8GA1UEBxMIQmVya2VsZXkx -KjAoBgNVBAoTIVRlc3RpbmcgQ2VydGlmaWNhdGVzIGluIEFsYW1vRmlyZYIJAIqB -VOBRW4qMMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAEeHeXNZGHJW -VImbOHrYmSsZ5jFnzjGw8ynkOrcoJzaxg3OHoo/pNCQ7KcrIa5YPNFiNoaSa/Lzn -LBt6HkM1Vi1rMaERHLWp/W5ruInCu4CuVtQshdNcOEofJ03wdrQylOBZq8MZkTVn -NcqUFg/sBANM/9WhafVi7XaUjWl+V7ZnzdbKP/ywvsiJ+wyKMA7Wt19HMrV2dTBz -CD4vxpwOBev0oTp2NvAHdgNkeK52skHoz+MY8uivVJQr4hqLYJPXUyAcVZCaqeK/ -hxDkbRo6eZsYcjTRqMKtGMVjHHd8alXcVJwcuWkhUYxy8jRf0kFj/9mMie9jRokJ -ovKLbNJfEbI= ------END CERTIFICATE----- diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.crt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.crt deleted file mode 100644 index d22b9ab..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/certPEM.crt +++ /dev/null @@ -1,24 +0,0 @@ ------BEGIN CERTIFICATE----- -MIID9DCCAtygAwIBAgIJAIqBVOBRW4qMMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV -BAYTAlVTMQswCQYDVQQIEwJDQTERMA8GA1UEBxMIQmVya2VsZXkxKjAoBgNVBAoT -IVRlc3RpbmcgQ2VydGlmaWNhdGVzIGluIEFsYW1vRmlyZTAeFw0xNTEyMTEwMjA5 -MDlaFw0xNjEyMTAwMjA5MDlaMFkxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTER -MA8GA1UEBxMIQmVya2VsZXkxKjAoBgNVBAoTIVRlc3RpbmcgQ2VydGlmaWNhdGVz -IGluIEFsYW1vRmlyZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJy9 -FTR4QzhYyo2v2yv8SwlBQ32MHQF8Ez1J+YBsyZjcTVOGJtyPxrbJxGuRhyDzKUqz -X/zTsT+JPvZQXXBmyq0l0DhCcK84cHyVLcdEAzukam85EpJRWzSg8kDKzuTx2oLk -X8Zdcj7EEtYWV/5+/YahM4tXYhg+Lqm6koJEVHMld6zfedC7HN+jsTb73IrAY0dd -BPl7WPgDIPEl0kcGI6F7NS0+CKsgX412E5+TGUkvA8VI+e9+cn/EXBdklVQQGSOu -rHpcoOi1VqnQI0hGXlFi4MpamwMG2yArIUU0TXZ7G+/AbUYiGdB6ogvg5UTCfyZy -UXVljSJyzYmLs7hXQK8CAwEAAaOBvjCBuzAdBgNVHQ4EFgQU9EaWHrJGYvpCEW5f -CUEMRk9DlN8wgYsGA1UdIwSBgzCBgIAU9EaWHrJGYvpCEW5fCUEMRk9DlN+hXaRb -MFkxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTERMA8GA1UEBxMIQmVya2VsZXkx -KjAoBgNVBAoTIVRlc3RpbmcgQ2VydGlmaWNhdGVzIGluIEFsYW1vRmlyZYIJAIqB -VOBRW4qMMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAEeHeXNZGHJW -VImbOHrYmSsZ5jFnzjGw8ynkOrcoJzaxg3OHoo/pNCQ7KcrIa5YPNFiNoaSa/Lzn -LBt6HkM1Vi1rMaERHLWp/W5ruInCu4CuVtQshdNcOEofJ03wdrQylOBZq8MZkTVn -NcqUFg/sBANM/9WhafVi7XaUjWl+V7ZnzdbKP/ywvsiJ+wyKMA7Wt19HMrV2dTBz -CD4vxpwOBev0oTp2NvAHdgNkeK52skHoz+MY8uivVJQr4hqLYJPXUyAcVZCaqeK/ -hxDkbRo6eZsYcjTRqMKtGMVjHHd8alXcVJwcuWkhUYxy8jRf0kFj/9mMie9jRokJ -ovKLbNJfEbI= ------END CERTIFICATE----- diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/keyDER.der b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/keyDER.der deleted file mode 100644 index 969657d..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/keyDER.der and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/randomGibberish.crt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/randomGibberish.crt deleted file mode 100644 index 23d1360..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Certificates/selfSignedAndMalformedCerts/randomGibberish.crt and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/rainbow.jpg b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/rainbow.jpg deleted file mode 100644 index 9122468..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/rainbow.jpg and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/unicorn.png b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/unicorn.png deleted file mode 100644 index bc504e5..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Images/unicorn.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/empty_data.json b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/empty_data.json deleted file mode 100644 index e69de29..0000000 diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/invalid_data.json b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/invalid_data.json deleted file mode 100644 index 88a123a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/invalid_data.json +++ /dev/null @@ -1,6 +0,0 @@ -this is not going -"to" be happy json -data at all -{ - "10": whoops -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/valid_data.json b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/valid_data.json deleted file mode 100644 index 39a30eb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/JSON/valid_data.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "team": "royals", - "score": 23 -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/empty_string.txt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/empty_string.txt deleted file mode 100644 index e69de29..0000000 diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf32_string.txt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf32_string.txt deleted file mode 100644 index 3a4a280..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf32_string.txt and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf8_string.txt b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf8_string.txt deleted file mode 100644 index eb2348c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Resources/Responses/String/utf8_string.txt +++ /dev/null @@ -1 +0,0 @@ -random data \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseSerializationTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseSerializationTests.swift deleted file mode 100644 index b1644e0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseSerializationTests.swift +++ /dev/null @@ -1,1267 +0,0 @@ -// -// ResponseSerializationTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -final class DataResponseSerializationTestCase: BaseTestCase { - // MARK: Properties - - private let error = AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - - // MARK: DataResponseSerializer - - func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() { - // Given - let serializer = DataResponseSerializer() - let data = Data("data".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDataResponseSerializerFailsWhenDataIsNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDataResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDataResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure, "result is failure should be true") - XCTAssertNil(result.success, "result value should be nil") - XCTAssertNotNil(result.failure, "result error should not be nil") - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDataResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd204ResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success?.count, 0) - } - - func testThatDataResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd205ResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success?.count, 0) - } - - func testThatDataResponseSerializerSucceedsWhenDataIsNilWithHEADRequestAnd200ResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let request = URLRequest.make(method: .head) - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success?.count, 0) - } - - // MARK: StringResponseSerializer - - func testThatStringResponseSerializerFailsWhenDataIsNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatStringResponseSerializerFailsWhenDataIsEmpty() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: Data(), error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() { - let serializer = StringResponseSerializer() - let data = Data("data".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() { - let serializer = StringResponseSerializer(encoding: .utf8) - let data = Data("data".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() { - let serializer = StringResponseSerializer() - let data = Data("data".utf8) - let response = HTTPURLResponse(statusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() { - // Given - let serializer = StringResponseSerializer(encoding: .utf8) - let data = "random data".data(using: .utf32)! - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isStringSerializationFailed, true) - XCTAssertEqual(result.failure?.asAFError?.failedStringEncoding, .utf8) - } - - func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() { - // Given - let serializer = StringResponseSerializer() - let data = "random data".data(using: .utf32)! - let response = HTTPURLResponse(statusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isStringSerializationFailed, true) - XCTAssertEqual(result.failure?.asAFError?.failedStringEncoding, .utf8) - } - - func testThatStringResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatStringResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd204ResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success, "") - } - - func testThatStringResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd205ResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success, "") - } - - func testThatStringResponseSerializerSucceedsWhenDataIsNilWithHEADRequestAnd200ResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let request = URLRequest.make(method: .head) - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success, "") - } - - // MARK: JSONResponseSerializer - - func testThatJSONResponseSerializerFailsWhenDataIsNil() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatJSONResponseSerializerFailsWhenDataIsEmpty() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: Data(), error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() { - // Given - let serializer = JSONResponseSerializer() - let data = Data("{\"json\": true}".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() { - // Given - let serializer = JSONResponseSerializer() - let data = Data("definitely not valid json".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isJSONSerializationFailed, true) - XCTAssertEqual((result.failure?.asAFError?.underlyingError as? CocoaError)?.code, .propertyListReadCorrupt) - } - - func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatJSONResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd204ResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success as? NSNull, NSNull()) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd205ResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success as? NSNull, NSNull()) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithHEADRequestAnd200ResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let request = URLRequest.make(method: .head) - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success as? NSNull, NSNull()) - } -} - -// MARK: - - -// used by testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseConformingTypeAndEmptyResponseStatusCode -extension Bool: EmptyResponse { - public static func emptyValue() -> Bool { - return true - } -} - -final class DecodableResponseSerializerTests: BaseTestCase { - private let error = AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - - struct DecodableValue: Decodable, EmptyResponse { - static func emptyValue() -> DecodableValue { - return DecodableValue(string: "") - } - - let string: String - } - - func testThatDecodableResponseSerializerFailsWhenDataIsNil() { - // Given - let serializer = DecodableResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDecodableResponseSerializerFailsWhenDataIsEmpty() { - // Given - let serializer = DecodableResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: Data(), error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsValidJSON() { - // Given - let data = Data("{\"string\":\"string\"}".utf8) - let serializer = DecodableResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertEqual(result.success?.string, "string") - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerFailsWhenDataIsInvalidRepresentation() { - // Given - let serializer = DecodableResponseSerializer() - let data = Data("definitely not valid".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - } - - func testThatDecodableResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = DecodableResponseSerializer() - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDecodableResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithEmptyTypeAndEmptyResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd204ResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithGETRequestAnd205ResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let request = URLRequest.make(method: .get) - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithHEADRequestAnd200ResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let request = URLRequest.make(method: .head) - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serialize(request: request, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseConformingTypeAndEmptyResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerFailsWhenDataIsNilWithEmptyResponseNonconformingTypeAndEmptyResponseStatusCode() { - // Given - let serializer = DecodableResponseSerializer() - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serialize(request: nil, response: response, data: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInvalidEmptyResponse, true) - } -} - -// MARK: - - -final class DownloadResponseSerializationTestCase: BaseTestCase { - // MARK: Properties - - private let error = AFError.responseSerializationFailed(reason: .inputFileNil) - - private var jsonEmptyDataFileURL: URL { return url(forResource: "empty_data", withExtension: "json") } - private var jsonValidDataFileURL: URL { return url(forResource: "valid_data", withExtension: "json") } - private var jsonInvalidDataFileURL: URL { return url(forResource: "invalid_data", withExtension: "json") } - - private var stringEmptyDataFileURL: URL { return url(forResource: "empty_string", withExtension: "txt") } - private var stringUTF8DataFileURL: URL { return url(forResource: "utf8_string", withExtension: "txt") } - private var stringUTF32DataFileURL: URL { return url(forResource: "utf32_string", withExtension: "txt") } - - private var invalidFileURL: URL { return URL(fileURLWithPath: "/this/file/does/not/exist.txt") } - - // MARK: Tests - Data Response Serializer - - func testThatDataResponseSerializerSucceedsWhenFileDataIsNotNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: jsonValidDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatDataResponseSerializerFailsWhenFileDataIsEmpty() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: jsonEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatDataResponseSerializerFailsWhenFileURLIsNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatDataResponseSerializerFailsWhenFileURLIsInvalid() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: invalidFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileReadFailed, true) - } - - func testThatDataResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = DataResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatDataResponseSerializerFailsWhenFileURLIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatDataResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { - // Given - let serializer = DataResponseSerializer() - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: jsonEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success?.count, 0) - } - - // MARK: Tests - String Response Serializer - - func testThatStringResponseSerializerFailsWhenFileURLIsNil() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatStringResponseSerializerFailsWhenFileURLIsInvalid() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: invalidFileURL, error: nil) } - - // Then - XCTAssertEqual(result.isSuccess, false) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileReadFailed, true) - } - - func testThatStringResponseSerializerFailsWhenFileDataIsEmpty() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: stringEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: stringUTF8DataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() { - // Given - let serializer = StringResponseSerializer(encoding: .utf8) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: stringUTF8DataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() { - // Given - let serializer = StringResponseSerializer() - let response = HTTPURLResponse(statusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: stringUTF8DataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() { - // Given - let serializer = StringResponseSerializer(encoding: .utf8) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: stringUTF32DataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isStringSerializationFailed, true) - XCTAssertEqual(result.failure?.asAFError?.failedStringEncoding, .utf8) - } - - func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() { - // Given - let serializer = StringResponseSerializer() - let response = HTTPURLResponse(statusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: stringUTF32DataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isStringSerializationFailed, true) - XCTAssertEqual(result.failure?.asAFError?.failedStringEncoding, .utf8) - } - - func testThatStringResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = StringResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatStringResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { - // Given - let serializer = StringResponseSerializer() - let response = HTTPURLResponse(statusCode: 204) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: stringEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - XCTAssertEqual(result.success, "") - } - - // MARK: Tests - JSON Response Serializer - - func testThatJSONResponseSerializerFailsWhenFileURLIsNil() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatJSONResponseSerializerFailsWhenFileURLIsInvalid() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: invalidFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileReadFailed, true) - } - - func testThatJSONResponseSerializerFailsWhenFileDataIsEmpty() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: jsonEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputDataNilOrZeroLength, true) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: jsonValidDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - } - - func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: jsonInvalidDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isJSONSerializationFailed, true) - XCTAssertEqual((result.failure?.asAFError?.underlyingError as? CocoaError)?.code, .propertyListReadCorrupt) - } - - func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() { - // Given - let serializer = JSONResponseSerializer() - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: nil, fileURL: nil, error: error) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatJSONResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let response = HTTPURLResponse(statusCode: 200) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: nil, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - XCTAssertEqual(result.failure?.asAFError?.isInputFileNil, true) - } - - func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { - // Given - let serializer = JSONResponseSerializer() - let response = HTTPURLResponse(statusCode: 205) - - // When - let result = Result { try serializer.serializeDownload(request: nil, response: response, fileURL: jsonEmptyDataFileURL, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertNotNil(result.success) - XCTAssertNil(result.failure) - - XCTAssertEqual(result.success as? NSNull, NSNull()) - } -} - -final class CustomResponseSerializerTests: BaseTestCase { - func testThatCustomResponseSerializersCanBeWrittenWithoutCompilerIssues() { - // Given - final class UselessResponseSerializer: ResponseSerializer { - func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data? { - return data - } - } - let serializer = UselessResponseSerializer() - let expectation = self.expectation(description: "request should finish") - var data: Data? - - // When - AF.request(URLRequest.makeHTTPBinRequest()).response(responseSerializer: serializer) { response in - data = response.data - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(data) - } -} - -final class DataPreprocessorSerializationTests: BaseTestCase { - struct DropFirst: DataPreprocessor { - func preprocess(_ data: Data) throws -> Data { - return data.dropFirst() - } - } - - struct Throwing: DataPreprocessor { - struct Error: Swift.Error {} - - func preprocess(_ data: Data) throws -> Data { - throw Error() - } - } - - func testThatDataResponseSerializerProperlyCallsSuccessfulDataPreprocessor() { - // Given - let preprocessor = DropFirst() - let serializer = DataResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("abcd".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertEqual(result.success, Data("bcd".utf8)) - XCTAssertNil(result.failure) - } - - func testThatDataResponseSerializerProperlyReceivesErrorFromFailingDataPreprocessor() { - // Given - let preprocessor = Throwing() - let serializer = DataResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("abcd".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - } - - func testThatStringResponseSerializerProperlyCallsSuccessfulDataPreprocessor() { - // Given - let preprocessor = DropFirst() - let serializer = StringResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("abcd".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertEqual(result.success, "bcd") - XCTAssertNil(result.failure) - } - - func testThatStringResponseSerializerProperlyReceivesErrorFromFailingDataPreprocessor() { - // Given - let preprocessor = Throwing() - let serializer = StringResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("abcd".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - } - - func testThatJSONResponseSerializerProperlyCallsSuccessfulDataPreprocessor() { - // Given - let preprocessor = DropFirst() - let serializer = JSONResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("1\"abcd\"".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertEqual(result.success as? String, "abcd") - XCTAssertNil(result.failure) - } - - func testThatJSONResponseSerializerProperlyReceivesErrorFromFailingDataPreprocessor() { - // Given - let preprocessor = Throwing() - let serializer = JSONResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("1\"abcd\"".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - } - - func testThatDecodableResponseSerializerProperlyCallsSuccessfulDataPreprocessor() { - // Given - let preprocessor = DropFirst() - let serializer = DecodableResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("1{\"string\":\"string\"}".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isSuccess) - XCTAssertEqual(result.success?.string, "string") - XCTAssertNil(result.failure) - } - - func testThatDecodableResponseSerializerProperlyReceivesErrorFromFailingDataPreprocessor() { - // Given - let preprocessor = Throwing() - let serializer = DecodableResponseSerializer(dataPreprocessor: preprocessor) - let data = Data("1{\"string\":\"string\"}".utf8) - - // When - let result = Result { try serializer.serialize(request: nil, response: nil, data: data, error: nil) } - - // Then - XCTAssertTrue(result.isFailure) - XCTAssertNil(result.success) - XCTAssertNotNil(result.failure) - } -} - -final class DataPreprocessorTests: BaseTestCase { - func testThatPassthroughPreprocessorPassesDataThrough() { - // Given - let preprocessor = PassthroughPreprocessor() - let data = Data("data".utf8) - - // When - let result = Result { try preprocessor.preprocess(data) } - - // Then - XCTAssertEqual(data, result.success, "Preprocessed data should equal original data.") - } - - func testThatGoogleXSSIPreprocessorProperlyPreprocessesData() { - // Given - let preprocessor = GoogleXSSIPreprocessor() - let data = Data(")]}',\nabcd".utf8) - - // When - let result = Result { try preprocessor.preprocess(data) } - - // Then - XCTAssertEqual(result.success.map { String(decoding: $0, as: UTF8.self) }, "abcd") - } - - func testThatGoogleXSSIPreprocessorDoesNotChangeDataIfPrefixDoesNotMatch() { - // Given - let preprocessor = GoogleXSSIPreprocessor() - let data = Data("abcd".utf8) - - // When - let result = Result { try preprocessor.preprocess(data) } - - // Then - XCTAssertEqual(result.success.map { String(decoding: $0, as: UTF8.self) }, "abcd") - } -} - -extension HTTPURLResponse { - convenience init(statusCode: Int, headers: HTTPHeaders? = nil) { - let url = URL(string: "https://httpbin.org/get")! - self.init(url: url, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers?.dictionary)! - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseTests.swift deleted file mode 100644 index 8ccc2e1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ResponseTests.swift +++ /dev/null @@ -1,679 +0,0 @@ -// -// ResponseTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -final class ResponseTestCase: BaseTestCase { - func testThatResponseReturnsSuccessResultWithValidData() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseReturnsFailureResultWithOptionalDataAndError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with invalid hostname error") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseDataTestCase: BaseTestCase { - func testThatResponseDataReturnsSuccessResultWithValidData() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseData { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseDataReturnsFailureResultWithOptionalDataAndError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseData { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseStringTestCase: BaseTestCase { - func testThatResponseStringReturnsSuccessResultWithValidString() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseString { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseString { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseJSONTestCase: BaseTestCase { - func testThatResponseJSONReturnsSuccessResultWithValidJSON() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseJSONReturnsSuccessResultForGETRequest() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - - if - let responseDictionary = response?.result.success as? [String: Any], - let args = responseDictionary["args"] as? [String: String] { - XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") - } else { - XCTFail("args should not be nil") - } - } - - func testThatResponseJSONReturnsSuccessResultForPOSTRequest() { - // Given - let urlString = "https://httpbin.org/post" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, method: .post, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - - if - let responseDictionary = response?.result.success as? [String: Any], - let form = responseDictionary["form"] as? [String: String] { - XCTAssertEqual(form, ["foo": "bar"], "form should match parameters") - } else { - XCTFail("form should not be nil") - } - } -} - -final class ResponseJSONDecodableTestCase: BaseTestCase { - func testThatResponseDecodableReturnsSuccessResultWithValidJSON() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: [:]).responseDecodable(of: HTTPBinResponse.self) { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(response?.result.success?.url, "https://httpbin.org/get") - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseDecodableWithPassedTypeReturnsSuccessResultWithValidJSON() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: [:]).responseDecodable(of: HTTPBinResponse.self) { - response = $0 - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(response?.result.success?.url, "https://httpbin.org/get") - XCTAssertNotNil(response?.metrics) - } - - func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: [:]).responseDecodable(of: HTTPBinResponse.self) { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseMapTestCase: BaseTestCase { - func testThatMapTransformsSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.map { json in - // json["args"]["foo"] is "bar": use this invariant to test the map function - ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(response?.result.success, "bar") - XCTAssertNotNil(response?.metrics) - } - - func testThatMapPreservesFailureError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseData { resp in - response = resp.map { _ in "ignored" } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseTryMapTestCase: BaseTestCase { - func testThatTryMapTransformsSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in - response = resp.tryMap { json in - // json["args"]["foo"] is "bar": use this invariant to test the tryMap function - ((json as? [String: Any])?["args"] as? [String: Any])?["foo"] as? String ?? "invalid" - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(response?.result.success, "bar") - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapCatchesTransformationError() { - // Given - struct TransformError: Error {} - - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseData { resp in - response = resp.tryMap { _ in - throw TransformError() - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - - if let error = response?.result.failure { - XCTAssertTrue(error is TransformError) - } else { - XCTFail("tryMap should catch the transformation error") - } - - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapPreservesFailureError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail with 404") - - var response: DataResponse? - - // When - AF.request(urlString, parameters: ["foo": "bar"]).responseData { resp in - response = resp.tryMap { _ in "ignored" } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.asAFError?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -enum TestError: Error { - case error(error: AFError) -} - -enum TransformationError: Error { - case error - - func alwaysFails() throws -> TestError { - throw TransformationError.error - } -} - -final class ResponseMapErrorTestCase: BaseTestCase { - func testThatMapErrorTransformsFailureValue() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should not succeed") - - var response: DataResponse? - - // When - AF.request(urlString).responseJSON { resp in - response = resp.mapError { error in - TestError.error(error: error) - } - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - guard let error = response?.error, case .error = error else { XCTFail(); return } - - XCTAssertNotNil(response?.metrics) - } - - func testThatMapErrorPreservesSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString).responseData { resp in - response = resp.mapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } -} - -// MARK: - - -final class ResponseTryMapErrorTestCase: BaseTestCase { - func testThatTryMapErrorPreservesSuccessValue() { - // Given - let urlString = "https://httpbin.org/get" - let expectation = self.expectation(description: "request should succeed") - - var response: DataResponse? - - // When - AF.request(urlString).responseData { resp in - response = resp.tryMapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapErrorCatchesTransformationError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DataResponse? - - // When - AF.request(urlString).responseData { resp in - response = resp.tryMapError { _ in try TransformationError.error.alwaysFails() } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - - if let error = response?.result.failure { - XCTAssertTrue(error is TransformationError) - } else { - XCTFail("tryMapError should catch the transformation error") - } - - XCTAssertNotNil(response?.metrics) - } - - func testThatTryMapErrorTransformsError() { - // Given - let urlString = "https://invalid-url-here.org/this/does/not/exist" - let expectation = self.expectation(description: "request should fail") - - var response: DataResponse? - - // When - AF.request(urlString).responseData { resp in - response = resp.tryMapError { TestError.error(error: $0) } - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertEqual(response?.result.isFailure, true) - - guard let error = response?.error as? TestError, - case let .error(underlyingError) = error - else { XCTFail(); return } - - XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) - XCTAssertEqual((underlyingError.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - - XCTAssertNotNil(response?.metrics) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Result+Alamofire.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/Result+Alamofire.swift deleted file mode 100644 index 18bbec8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/Result+Alamofire.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// Result+Alamofire.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Result { - var isSuccess: Bool { - guard case .success = self else { return false } - return true - } - - var isFailure: Bool { - return !isSuccess - } - - var success: Success? { - guard case let .success(value) = self else { return nil } - return value - } - - var failure: Failure? { - guard case let .failure(error) = self else { return nil } - return error - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RetryPolicyTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/RetryPolicyTests.swift deleted file mode 100644 index 06e3729..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/RetryPolicyTests.swift +++ /dev/null @@ -1,389 +0,0 @@ -// -// RetryPolicyTests.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import XCTest - -class BaseRetryPolicyTestCase: BaseTestCase { - // MARK: Helper Types - - class StubRequest: DataRequest { - let urlRequest: URLRequest - override var request: URLRequest? { return urlRequest } - - let mockedResponse: HTTPURLResponse? - override var response: HTTPURLResponse? { return mockedResponse } - - init(_ url: URL, method: HTTPMethod, response: HTTPURLResponse?, session: Session) { - mockedResponse = response - - let request = Session.RequestConvertible(url: url, - method: method, - parameters: nil, - encoding: URLEncoding.default, - headers: nil) - - urlRequest = try! request.asURLRequest() - - super.init(convertible: request, - underlyingQueue: session.rootQueue, - serializationQueue: session.serializationQueue, - eventMonitor: session.eventMonitor, - interceptor: nil, - delegate: session) - } - } - - // MARK: Properties - - let idempotentMethods: Set = [.get, .head, .put, .delete, .options, .trace] - let nonIdempotentMethods: Set = [.post, .patch, .connect] - var methods: Set { return idempotentMethods.union(nonIdempotentMethods) } - - let session = Session(startRequestsImmediately: false) - - let url = URL(string: "https://api.alamofire.org")! - let connectionLostError = NSError(domain: URLError.errorDomain, code: URLError.networkConnectionLost.rawValue, userInfo: nil) - let resourceUnavailableError = NSError(domain: URLError.errorDomain, code: URLError.resourceUnavailable.rawValue, userInfo: nil) - let unknownError = NSError(domain: URLError.errorDomain, code: URLError.unknown.rawValue, userInfo: nil) - - let retryableStatusCodes: Set = [408, 500, 502, 503, 504] - - let retryableErrorCodes: Set = [.backgroundSessionInUseByAnotherProcess, - .backgroundSessionWasDisconnected, - .badServerResponse, - .callIsActive, - .cannotConnectToHost, - .cannotFindHost, - .cannotLoadFromNetwork, - .dataNotAllowed, - .dnsLookupFailed, - .downloadDecodingFailedMidStream, - .downloadDecodingFailedToComplete, - .internationalRoamingOff, - .networkConnectionLost, - .notConnectedToInternet, - .secureConnectionFailed, - .serverCertificateHasBadDate, - .serverCertificateNotYetValid, - .timedOut] - - let nonRetryableErrorCodes: Set = [.appTransportSecurityRequiresSecureConnection, - .backgroundSessionRequiresSharedContainer, - .badURL, - .cancelled, - .cannotCloseFile, - .cannotCreateFile, - .cannotDecodeContentData, - .cannotDecodeRawData, - .cannotMoveFile, - .cannotOpenFile, - .cannotParseResponse, - .cannotRemoveFile, - .cannotWriteToFile, - .clientCertificateRejected, - .clientCertificateRequired, - .dataLengthExceedsMaximum, - .fileDoesNotExist, - .fileIsDirectory, - .httpTooManyRedirects, - .noPermissionsToReadFile, - .redirectToNonExistentLocation, - .requestBodyStreamExhausted, - .resourceUnavailable, - .serverCertificateHasUnknownRoot, - .serverCertificateUntrusted, - .unknown, - .unsupportedURL, - .userAuthenticationRequired, - .userCancelledAuthentication, - .zeroByteResource] - - var errorCodes: Set { - return retryableErrorCodes.union(nonRetryableErrorCodes) - } -} - -// MARK: - - -class RetryPolicyTestCase: BaseRetryPolicyTestCase { - // MARK: Tests - Retry - - func testThatRetryPolicyRetriesRequestsBelowRetryLimit() { - // Given - let retryPolicy = RetryPolicy() - let request = self.request(method: .get) - - var results: [Int: RetryResult] = [:] - - // When - for index in 0...2 { - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: connectionLostError) { result in - results[index] = result - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - request.prepareForRetry() - } - - // Then - XCTAssertEqual(results.count, 3) - - if results.count == 3 { - XCTAssertEqual(results[0]?.retryRequired, true) - XCTAssertEqual(results[0]?.delay, 0.5) - XCTAssertNil(results[0]?.error) - - XCTAssertEqual(results[1]?.retryRequired, true) - XCTAssertEqual(results[1]?.delay, 1.0) - XCTAssertNil(results[1]?.error) - - XCTAssertEqual(results[2]?.retryRequired, false) - XCTAssertNil(results[2]?.delay) - XCTAssertNil(results[2]?.error) - } - } - - func testThatRetryPolicyRetriesIdempotentRequests() { - // Given - let retryPolicy = RetryPolicy() - var results: [HTTPMethod: RetryResult] = [:] - - // When - for method in methods { - let request = self.request(method: method) - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: connectionLostError) { result in - results[method] = result - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - } - - // Then - XCTAssertEqual(results.count, methods.count) - - for (method, result) in results { - XCTAssertEqual(result.retryRequired, idempotentMethods.contains(method)) - XCTAssertEqual(result.delay, result.retryRequired ? 0.5 : nil) - XCTAssertNil(result.error) - } - } - - func testThatRetryPolicyRetriesRequestsWithRetryableStatusCodes() { - // Given - let retryPolicy = RetryPolicy() - let statusCodes = Set(100...599) - var results: [Int: RetryResult] = [:] - - // When - for statusCode in statusCodes { - let request = self.request(method: .get, statusCode: statusCode) - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: unknownError) { result in - results[statusCode] = result - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - } - - // Then - XCTAssertEqual(results.count, statusCodes.count) - - for (statusCode, result) in results { - XCTAssertEqual(result.retryRequired, retryableStatusCodes.contains(statusCode)) - XCTAssertEqual(result.delay, result.retryRequired ? 0.5 : nil) - XCTAssertNil(result.error) - } - } - - func testThatRetryPolicyRetriesRequestsWithRetryableErrors() { - // Given - let retryPolicy = RetryPolicy() - var results: [URLError.Code: RetryResult] = [:] - - // When - for code in errorCodes { - let request = self.request(method: .get) - let error = urlError(with: code) - - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: error) { result in - results[code] = result - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - } - - // Then - XCTAssertEqual(results.count, errorCodes.count) - - for (urlErrorCode, result) in results { - XCTAssertEqual(result.retryRequired, retryableErrorCodes.contains(urlErrorCode)) - XCTAssertEqual(result.delay, result.retryRequired ? 0.5 : nil) - XCTAssertNil(result.error) - } - } - - func testThatRetryPolicyDoesNotRetryErrorsThatAreNotURLErrors() { - // Given - let retryPolicy = RetryPolicy() - let request = self.request(method: .get) - - let errors: [Error] = [resourceUnavailableError, - unknownError] - - var results: [RetryResult] = [] - - // When - for error in errors { - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: error) { result in - results.append(result) - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - } - - // Then - XCTAssertEqual(results.count, errors.count) - - for result in results { - XCTAssertEqual(result.retryRequired, false) - XCTAssertNil(result.delay) - XCTAssertNil(result.error) - } - } - - // MARK: Tests - Exponential Backoff - - func testThatRetryPolicyTimeDelayBacksOffExponentially() { - // Given - let retryPolicy = RetryPolicy(retryLimit: 4) - let request = self.request(method: .get) - - var results: [Int: RetryResult] = [:] - - // When - for index in 0...4 { - let expectation = self.expectation(description: "retry policy should complete") - - retryPolicy.retry(request, for: session, dueTo: connectionLostError) { result in - results[index] = result - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - request.prepareForRetry() - } - - // Then - XCTAssertEqual(results.count, 5) - - if results.count == 5 { - XCTAssertEqual(results[0]?.retryRequired, true) - XCTAssertEqual(results[0]?.delay, 0.5) - XCTAssertNil(results[0]?.error) - - XCTAssertEqual(results[1]?.retryRequired, true) - XCTAssertEqual(results[1]?.delay, 1.0) - XCTAssertNil(results[1]?.error) - - XCTAssertEqual(results[2]?.retryRequired, true) - XCTAssertEqual(results[2]?.delay, 2.0) - XCTAssertNil(results[2]?.error) - - XCTAssertEqual(results[3]?.retryRequired, true) - XCTAssertEqual(results[3]?.delay, 4.0) - XCTAssertNil(results[3]?.error) - - XCTAssertEqual(results[4]?.retryRequired, false) - XCTAssertNil(results[4]?.delay) - XCTAssertNil(results[4]?.error) - } - } - - // MARK: Test Helpers - - func request(method: HTTPMethod = .get, statusCode: Int? = nil) -> Request { - var response: HTTPURLResponse? - - if let statusCode = statusCode { - response = HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: nil, headerFields: nil) - } - - return StubRequest(url, method: method, response: response, session: session) - } - - func urlError(with code: URLError.Code) -> URLError { - return NSError(domain: URLError.errorDomain, code: code.rawValue, userInfo: nil) as! URLError - } -} - -// MARK: - - -class ConnectionLostRetryPolicyTestCase: BaseRetryPolicyTestCase { - func testThatConnectionLostRetryPolicyCanBeInitializedWithDefaultValues() { - // Given, When - let retryPolicy = ConnectionLostRetryPolicy() - - // Then - XCTAssertEqual(retryPolicy.retryLimit, 2) - XCTAssertEqual(retryPolicy.exponentialBackoffBase, 2) - XCTAssertEqual(retryPolicy.exponentialBackoffScale, 0.5) - XCTAssertEqual(retryPolicy.retryableHTTPMethods, idempotentMethods) - XCTAssertEqual(retryPolicy.retryableHTTPStatusCodes, []) - XCTAssertEqual(retryPolicy.retryableURLErrorCodes, [.networkConnectionLost]) - } - - func testThatConnectionLostRetryPolicyCanBeInitializedWithCustomValues() { - // Given, When - let retryPolicy = ConnectionLostRetryPolicy(retryLimit: 3, - exponentialBackoffBase: 4, - exponentialBackoffScale: 0.25, - retryableHTTPMethods: [.delete, .get]) - - // Then - XCTAssertEqual(retryPolicy.retryLimit, 3) - XCTAssertEqual(retryPolicy.exponentialBackoffBase, 4) - XCTAssertEqual(retryPolicy.exponentialBackoffScale, 0.25) - XCTAssertEqual(retryPolicy.retryableHTTPMethods, [.delete, .get]) - XCTAssertEqual(retryPolicy.retryableHTTPStatusCodes, []) - XCTAssertEqual(retryPolicy.retryableURLErrorCodes, [.networkConnectionLost]) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ServerTrustEvaluatorTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ServerTrustEvaluatorTests.swift deleted file mode 100644 index 4695564..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ServerTrustEvaluatorTests.swift +++ /dev/null @@ -1,1413 +0,0 @@ -// -// ServerTrustPolicyTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -private struct TestCertificates { - // Root Certificates - static let rootCA = TestCertificates.certificate(filename: "alamofire-root-ca") - - // Intermediate Certificates - static let intermediateCA1 = TestCertificates.certificate(filename: "alamofire-signing-ca1") - static let intermediateCA2 = TestCertificates.certificate(filename: "alamofire-signing-ca2") - - // Leaf Certificates - Signed by CA1 - static let leafWildcard = TestCertificates.certificate(filename: "wildcard.alamofire.org") - static let leafMultipleDNSNames = TestCertificates.certificate(filename: "multiple-dns-names") - static let leafSignedByCA1 = TestCertificates.certificate(filename: "signed-by-ca1") - static let leafDNSNameAndURI = TestCertificates.certificate(filename: "test.alamofire.org") - - // Leaf Certificates - Signed by CA2 - static let leafExpired = TestCertificates.certificate(filename: "expired") - static let leafMissingDNSNameAndURI = TestCertificates.certificate(filename: "missing-dns-name-and-uri") - static let leafSignedByCA2 = TestCertificates.certificate(filename: "signed-by-ca2") - static let leafValidDNSName = TestCertificates.certificate(filename: "valid-dns-name") - static let leafValidURI = TestCertificates.certificate(filename: "valid-uri") - - static func certificate(filename: String) -> SecCertificate { - class Locator {} - let filePath = Bundle(for: Locator.self).path(forResource: filename, ofType: "cer")! - let data = try! Data(contentsOf: URL(fileURLWithPath: filePath)) - let certificate = SecCertificateCreateWithData(nil, data as CFData)! - - return certificate - } -} - -// MARK: - - -private enum TestTrusts { - // Leaf Trusts - Signed by CA1 - case leafWildcard - case leafMultipleDNSNames - case leafSignedByCA1 - case leafDNSNameAndURI - - // Leaf Trusts - Signed by CA2 - case leafExpired - case leafMissingDNSNameAndURI - case leafSignedByCA2 - case leafValidDNSName - case leafValidURI - - // Invalid Trusts - case leafValidDNSNameMissingIntermediate - case leafValidDNSNameWithIncorrectIntermediate - - var trust: SecTrust { - let trust: SecTrust - - switch self { - case .leafWildcard: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafWildcard, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - case .leafMultipleDNSNames: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafMultipleDNSNames, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - case .leafSignedByCA1: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafSignedByCA1, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - case .leafDNSNameAndURI: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafDNSNameAndURI, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - case .leafExpired: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafExpired, - TestCertificates.intermediateCA2, - TestCertificates.rootCA]) - case .leafMissingDNSNameAndURI: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafMissingDNSNameAndURI, - TestCertificates.intermediateCA2, - TestCertificates.rootCA]) - case .leafSignedByCA2: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafSignedByCA2, - TestCertificates.intermediateCA2, - TestCertificates.rootCA]) - case .leafValidDNSName: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2, - TestCertificates.rootCA]) - case .leafValidURI: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafValidURI, - TestCertificates.intermediateCA2, - TestCertificates.rootCA]) - case .leafValidDNSNameMissingIntermediate: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.rootCA]) - case .leafValidDNSNameWithIncorrectIntermediate: - trust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - } - - return trust - } - - static func trustWithCertificates(_ certificates: [SecCertificate]) -> SecTrust { - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - SecTrustCreateWithCertificates(certificates as CFTypeRef, policy, &trust) - - return trust! - } -} - -// MARK: - Basic X509 and SSL Exploration Tests - - -class ServerTrustPolicyTestCase: BaseTestCase { - func setRootCertificateAsLoneAnchorCertificateForTrust(_ trust: SecTrust) { - SecTrustSetAnchorCertificates(trust, [TestCertificates.rootCA] as CFArray) - SecTrustSetAnchorCertificatesOnly(trust, true) - } -} - -// MARK: - SecTrust Extension - -extension SecTrust { - /// Evaluates `self` and returns `true` if the evaluation succeeds with a value of `.unspecified` or `.proceed`. - var isValid: Bool { - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(self, &result) - - return (status == errSecSuccess) ? (result == .unspecified || result == .proceed) : false - } -} - -// MARK: - - -class ServerTrustPolicyExplorationBasicX509PolicyValidationTestCase: ServerTrustPolicyTestCase { - func testThatAnchoredRootCertificatePassesBasicX509ValidationWithRootInTrust() { - // Given - let trust = TestTrusts.trustWithCertificates([TestCertificates.leafDNSNameAndURI, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateBasicX509()] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatAnchoredRootCertificatePassesBasicX509ValidationWithoutRootInTrust() { - // Given - let trust = TestTrusts.leafDNSNameAndURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateBasicX509()] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatCertificateMissingDNSNamePassesBasicX509Validation() { - // Given - let trust = TestTrusts.leafMissingDNSNameAndURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateBasicX509()] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatExpiredCertificateFailsBasicX509Validation() { - // Given - let trust = TestTrusts.leafExpired.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateBasicX509()] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertFalse(trust.isValid, "trust should not be valid") - } -} - -// MARK: - - -class ServerTrustPolicyExplorationSSLPolicyValidationTestCase: ServerTrustPolicyTestCase { - func testThatAnchoredRootCertificatePassesSSLValidationWithRootInTrust() { - // Given - let trust = TestTrusts.trustWithCertificates([TestCertificates.leafDNSNameAndURI, - TestCertificates.intermediateCA1, - TestCertificates.rootCA]) - - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatAnchoredRootCertificatePassesSSLValidationWithoutRootInTrust() { - // Given - let trust = TestTrusts.leafDNSNameAndURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatCertificateMissingDNSNameFailsSSLValidation() { - // Given - let trust = TestTrusts.leafMissingDNSNameAndURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertFalse(trust.isValid, "trust should not be valid") - } - - func testThatWildcardCertificatePassesSSLValidation() { - // Given - let trust = TestTrusts.leafWildcard.trust // *.alamofire.org - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatDNSNameCertificatePassesSSLValidation() { - // Given - let trust = TestTrusts.leafValidDNSName.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should be valid") - } - - func testThatURICertificateFailsSSLValidation() { - // Given - let trust = TestTrusts.leafValidURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertFalse(trust.isValid, "trust should not be valid") - } - - func testThatMultipleDNSNamesCertificatePassesSSLValidationForAllEntries() { - // Given - let trust = TestTrusts.leafMultipleDNSNames.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString), - SecPolicyCreateSSL(true, "blog.alamofire.org" as CFString), - SecPolicyCreateSSL(true, "www.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should not be valid") - } - - func testThatPassingNilForHostParameterAllowsCertificateMissingDNSNameToPassSSLValidation() { - // Given - let trust = TestTrusts.leafMissingDNSNameAndURI.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, nil)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertTrue(trust.isValid, "trust should not be valid") - } - - func testThatExpiredCertificateFailsSSLValidation() { - // Given - let trust = TestTrusts.leafExpired.trust - setRootCertificateAsLoneAnchorCertificateForTrust(trust) - - // When - let policies = [SecPolicyCreateSSL(true, "test.alamofire.org" as CFString)] - SecTrustSetPolicies(trust, policies as CFTypeRef) - - // Then - XCTAssertFalse(trust.isValid, "trust should not be valid") - } -} - -// MARK: - Server Trust Policy Tests - - -class ServerTrustPolicyPerformDefaultEvaluationTestCase: ServerTrustPolicyTestCase { - // MARK: Do NOT Validate Host - - func testThatValidCertificateChainPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatNonAnchoredRootCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2]) - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingDNSNameLeafCertificatePassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafMissingDNSNameAndURI.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatExpiredCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingIntermediateCertificateInChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - // MARK: Validate Host - - func testThatValidCertificateChainPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: true) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatNonAnchoredRootCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2]) - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: true) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingDNSNameLeafCertificateFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafMissingDNSNameAndURI.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: true) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatWildcardedLeafCertificateChainPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafWildcard.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: true) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatExpiredCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: true) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingIntermediateCertificateInChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = DefaultTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - XCTAssertEqual(result.failure?.asAFError?.isServerTrustEvaluationError, true) - } -} - -// MARK: - - -class ServerTrustPolicyPerformRevokedEvaluationTestCase: ServerTrustPolicyTestCase { - // MARK: Do NOT Validate Host - - func testThatValidCertificateChainPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let serverTrustPolicy = RevocationTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatNonAnchoredRootCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2]) - let serverTrustPolicy = RevocationTrustEvaluator(validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingDNSNameLeafCertificatePassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafMissingDNSNameAndURI.trust - let serverTrustPolicy = RevocationTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatExpiredCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let serverTrustPolicy = RevocationTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingIntermediateCertificateInChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = RevocationTrustEvaluator(validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - // MARK: Validate Host - - func testThatValidCertificateChainPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatNonAnchoredRootCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2]) - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingDNSNameLeafCertificateFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafMissingDNSNameAndURI.trust - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatWildcardedLeafCertificateChainPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafWildcard.trust - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatExpiredCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatMissingIntermediateCertificateInChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = RevocationTrustEvaluator() - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } -} - -// MARK: - - -class ServerTrustPolicyPinCertificatesTestCase: ServerTrustPolicyTestCase { - // MARK: Validate Certificate Chain Without Validating Host - - func testThatPinnedLeafCertificatePassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafValidDNSName] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedIntermediateCertificatePassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedRootCertificatePassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.rootCA] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafSignedByCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: true, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA1] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningExpiredLeafCertificateFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.leafExpired] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - // MARK: Validate Certificate Chain and Host - - func testThatPinnedLeafCertificatePassesEvaluationWithSelfSignedSupportAndHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafValidDNSName] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedIntermediateCertificatePassesEvaluationWithSelfSignedSupportAndHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedRootCertificatePassesEvaluationWithSelfSignedSupportAndHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.rootCA] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafSignedByCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: true, - validateHost: true) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA1] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningExpiredLeafCertificateFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.leafExpired] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - // MARK: Do NOT Validate Certificate Chain or Host - - func testThatPinnedLeafCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafValidDNSName] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedIntermediateCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinnedRootCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.rootCA] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningLeafCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.leafSignedByCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningIntermediateCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let certificates = [TestCertificates.intermediateCA1] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.leafExpired] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningIntermediateCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.intermediateCA2] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningRootCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let certificates = [TestCertificates.rootCA] - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningMultipleCertificatesWithoutCertificateChainValidationPassesEvaluation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - - let certificates = [TestCertificates.leafMultipleDNSNames, // not in certificate chain - TestCertificates.leafSignedByCA1, // not in certificate chain - TestCertificates.leafExpired, // in certificate chain 👍🏼👍🏼 - TestCertificates.leafWildcard, // not in certificate chain - TestCertificates.leafDNSNameAndURI // not in certificate chain - ] - - let serverTrustPolicy = PinnedCertificatesTrustEvaluator(certificates: certificates, - performDefaultValidation: false, - validateHost: false) - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } -} - -// MARK: - - -class ServerTrustPolicyPinPublicKeysTestCase: ServerTrustPolicyTestCase { - // MARK: Validate Certificate Chain Without Validating Host - - func testThatPinningLeafKeyPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningIntermediateKeyPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.intermediateCA2].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningRootKeyPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.rootCA].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningKeyNotInCertificateChainFailsEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafSignedByCA2].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningBackupKeyPassesEvaluationWithoutHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafSignedByCA1, TestCertificates.intermediateCA1, TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - // MARK: Validate Certificate Chain and Host - - func testThatPinningLeafKeyPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningIntermediateKeyPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.intermediateCA2].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningRootKeyPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.rootCA].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningKeyNotInCertificateChainFailsEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafSignedByCA2].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningBackupKeyPassesEvaluationWithHostValidation() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let keys = [TestCertificates.leafSignedByCA1, TestCertificates.intermediateCA1, TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - // MARK: Do NOT perform default validation or validate host. - - func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithMissingIntermediateCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let keys = [TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningRootKeyWithoutCertificateChainValidationFailsEvaluationWithMissingIntermediateCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let keys = [TestCertificates.rootCA].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithIncorrectIntermediateCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameWithIncorrectIntermediate.trust - let keys = [TestCertificates.leafValidDNSName].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let keys = [TestCertificates.leafExpired].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningIntermediateKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let keys = [TestCertificates.intermediateCA2].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatPinningRootKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let keys = [TestCertificates.rootCA].af.publicKeys - let serverTrustPolicy = PublicKeysTrustEvaluator(keys: keys, - performDefaultValidation: false, - validateHost: false) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } -} - -// MARK: - - -class ServerTrustPolicyDisableEvaluationTestCase: ServerTrustPolicyTestCase { - func testThatCertificateChainMissingIntermediateCertificatePassesEvaluation() throws { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSNameMissingIntermediate.trust - let serverTrustPolicy = DisabledEvaluator() - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatExpiredLeafCertificatePassesEvaluation() throws { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let serverTrustPolicy = DisabledEvaluator() - - // When - let result = Result { try serverTrustPolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } -} - -// MARK: - - -class ServerTrustPolicyCompositeTestCase: ServerTrustPolicyTestCase { - func testThatValidCertificateChainPassesDefaultAndRevocationCompositeChecks() throws { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafValidDNSName.trust - let defaultPolicy = DefaultTrustEvaluator(validateHost: false) - let revocationPolicy = RevocationTrustEvaluator(validateHost: false) - let compositePolicy = CompositeTrustEvaluator(evaluators: [defaultPolicy, revocationPolicy]) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try compositePolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertTrue(result.isSuccess, "server trust should pass evaluation") - } - - func testThatNonAnchoredRootCertificateChainFailsEvaluationWithoutHostValidation() throws { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.trustWithCertificates([TestCertificates.leafValidDNSName, - TestCertificates.intermediateCA2]) - let defaultPolicy = DefaultTrustEvaluator(validateHost: false) - let revocationPolicy = RevocationTrustEvaluator(validateHost: false) - let compositePolicy = CompositeTrustEvaluator(evaluators: [defaultPolicy, revocationPolicy]) - - // When - let result = Result { try compositePolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } - - func testThatExpiredLeafCertificateFailsDefaultAndRevocationComposite() throws { - // Given - let host = "test.alamofire.org" - let serverTrust = TestTrusts.leafExpired.trust - let defaultPolicy = DefaultTrustEvaluator(validateHost: false) - let revocationPolicy = RevocationTrustEvaluator(validateHost: false) - let compositePolicy = CompositeTrustEvaluator(evaluators: [defaultPolicy, revocationPolicy]) - - // When - setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust) - let result = Result { try compositePolicy.evaluate(serverTrust, forHost: host) } - - // Then - XCTAssertFalse(result.isSuccess, "server trust should not pass evaluation") - } -} - -// MARK: - - -class ServerTrustPolicyCertificatesInBundleTestCase: ServerTrustPolicyTestCase { - func testOnlyValidCertificatesAreDetected() { - // Given - // Files present in bundle in the form of type+encoding+extension [key|cert][DER|PEM].[cer|crt|der|key|pem] - // certDER.cer: DER-encoded well-formed certificate - // certDER.crt: DER-encoded well-formed certificate - // certDER.der: DER-encoded well-formed certificate - // certPEM.*: PEM-encoded well-formed certificates, expected to fail: Apple API only handles DER encoding - // devURandomGibberish.crt: Random data, should fail - // keyDER.der: DER-encoded key, not a certificate, should fail - - // When - let certificates = Bundle(for: ServerTrustPolicyCertificatesInBundleTestCase.self).af.certificates - -// Then -// Expectation: 19 well-formed certificates in the test bundle plus 4 invalid certificates. -#if os(macOS) - // For some reason, macOS is allowing all certificates to be considered valid. Need to file a - // rdar demonstrating this behavior. - if #available(macOS 10.12, *) { - XCTAssertEqual(certificates.count, 19, "Expected 19 well-formed certificates") - } else { - XCTAssertEqual(certificates.count, 23, "Expected 23 well-formed certificates") - } -#else - XCTAssertEqual(certificates.count, 19, "Expected 19 well-formed certificates") -#endif - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionDelegateTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionDelegateTests.swift deleted file mode 100644 index 62c6c4f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionDelegateTests.swift +++ /dev/null @@ -1,206 +0,0 @@ -// -// SessionDelegateTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import XCTest - -class SessionDelegateTestCase: BaseTestCase { - var manager: Session! - - // MARK: - Setup and Teardown - - override func setUp() { - super.setUp() - manager = Session(configuration: .ephemeral) - } - - // MARK: - Tests - Redirects - - func testThatRequestWillPerformHTTPRedirectionByDefault() { - // Given - let redirectURLString = "https://www.apple.com/" - let urlString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" - - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - var response: DataResponse? - - // When - manager.request(urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - func testThatRequestWillPerformRedirectionMultipleTimesByDefault() { - // Given - let redirectURLString = "https://httpbin.org/get" - let urlString = "https://httpbin.org/redirect/5" - - let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)") - - var response: DataResponse? - - // When - manager.request(urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString) - XCTAssertEqual(response?.response?.statusCode, 200) - } - - // MARK: - Tests - Notification - - func testThatAppropriateNotificationsAreCalledWithRequestForDataRequest() { - // Given - let session = Session(startRequestsImmediately: false) - var resumedRequest: Request? - var resumedTaskRequest: Request? - var completedTaskRequest: Request? - var completedRequest: Request? - var requestResponse: DataResponse? - let expect = expectation(description: "request should complete") - - // When - let request = session.request("https://httpbin.org/get").response { response in - requestResponse = response - expect.fulfill() - } - expectation(forNotification: Request.didResumeNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - resumedRequest = notification.request - return true - } - expectation(forNotification: Request.didResumeTaskNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - resumedTaskRequest = notification.request - return true - } - expectation(forNotification: Request.didCompleteTaskNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - completedTaskRequest = notification.request - return true - } - expectation(forNotification: Request.didFinishNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - completedRequest = notification.request - return true - } - - request.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(resumedRequest) - XCTAssertNotNil(resumedTaskRequest) - XCTAssertNotNil(completedTaskRequest) - XCTAssertNotNil(completedRequest) - XCTAssertEqual(resumedRequest, completedRequest) - XCTAssertEqual(resumedTaskRequest, completedTaskRequest) - XCTAssertEqual(requestResponse?.response?.statusCode, 200) - } - - func testThatDidCompleteNotificationIsCalledWithRequestForDownloadRequests() { - // Given - let session = Session(startRequestsImmediately: false) - var resumedRequest: Request? - var resumedTaskRequest: Request? - var completedTaskRequest: Request? - var completedRequest: Request? - var requestResponse: DownloadResponse? - let expect = expectation(description: "request should complete") - - // When - let request = session.download("https://httpbin.org/get").response { response in - requestResponse = response - expect.fulfill() - } - expectation(forNotification: Request.didResumeNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - resumedRequest = notification.request - return true - } - expectation(forNotification: Request.didResumeTaskNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - resumedTaskRequest = notification.request - return true - } - expectation(forNotification: Request.didCompleteTaskNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - completedTaskRequest = notification.request - return true - } - expectation(forNotification: Request.didFinishNotification, object: nil) { notification in - guard let receivedRequest = notification.request, receivedRequest == request else { return false } - - completedRequest = notification.request - return true - } - - request.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(resumedRequest) - XCTAssertNotNil(resumedTaskRequest) - XCTAssertNotNil(completedTaskRequest) - XCTAssertNotNil(completedRequest) - XCTAssertEqual(resumedRequest, completedRequest) - XCTAssertEqual(resumedTaskRequest, completedTaskRequest) - XCTAssertEqual(requestResponse?.response?.statusCode, 200) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionTests.swift deleted file mode 100644 index 28e1a52..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/SessionTests.swift +++ /dev/null @@ -1,1739 +0,0 @@ -// -// SessionTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import XCTest - -final class SessionTestCase: BaseTestCase { - // MARK: Helper Types - - private class HTTPMethodAdapter: RequestInterceptor { - let method: HTTPMethod - let throwsError: Bool - - var adaptedCount = 0 - - init(method: HTTPMethod, throwsError: Bool = false) { - self.method = method - self.throwsError = throwsError - } - - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptedCount += 1 - - let result: Result = Result { - guard !throwsError else { throw AFError.invalidURL(url: "") } - - var urlRequest = urlRequest - urlRequest.httpMethod = method.rawValue - - return urlRequest - } - - completion(result) - } - } - - private class HeaderAdapter: RequestInterceptor { - let headers: HTTPHeaders - let throwsError: Bool - - var adaptedCount = 0 - - init(headers: HTTPHeaders = ["field": "value"], throwsError: Bool = false) { - self.headers = headers - self.throwsError = throwsError - } - - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptedCount += 1 - - let result: Result = Result { - guard !throwsError else { throw AFError.invalidURL(url: "") } - - var urlRequest = urlRequest - - var finalHeaders = urlRequest.headers - headers.forEach { finalHeaders.add($0) } - - urlRequest.headers = finalHeaders - - return urlRequest - } - - completion(result) - } - } - - private class RequestHandler: RequestInterceptor { - var adaptCalledCount = 0 - var adaptedCount = 0 - var retryCount = 0 - var retryCalledCount = 0 - var retryErrors: [Error] = [] - - var shouldApplyAuthorizationHeader = false - var throwsErrorOnFirstAdapt = false - var throwsErrorOnSecondAdapt = false - var throwsErrorOnRetry = false - var shouldRetry = true - var retryDelay: TimeInterval? - - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptCalledCount += 1 - - let result: Result = Result { - if throwsErrorOnFirstAdapt { - throwsErrorOnFirstAdapt = false - throw AFError.invalidURL(url: "/adapt/error/1") - } - - if throwsErrorOnSecondAdapt && adaptedCount == 1 { - throwsErrorOnSecondAdapt = false - throw AFError.invalidURL(url: "/adapt/error/2") - } - - var urlRequest = urlRequest - - adaptedCount += 1 - - if shouldApplyAuthorizationHeader && adaptedCount > 1 { - urlRequest.headers.update(.authorization(username: "user", password: "password")) - } - - return urlRequest - } - - completion(result) - } - - func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retryCalledCount += 1 - - if throwsErrorOnRetry { - let error = AFError.invalidURL(url: "/invalid/url/\(retryCalledCount)") - completion(.doNotRetryWithError(error)) - return - } - - guard shouldRetry else { completion(.doNotRetry); return } - - retryCount += 1 - retryErrors.append(error) - - if retryCount < 2 { - if let retryDelay = retryDelay { - completion(.retryWithDelay(retryDelay)) - } else { - completion(.retry) - } - } else { - completion(.doNotRetry) - } - } - } - - private class UploadHandler: RequestInterceptor { - var adaptCalledCount = 0 - var adaptedCount = 0 - var retryCalledCount = 0 - var retryCount = 0 - var retryErrors: [Error] = [] - - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptCalledCount += 1 - - let result: Result = Result { - adaptedCount += 1 - - if adaptedCount == 1 { throw AFError.invalidURL(url: "") } - - return urlRequest - } - - completion(result) - } - - func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retryCalledCount += 1 - - retryCount += 1 - retryErrors.append(error) - - completion(.retry) - } - } - - // MARK: Tests - Initialization - - func testInitializerWithDefaultArguments() { - // Given, When - let session = Session() - - // Then - XCTAssertNotNil(session.session.delegate, "session delegate should not be nil") - XCTAssertTrue(session.delegate === session.session.delegate, "manager delegate should equal session delegate") - XCTAssertNil(session.serverTrustManager, "session server trust policy manager should be nil") - } - - func testInitializerWithSpecifiedArguments() { - // Given - let configuration = URLSessionConfiguration.default - let delegate = SessionDelegate() - let serverTrustManager = ServerTrustManager(evaluators: [:]) - - // When - let session = Session(configuration: configuration, - delegate: delegate, - serverTrustManager: serverTrustManager) - - // Then - XCTAssertNotNil(session.session.delegate, "session delegate should not be nil") - XCTAssertTrue(session.delegate === session.session.delegate, "manager delegate should equal session delegate") - XCTAssertNotNil(session.serverTrustManager, "session server trust policy manager should not be nil") - } - - func testThatSessionInitializerSucceedsWithDefaultArguments() { - // Given - let delegate = SessionDelegate() - let underlyingQueue = DispatchQueue(label: "underlyingQueue") - let urlSession: URLSession = { - let configuration = URLSessionConfiguration.default - let queue = OperationQueue(underlyingQueue: underlyingQueue, name: "delegateQueue") - return URLSession(configuration: configuration, delegate: delegate, delegateQueue: queue) - }() - - // When - let session = Session(session: urlSession, delegate: delegate, rootQueue: underlyingQueue) - - // Then - XCTAssertTrue(session.delegate === session.session.delegate, "manager delegate should equal session delegate") - XCTAssertNil(session.serverTrustManager, "session server trust policy manager should be nil") - } - - func testThatSessionInitializerSucceedsWithSpecifiedArguments() { - // Given - let delegate = SessionDelegate() - let underlyingQueue = DispatchQueue(label: "underlyingQueue") - let urlSession: URLSession = { - let configuration = URLSessionConfiguration.default - let queue = OperationQueue(underlyingQueue: underlyingQueue, name: "delegateQueue") - return URLSession(configuration: configuration, delegate: delegate, delegateQueue: queue) - }() - - let serverTrustManager = ServerTrustManager(evaluators: [:]) - - // When - let session = Session(session: urlSession, - delegate: delegate, - rootQueue: underlyingQueue, - serverTrustManager: serverTrustManager) - - // Then - XCTAssertTrue(session.delegate === session.session.delegate, "manager delegate should equal session delegate") - XCTAssertNotNil(session.serverTrustManager, "session server trust policy manager should not be nil") - } - - // MARK: Tests - Default HTTP Headers - - func testDefaultUserAgentHeader() { - // Given, When - let userAgent = HTTPHeaders.default["User-Agent"] - - // Then - let osNameVersion: String = { - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - - let osName: String = { -#if os(iOS) - return "iOS" -#elseif os(watchOS) - return "watchOS" -#elseif os(tvOS) - return "tvOS" -#elseif os(macOS) - return "macOS" -#elseif os(Linux) - return "Linux" -#else - return "Unknown" -#endif - }() - - return "\(osName) \(versionString)" - }() - - let alamofireVersion: String = { - guard - let afInfo = Bundle(for: Session.self).infoDictionary, - let build = afInfo["CFBundleShortVersionString"] - else { return "Unknown" } - - return "Alamofire/\(build)" - }() - - XCTAssertTrue(userAgent?.contains(alamofireVersion) == true) - XCTAssertTrue(userAgent?.contains(osNameVersion) == true) - XCTAssertTrue(userAgent?.contains("Unknown/Unknown") == true) - } - - // MARK: Tests - Supported Accept-Encodings - - func testDefaultAcceptEncodingSupportsAppropriateEncodingsOnAppropriateSystems() { - // Given - let brotliURL = URL(string: "https://httpbin.org/brotli")! - let gzipURL = URL(string: "https://httpbin.org/gzip")! - let deflateURL = URL(string: "https://httpbin.org/deflate")! - let brotliExpectation = expectation(description: "brotli request should complete") - let gzipExpectation = expectation(description: "gzip request should complete") - let deflateExpectation = expectation(description: "deflate request should complete") - var brotliResponse: DataResponse? - var gzipResponse: DataResponse? - var deflateResponse: DataResponse? - - // When - AF.request(brotliURL).responseJSON { response in - brotliResponse = response - brotliExpectation.fulfill() - } - - AF.request(gzipURL).responseJSON { response in - gzipResponse = response - gzipExpectation.fulfill() - } - - AF.request(deflateURL).responseJSON { response in - deflateResponse = response - deflateExpectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { - XCTAssertTrue(brotliResponse?.result.isSuccess == true) - } else { - XCTAssertTrue(brotliResponse?.result.isFailure == true) - } - - XCTAssertTrue(gzipResponse?.result.isSuccess == true) - XCTAssertTrue(deflateResponse?.result.isSuccess == true) - } - - // MARK: Tests - Start Requests Immediately - - func testSetStartRequestsImmediatelyToFalseAndResumeRequest() { - // Given - let session = Session(startRequestsImmediately: false) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - let expectation = self.expectation(description: "\(url)") - - var response: HTTPURLResponse? - - // When - session.request(urlRequest) - .response { resp in - response = resp.response - expectation.fulfill() - } - .resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response, "response should not be nil") - XCTAssertTrue(response?.statusCode == 200, "response status code should be 200") - } - - func testSetStartRequestsImmediatelyToFalseAndCancelledCallsResponseHandlers() { - // Given - let session = Session(startRequestsImmediately: false) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - let expectation = self.expectation(description: "\(url)") - - var response: DataResponse? - - // When - let request = session.request(urlRequest) - .cancel() - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response, "response should not be nil") - XCTAssertTrue(request.isCancelled) - XCTAssertTrue((request.task == nil) || (request.task?.state == .canceling || request.task?.state == .completed)) - XCTAssertEqual(request.error?.isExplicitlyCancelledError, true) - } - - func testSetStartRequestsImmediatelyToFalseAndResumeThenCancelRequestHasCorrectOutput() { - // Given - let session = Session(startRequestsImmediately: false) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - let expectation = self.expectation(description: "\(url)") - - var response: DataResponse? - - // When - let request = session.request(urlRequest) - .resume() - .cancel() - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response, "response should not be nil") - XCTAssertTrue(request.isCancelled) - XCTAssertTrue((request.task == nil) || (request.task?.state == .canceling || request.task?.state == .completed)) - XCTAssertEqual(request.error?.isExplicitlyCancelledError, true) - } - - func testSetStartRequestsImmediatelyToFalseAndCancelThenResumeRequestDoesntCreateTaskAndStaysCancelled() { - // Given - let session = Session(startRequestsImmediately: false) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - let expectation = self.expectation(description: "\(url)") - - var response: DataResponse? - - // When - let request = session.request(urlRequest) - .cancel() - .resume() - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response, "response should not be nil") - XCTAssertTrue(request.isCancelled) - XCTAssertTrue((request.task == nil) || (request.task?.state == .canceling || request.task?.state == .completed)) - XCTAssertEqual(request.error?.isExplicitlyCancelledError, true) - } - - // MARK: Tests - Deinitialization - - func testReleasingManagerWithPendingRequestDeinitializesSuccessfully() { - // Given - let monitor = ClosureEventMonitor() - let expectation = self.expectation(description: "Request created") - monitor.requestDidCreateTask = { _, _ in expectation.fulfill() } - var session: Session? = Session(startRequestsImmediately: false, eventMonitors: [monitor]) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - // When - let request = session?.request(urlRequest) - session = nil - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request?.task?.state, .suspended) - XCTAssertNil(session, "manager should be nil") - } - - func testReleasingManagerWithPendingCanceledRequestDeinitializesSuccessfully() { - // Given - var session: Session? = Session(startRequestsImmediately: false) - - let url = URL(string: "https://httpbin.org/get")! - let urlRequest = URLRequest(url: url) - - // When - let request = session?.request(urlRequest) - request?.cancel() - session = nil - - let state = request?.state - - // Then - XCTAssertTrue(state == .cancelled, "state should be .cancelled") - XCTAssertNil(session, "manager should be nil") - } - - // MARK: Tests - Bad Requests - - func testThatDataRequestWithInvalidURLStringThrowsResponseHandlerError() { - // Given - let session = Session() - let expectation = self.expectation(description: "Request should fail with error") - - var response: DataResponse? - - // When - session.request("https://httpbin.org/get/äëïöü").response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isInvalidURLError, true) - XCTAssertEqual(response?.error?.urlConvertible as? String, "https://httpbin.org/get/äëïöü") - } - - func testThatDownloadRequestWithInvalidURLStringThrowsResponseHandlerError() { - // Given - let session = Session() - let expectation = self.expectation(description: "Download should fail with error") - - var response: DownloadResponse? - - // When - session.download("https://httpbin.org/get/äëïöü").response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.fileURL) - XCTAssertNil(response?.resumeData) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isInvalidURLError, true) - XCTAssertEqual(response?.error?.urlConvertible as? String, "https://httpbin.org/get/äëïöü") - } - - func testThatUploadDataRequestWithInvalidURLStringThrowsResponseHandlerError() { - // Given - let session = Session() - let expectation = self.expectation(description: "Upload should fail with error") - - var response: DataResponse? - - // When - session.upload(Data(), to: "https://httpbin.org/get/äëïöü").response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isInvalidURLError, true) - XCTAssertEqual(response?.error?.urlConvertible as? String, "https://httpbin.org/get/äëïöü") - } - - func testThatUploadFileRequestWithInvalidURLStringThrowsResponseHandlerError() { - // Given - let session = Session() - let expectation = self.expectation(description: "Upload should fail with error") - - var response: DataResponse? - - // When - session.upload(URL(fileURLWithPath: "/invalid"), to: "https://httpbin.org/get/äëïöü").response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isInvalidURLError, true) - XCTAssertEqual(response?.error?.urlConvertible as? String, "https://httpbin.org/get/äëïöü") - } - - func testThatUploadStreamRequestWithInvalidURLStringThrowsResponseHandlerError() { - // Given - let session = Session() - let expectation = self.expectation(description: "Upload should fail with error") - - var response: DataResponse? - - // When - session.upload(InputStream(data: Data()), to: "https://httpbin.org/get/äëïöü").response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(response?.request) - XCTAssertNil(response?.response) - XCTAssertNil(response?.data) - XCTAssertNotNil(response?.error) - XCTAssertEqual(response?.error?.isInvalidURLError, true) - XCTAssertEqual(response?.error?.urlConvertible as? String, "https://httpbin.org/get/äëïöü") - } - - // MARK: Tests - Request Adapter - - func testThatSessionCallsRequestAdaptersWhenCreatingDataRequest() { - // Given - let urlString = "https://httpbin.org/get" - - let methodAdapter = HTTPMethodAdapter(method: .post) - let headerAdapter = HeaderAdapter() - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidCreateTask = { _, _ in expectation1.fulfill() } - - let request1 = session.request(urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidCreateTask = { _, _ in expectation2.fulfill() } - - let request2 = session.request(urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request1.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.allHTTPHeaderFields?.count, 1) - XCTAssertEqual(methodAdapter.adaptedCount, 2) - XCTAssertEqual(headerAdapter.adaptedCount, 1) - } - - func testThatSessionCallsRequestAdaptersWhenCreatingDownloadRequest() { - // Given - let urlString = "https://httpbin.org/get" - - let methodAdapter = HTTPMethodAdapter(method: .post) - let headerAdapter = HeaderAdapter() - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidCreateTask = { _, _ in expectation1.fulfill() } - - let request1 = session.download(urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidCreateTask = { _, _ in expectation2.fulfill() } - - let request2 = session.download(urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request1.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.allHTTPHeaderFields?.count, 1) - XCTAssertEqual(methodAdapter.adaptedCount, 2) - XCTAssertEqual(headerAdapter.adaptedCount, 1) - } - - func testThatSessionCallsRequestAdaptersWhenCreatingUploadRequestWithData() { - // Given - let data = Data("data".utf8) - let urlString = "https://httpbin.org/post" - - let methodAdapter = HTTPMethodAdapter(method: .get) - let headerAdapter = HeaderAdapter() - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidCreateTask = { _, _ in expectation1.fulfill() } - - let request1 = session.upload(data, to: urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidCreateTask = { _, _ in expectation2.fulfill() } - - let request2 = session.upload(data, to: urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request1.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.allHTTPHeaderFields?.count, 1) - XCTAssertEqual(methodAdapter.adaptedCount, 2) - XCTAssertEqual(headerAdapter.adaptedCount, 1) - } - - func testThatSessionCallsRequestAdaptersWhenCreatingUploadRequestWithFile() { - // Given - let fileURL = URL(fileURLWithPath: "/path/to/some/file.txt") - let urlString = "https://httpbin.org/post" - - let methodAdapter = HTTPMethodAdapter(method: .get) - let headerAdapter = HeaderAdapter() - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidCreateTask = { _, _ in expectation1.fulfill() } - - let request1 = session.upload(fileURL, to: urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidCreateTask = { _, _ in expectation2.fulfill() } - - let request2 = session.upload(fileURL, to: urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request1.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.allHTTPHeaderFields?.count, 1) - XCTAssertEqual(methodAdapter.adaptedCount, 2) - XCTAssertEqual(headerAdapter.adaptedCount, 1) - } - - func testThatSessionCallsRequestAdaptersWhenCreatingUploadRequestWithInputStream() { - // Given - let inputStream = InputStream(data: Data("data".utf8)) - let urlString = "https://httpbin.org/post" - - let methodAdapter = HTTPMethodAdapter(method: .get) - let headerAdapter = HeaderAdapter() - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidCreateTask = { _, _ in expectation1.fulfill() } - - let request1 = session.upload(inputStream, to: urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidCreateTask = { _, _ in expectation2.fulfill() } - - let request2 = session.upload(inputStream, to: urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request1.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.httpMethod, methodAdapter.method.rawValue) - XCTAssertEqual(request2.task?.originalRequest?.allHTTPHeaderFields?.count, 1) - XCTAssertEqual(methodAdapter.adaptedCount, 2) - XCTAssertEqual(headerAdapter.adaptedCount, 1) - } - - func testThatSessionReturnsRequestAdaptationErrorWhenRequestAdapterThrowsError() { - // Given - let urlString = "https://httpbin.org/get" - - let methodAdapter = HTTPMethodAdapter(method: .post, throwsError: true) - let headerAdapter = HeaderAdapter(throwsError: true) - let monitor = ClosureEventMonitor() - - let session = Session(startRequestsImmediately: false, interceptor: methodAdapter, eventMonitors: [monitor]) - - // When - let expectation1 = expectation(description: "Request 1 created") - monitor.requestDidFailToAdaptURLRequestWithError = { _, _, _ in expectation1.fulfill() } - - let request1 = session.request(urlString) - waitForExpectations(timeout: timeout, handler: nil) - - let expectation2 = expectation(description: "Request 2 created") - monitor.requestDidFailToAdaptURLRequestWithError = { _, _, _ in expectation2.fulfill() } - - let request2 = session.request(urlString, interceptor: headerAdapter) - waitForExpectations(timeout: timeout, handler: nil) - - let requests = [request1, request2] - - // Then - for request in requests { - XCTAssertEqual(request.error?.isRequestAdaptationError, true) - XCTAssertEqual(request.error?.underlyingError?.asAFError?.urlConvertible as? String, "") - } - } - - // MARK: Tests - Request Retrier - - func testThatSessionCallsRequestRetrierWhenRequestEncountersError() { - // Given - let handler = RequestHandler() - - let session = Session() - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password", interceptor: handler) - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 3) - XCTAssertEqual(handler.retryCount, 3) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsRequestRetrierThenSessionRetrierWhenRequestEncountersError() { - // Given - let sessionHandler = RequestHandler() - let requestHandler = RequestHandler() - - let session = Session(interceptor: sessionHandler) - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password", interceptor: requestHandler) - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(sessionHandler.adaptCalledCount, 3) - XCTAssertEqual(sessionHandler.adaptedCount, 3) - XCTAssertEqual(sessionHandler.retryCalledCount, 3) - XCTAssertEqual(sessionHandler.retryCount, 3) - XCTAssertEqual(requestHandler.adaptCalledCount, 3) - XCTAssertEqual(requestHandler.adaptedCount, 3) - XCTAssertEqual(requestHandler.retryCalledCount, 4) - XCTAssertEqual(requestHandler.retryCount, 4) - XCTAssertEqual(request.retryCount, 2) - XCTAssertEqual(response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsRequestRetrierWhenRequestInitiallyEncountersAdaptError() { - // Given - let handler = RequestHandler() - handler.adaptedCount = 1 - handler.throwsErrorOnSecondAdapt = true - handler.shouldApplyAuthorizationHeader = true - - let session = Session() - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - session.request("https://httpbin.org/basic-auth/user/password", interceptor: handler) - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 1) - XCTAssertEqual(handler.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, true) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsRequestRetrierWhenDownloadInitiallyEncountersAdaptError() { - // Given - let handler = RequestHandler() - handler.adaptedCount = 1 - handler.throwsErrorOnSecondAdapt = true - handler.shouldApplyAuthorizationHeader = true - - let session = Session() - - let expectation = self.expectation(description: "request should eventually fail") - var response: DownloadResponse? - - let destination: DownloadRequest.Destination = { _, _ in - let fileURL = self.testDirectoryURL.appendingPathComponent("test-output.json") - return (fileURL, [.removePreviousFile]) - } - - // When - session.download("https://httpbin.org/basic-auth/user/password", interceptor: handler, to: destination) - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 1) - XCTAssertEqual(handler.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, true) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsRequestRetrierWhenUploadInitiallyEncountersAdaptError() { - // Given - let handler = UploadHandler() - let session = Session(interceptor: handler) - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - let uploadData = Data("upload data".utf8) - - // When - session.upload(uploadData, to: "https://httpbin.org/post") - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 1) - XCTAssertEqual(handler.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, true) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsAdapterWhenRequestIsRetried() { - // Given - let handler = RequestHandler() - handler.shouldApplyAuthorizationHeader = true - - let session = Session(interceptor: handler) - - let expectation = self.expectation(description: "request should eventually succeed") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password") - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 1) - XCTAssertEqual(handler.retryCount, 1) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, true) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionReturnsRequestAdaptationErrorWhenRequestIsRetried() { - // Given - let handler = RequestHandler() - handler.throwsErrorOnSecondAdapt = true - - let session = Session(interceptor: handler) - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password") - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 3) - XCTAssertEqual(handler.retryCount, 3) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, false) - XCTAssertEqual(request.error?.isRequestAdaptationError, true) - XCTAssertEqual(request.error?.underlyingError?.asAFError?.urlConvertible as? String, "/adapt/error/2") - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionRetriesRequestWithDelayWhenRetryResultContainsDelay() { - // Given - let handler = RequestHandler() - handler.retryDelay = 0.01 - handler.throwsErrorOnSecondAdapt = true - - let session = Session(interceptor: handler) - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password") - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 3) - XCTAssertEqual(handler.retryCount, 3) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(response?.result.isSuccess, false) - XCTAssertEqual(request.error?.isRequestAdaptationError, true) - XCTAssertEqual(request.error?.underlyingError?.asAFError?.urlConvertible as? String, "/adapt/error/2") - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionReturnsRequestRetryErrorWhenRequestRetrierThrowsError() { - // Given - let handler = RequestHandler() - handler.throwsErrorOnRetry = true - - let session = Session(interceptor: handler) - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/basic-auth/user/password") - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 1) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 2) - XCTAssertEqual(handler.retryCount, 0) - XCTAssertEqual(request.retryCount, 0) - XCTAssertEqual(response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - - if let error = response?.result.failure { - XCTAssertTrue(error.isRequestRetryError) - XCTAssertEqual(error.underlyingError?.asAFError?.urlConvertible as? String, "/invalid/url/2") - } else { - XCTFail("error should not be nil") - } - } - - // MARK: Tests - Response Serializer Retry - - func testThatSessionCallsRequestRetrierWhenResponseSerializerThrowsError() { - // Given - let handler = RequestHandler() - handler.shouldRetry = false - - let session = Session() - - let expectation = self.expectation(description: "request should eventually fail") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/image/jpeg", interceptor: handler) - .validate() - .responseJSON { jsonResponse in - response = jsonResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 1) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 1) - XCTAssertEqual(handler.retryCount, 0) - XCTAssertEqual(request.retryCount, 0) - XCTAssertEqual(response?.result.isSuccess, false) - XCTAssertEqual(response?.error?.isResponseSerializationError, true) - XCTAssertEqual((response?.error?.underlyingError as? CocoaError)?.code, .propertyListReadCorrupt) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - func testThatSessionCallsRequestRetrierForAllResponseSerializersThatThrowError() throws { - // Given - let handler = RequestHandler() - handler.throwsErrorOnRetry = true - - let session = Session() - - let json1Expectation = expectation(description: "request should eventually fail") - var json1Response: DataResponse? - - let json2Expectation = expectation(description: "request should eventually fail") - var json2Response: DataResponse? - - // When - let request = session.request("https://httpbin.org/image/jpeg", interceptor: handler) - .validate() - .responseJSON { response in - json1Response = response - json1Expectation.fulfill() - } - .responseJSON { response in - json2Response = response - json2Expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 1) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 2) - XCTAssertEqual(handler.retryCount, 0) - XCTAssertEqual(request.retryCount, 0) - XCTAssertEqual(json1Response?.result.isSuccess, false) - XCTAssertEqual(json2Response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - - let errors = [json1Response, json2Response].compactMap { $0?.error } - - XCTAssertEqual(errors.count, 2) - - for (index, error) in errors.enumerated() { - XCTAssertTrue(error.isRequestRetryError) - if case let .requestRetryFailed(retryError, originalError) = error { - XCTAssertEqual(retryError.asAFError?.urlConvertible as? String, "/invalid/url/\(index + 1)") - XCTAssertEqual((originalError.asAFError?.underlyingError as? CocoaError)?.code, .propertyListReadCorrupt) - } else { - XCTFail("Error failure reason should be response serialization failure") - } - } - } - - func testThatSessionRetriesRequestImmediatelyWhenResponseSerializerRequestsRetry() throws { - // Given - let handler = RequestHandler() - let session = Session() - - let json1Expectation = expectation(description: "request should eventually fail") - var json1Response: DataResponse? - - let json2Expectation = expectation(description: "request should eventually fail") - var json2Response: DataResponse? - - // When - let request = session.request("https://httpbin.org/image/jpeg", interceptor: handler) - .validate() - .responseJSON { response in - json1Response = response - json1Expectation.fulfill() - } - .responseJSON { response in - json2Response = response - json2Expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 2) - XCTAssertEqual(handler.retryCalledCount, 3) - XCTAssertEqual(handler.retryCount, 3) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(json1Response?.result.isSuccess, false) - XCTAssertEqual(json2Response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - - let errors = [json1Response, json2Response].compactMap { $0?.error } - XCTAssertEqual(errors.count, 2) - - for error in errors { - XCTAssertTrue(error.isResponseSerializationError) - XCTAssertEqual((error.underlyingError as? CocoaError)?.code, .propertyListReadCorrupt) - } - } - - func testThatSessionCallsResponseSerializerCompletionsWhenAdapterThrowsErrorDuringRetry() { - // Four retries should occur given this scenario: - // 1) Retrier is called from first response serializer failure (trips retry) - // 2) Retrier is called by Session for adapt error thrown - // 3) Retrier is called again from first response serializer failure - // 4) Retrier is called from second response serializer failure - - // Given - let handler = RequestHandler() - handler.throwsErrorOnSecondAdapt = true - - let session = Session() - - let json1Expectation = expectation(description: "request should eventually fail") - var json1Response: DataResponse? - - let json2Expectation = expectation(description: "request should eventually fail") - var json2Response: DataResponse? - - // When - let request = session.request("https://httpbin.org/image/jpeg", interceptor: handler) - .validate() - .responseJSON { response in - json1Response = response - json1Expectation.fulfill() - } - .responseJSON { response in - json2Response = response - json2Expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 4) - XCTAssertEqual(handler.retryCount, 4) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(json1Response?.result.isSuccess, false) - XCTAssertEqual(json2Response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - - let errors = [json1Response, json2Response].compactMap { $0?.error } - XCTAssertEqual(errors.count, 2) - - for error in errors { - XCTAssertTrue(error.isRequestAdaptationError) - XCTAssertEqual(error.underlyingError?.asAFError?.urlConvertible as? String, "/adapt/error/2") - } - } - - func testThatSessionCallsResponseSerializerCompletionsWhenAdapterThrowsErrorDuringRetryForDownloads() { - // Four retries should occur given this scenario: - // 1) Retrier is called from first response serializer failure (trips retry) - // 2) Retrier is called by Session for adapt error thrown - // 3) Retrier is called again from first response serializer failure - // 4) Retrier is called from second response serializer failure - - // Given - let handler = RequestHandler() - handler.throwsErrorOnSecondAdapt = true - - let session = Session() - - let json1Expectation = expectation(description: "request should eventually fail") - var json1Response: DownloadResponse? - - let json2Expectation = expectation(description: "request should eventually fail") - var json2Response: DownloadResponse? - - // When - let request = session.download("https://httpbin.org/image/jpeg", interceptor: handler) - .validate() - .responseJSON { response in - json1Response = response - json1Expectation.fulfill() - } - .responseJSON { response in - json2Response = response - json2Expectation.fulfill() - } - - waitForExpectations(timeout: 10, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 2) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 4) - XCTAssertEqual(handler.retryCount, 4) - XCTAssertEqual(request.retryCount, 1) - XCTAssertEqual(json1Response?.result.isSuccess, false) - XCTAssertEqual(json2Response?.result.isSuccess, false) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - - let errors = [json1Response, json2Response].compactMap { $0?.error } - XCTAssertEqual(errors.count, 2) - - for error in errors { - XCTAssertTrue(error.isRequestAdaptationError) - XCTAssertEqual(error.underlyingError?.asAFError?.urlConvertible as? String, "/adapt/error/2") - } - } - - // MARK: Tests - Session Invalidation - - func testThatSessionIsInvalidatedAndAllRequestsCompleteWhenSessionIsDeinitialized() { - // Given - let invalidationExpectation = expectation(description: "sessionDidBecomeInvalidWithError should be called") - let events = ClosureEventMonitor() - events.sessionDidBecomeInvalidWithError = { _, _ in - invalidationExpectation.fulfill() - } - var session: Session? = Session(startRequestsImmediately: false, eventMonitors: [events]) - var error: AFError? - let requestExpectation = expectation(description: "request should complete") - - // When - session?.request(URLRequest.makeHTTPBinRequest()).response { response in - error = response.error - requestExpectation.fulfill() - } - session = nil - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(error?.isSessionDeinitializedError, true) - } - - // MARK: Tests - Request Cancellation - - func testThatSessionOnlyCallsResponseSerializerCompletionWhenCancellingInsideCompletion() { - // Given - let handler = RequestHandler() - let session = Session() - - let expectation = self.expectation(description: "request should complete") - var response: DataResponse? - var completionCallCount = 0 - - // When - let request = session.request("https://httpbin.org/get", interceptor: handler) - request.validate() - - request.responseJSON { resp in - request.cancel() - - response = resp - completionCallCount += 1 - - DispatchQueue.main.after(0.01) { expectation.fulfill() } - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(handler.adaptCalledCount, 1) - XCTAssertEqual(handler.adaptedCount, 1) - XCTAssertEqual(handler.retryCalledCount, 0) - XCTAssertEqual(handler.retryCount, 0) - XCTAssertEqual(request.retryCount, 0) - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(completionCallCount, 1) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty) - XCTAssertTrue(session.activeRequests.isEmpty) - } - } - - // MARK: Tests - Request State - - func testThatSessionSetsRequestStateWhenStartRequestsImmediatelyIsTrue() { - // Given - let session = Session() - - let expectation = self.expectation(description: "request should complete") - var response: DataResponse? - - // When - let request = session.request("https://httpbin.org/get").responseJSON { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - XCTAssertEqual(response?.result.isSuccess, true) - } -} - -// MARK: - - -final class SessionCancellationTestCase: BaseTestCase { - func testThatAutomaticallyResumedRequestsCanBeMassCancelled() { - // Given - let count = 100 - let completion = expectation(description: "all requests should finish") - completion.expectedFulfillmentCount = count - let createdTasks = expectation(description: "all tasks created") - createdTasks.expectedFulfillmentCount = count - let gatheredMetrics = expectation(description: "metrics gathered for all tasks") - gatheredMetrics.expectedFulfillmentCount = count - let cancellation = expectation(description: "cancel all requests should be called") - let monitor = ClosureEventMonitor() - monitor.requestDidCreateTask = { _, _ in createdTasks.fulfill() } - monitor.requestDidGatherMetrics = { _, _ in gatheredMetrics.fulfill() } - let session = Session(eventMonitors: [monitor]) - let request = URLRequest.makeHTTPBinRequest(path: "delay/1") - var requests: [DataRequest] = [] - var responses: [DataResponse] = [] - - // When - requests = (0..] = [] - - // When - for _ in 0.. Void) { - completion(hasRetried ? .doNotRetry : .retry) - hasRetried = true - } - } - let monitor = ClosureEventMonitor() - let session = Session(interceptor: OnceRetrier(), eventMonitors: [monitor]) - let request = URLRequest.makeHTTPBinRequest(path: "status/401") - let completion = expectation(description: "all requests should finish") - let cancellation = expectation(description: "cancel all requests should be called") - let createTask = expectation(description: "should create task twice") - createTask.expectedFulfillmentCount = 2 - var tasksCreated = 0 - monitor.requestDidCreateTask = { _, _ in - tasksCreated += 1 - createTask.fulfill() - // Cancel after the second task is created to ensure proper lifetime events. - if tasksCreated == 2 { - session.cancelAllRequests { - cancellation.fulfill() - } - } - } - - var received: DataResponse? - - // When - session.request(request).validate().response { response in - received = response - completion.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertEqual(received?.error?.isExplicitlyCancelledError, true) - assert(on: session.rootQueue) { - XCTAssertTrue(session.requestTaskMap.isEmpty, "requestTaskMap should be empty but has \(session.requestTaskMap.count) items") - XCTAssertTrue(session.activeRequests.isEmpty, "activeRequests should be empty but has \(session.activeRequests.count) items") - } - } - - func testThatGETRequestsWithBodyDataAreConsideredInvalid() { - // Given - let session = Session() - var request = URLRequest.makeHTTPBinRequest() - request.httpBody = Data("invalid".utf8) - let expect = expectation(description: "request should complete") - var response: DataResponse? - - // When - session.request(request).responseDecodable(of: HTTPBinResponse.self) { resp in - response = resp - expect.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isBodyDataInGETRequest, true) - } - - func testThatAdaptedGETRequestsWithBodyDataAreConsideredInvalid() { - // Given - struct InvalidAdapter: RequestInterceptor { - func adapt(_ urlRequest: URLRequest, - for session: Session, - completion: @escaping (Result) -> Void) { - var request = urlRequest - request.httpBody = Data("invalid".utf8) - - completion(.success(request)) - } - } - let session = Session(interceptor: InvalidAdapter()) - let request = URLRequest.makeHTTPBinRequest() - let expect = expectation(description: "request should complete") - var response: DataResponse? - - // When - session.request(request).responseDecodable(of: HTTPBinResponse.self) { resp in - response = resp - expect.fulfill() - } - - waitForExpectations(timeout: timeout) - - // Then - XCTAssertEqual(response?.result.isFailure, true) - XCTAssertEqual(response?.error?.isRequestAdaptationError, true) - XCTAssertEqual(response?.error?.underlyingError?.asAFError?.isBodyDataInGETRequest, true) - } -} - -// MARK: - - -final class SessionConfigurationHeadersTestCase: BaseTestCase { - enum ConfigurationType { - case `default`, ephemeral, background - } - - func testThatDefaultConfigurationHeadersAreSentWithRequest() { - // Given, When, Then - executeAuthorizationHeaderTest(for: .default) - } - - func testThatEphemeralConfigurationHeadersAreSentWithRequest() { - // Given, When, Then - executeAuthorizationHeaderTest(for: .ephemeral) - } - -#if os(macOS) - func disabled_testThatBackgroundConfigurationHeadersAreSentWithRequest() { - // Given, When, Then - executeAuthorizationHeaderTest(for: .background) - } -#endif - - private func executeAuthorizationHeaderTest(for type: ConfigurationType) { - // Given - let session: Session = { - let configuration: URLSessionConfiguration = { - let configuration: URLSessionConfiguration - - switch type { - case .default: - configuration = .default - case .ephemeral: - configuration = .ephemeral - case .background: - let identifier = "org.alamofire.test.manager-configuration-tests" - configuration = .background(withIdentifier: identifier) - } - - var headers = HTTPHeaders.default - headers["Authorization"] = "Bearer 123456" - configuration.headers = headers - - return configuration - }() - - return Session(configuration: configuration) - }() - - let expectation = self.expectation(description: "request should complete successfully") - - var response: DataResponse? - - // When - session.request("https://httpbin.org/get") - .responseDecodable(of: HTTPBinResponse.self) { closureResponse in - response = closureResponse - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request, "request should not be nil") - XCTAssertNotNil(response?.response, "response should not be nil") - XCTAssertNotNil(response?.data, "data should not be nil") - XCTAssertEqual(response?.result.isSuccess, true) - XCTAssertEqual(response?.value?.headers["Authorization"], "Bearer 123456", "Authorization header should match") - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/TLSEvaluationTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/TLSEvaluationTests.swift deleted file mode 100644 index 6304add..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/TLSEvaluationTests.swift +++ /dev/null @@ -1,555 +0,0 @@ -// -// TLSEvaluationTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -private struct TestCertificates { - static let rootCA = TestCertificates.certificate(filename: "expired.badssl.com-root-ca") - static let intermediateCA1 = TestCertificates.certificate(filename: "expired.badssl.com-intermediate-ca-1") - static let intermediateCA2 = TestCertificates.certificate(filename: "expired.badssl.com-intermediate-ca-2") - static let leaf = TestCertificates.certificate(filename: "expired.badssl.com-leaf") - - static func certificate(filename: String) -> SecCertificate { - class Locator {} - let filePath = Bundle(for: Locator.self).path(forResource: filename, ofType: "cer")! - let data = try! Data(contentsOf: URL(fileURLWithPath: filePath)) - let certificate = SecCertificateCreateWithData(nil, data as CFData)! - - return certificate - } -} - -// MARK: - - -final class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase { - private let expiredURLString = "https://expired.badssl.com/" - private let expiredHost = "expired.badssl.com" - - private let revokedURLString = "https://revoked.badssl.com" - private let revokedHost = "revoked.badssl.com" - - private var configuration: URLSessionConfiguration! - - // MARK: Setup and Teardown - - override func setUp() { - super.setUp() - - configuration = URLSessionConfiguration.ephemeral - configuration.urlCache = nil - configuration.urlCredentialStorage = nil - } - - // MARK: Default Behavior Tests - - func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() { - // Given - let expectation = self.expectation(description: "\(expiredURLString)") - let manager = Session(configuration: configuration) - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error) - - if let error = error?.underlyingError as? URLError { - XCTAssertEqual(error.code, .serverCertificateUntrusted) - } else if let error = error?.underlyingError as NSError? { - XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String) - XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue)) - } else { - XCTFail("error should be a URLError or NSError from CFNetwork") - } - } - - func disabled_testRevokedCertificateRequestBehaviorWithNoServerTrustPolicy() { - // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This - // test is left for debugging purposes only. Should not be committed into the test suite while enabled. - - // Given - let expectation = self.expectation(description: "\(revokedURLString)") - let manager = Session(configuration: configuration) - - var error: Error? - - // When - manager.request(revokedURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) { - // Apple appears to have started revocation tests as part of default evaluation in 10.1 - XCTAssertNotNil(error) - } else { - XCTAssertNil(error) - } - } - - // MARK: Server Trust Policy - Perform Default Tests - - func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() { - // Given - let evaluators = [expiredHost: DefaultTrustEvaluator(validateHost: true)] - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - XCTAssertTrue(reason.isHostValidationFailed, "should be .hostValidationFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - func disabled_testRevokedCertificateRequestBehaviorWithDefaultServerTrustPolicy() { - // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This - // test is left for debugging purposes only. Should not be committed into the test suite while enabled. - - // Given - let defaultPolicy = DefaultTrustEvaluator() - let evaluators = [revokedHost: defaultPolicy] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(revokedURLString)") - var error: Error? - - // When - manager.request(revokedURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) { - // Apple appears to have started revocation tests as part of default evaluation in 10.1 - XCTAssertNotNil(error) - } else { - XCTAssertNil(error) - } - } - - // MARK: Server Trust Policy - Perform Revoked Tests - - func testThatExpiredCertificateRequestFailsWithRevokedServerTrustPolicy() { - // Given - let policy = RevocationTrustEvaluator() - - let evaluators = [expiredHost: policy] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() { - // Given - let policy = RevocationTrustEvaluator() - - let evaluators = [revokedHost: policy] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(revokedURLString)") - var error: AFError? - - // When - manager.request(revokedURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - // Test seems flaky and can result in either of these failures, perhaps due to the OS actually checking? - XCTAssertTrue(reason.isDefaultEvaluationFailed || reason.isRevocationCheckFailed, - "should be .defaultEvaluationFailed or .revocationCheckFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - // MARK: Server Trust Policy - Certificate Pinning Tests - - func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() { - // Given - let certificates = [TestCertificates.leaf] - let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() { - // Given - let certificates = [TestCertificates.leaf, - TestCertificates.intermediateCA1, - TestCertificates.intermediateCA2, - TestCertificates.rootCA] - - let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainOrHostValidation() { - // Given - let certificates = [TestCertificates.leaf] - let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, validateHost: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(error, "error should be nil") - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainOrHostValidation() { - // Given - let certificates = [TestCertificates.intermediateCA2] - let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false, validateHost: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(error, "error should be nil") - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() { - // Given - let certificates = [TestCertificates.rootCA] - let evaluators = [expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, performDefaultValidation: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) { - XCTAssertNotNil(error, "error should not be nil") - } else { - XCTAssertNil(error, "error should be nil") - } - } - - // MARK: Server Trust Policy - Public Key Pinning Tests - - func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() { - // Given - let keys = [TestCertificates.leaf].af.publicKeys - let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: AFError? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(error, "error should not be nil") - XCTAssertEqual(error?.isServerTrustEvaluationError, true) - - if case let .serverTrustEvaluationFailed(reason)? = error { - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - XCTAssertTrue(reason.isTrustEvaluationFailed, "should be .trustEvaluationFailed") - } else { - XCTAssertTrue(reason.isDefaultEvaluationFailed, "should be .defaultEvaluationFailed") - } - } else { - XCTFail("error should be .serverTrustEvaluationFailed") - } - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainOrHostValidation() { - // Given - let keys = [TestCertificates.leaf].af.publicKeys - let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(error, "error should be nil") - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainOrHostValidation() { - // Given - let keys = [TestCertificates.intermediateCA2].af.publicKeys - let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(error, "error should be nil") - } - - func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() { - // Given - let keys = [TestCertificates.rootCA].af.publicKeys - let evaluators = [expiredHost: PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: false, validateHost: false)] - - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) { - XCTAssertNotNil(error, "error should not be nil") - } else { - XCTAssertNil(error, "error should be nil") - } - } - - // MARK: Server Trust Policy - Disabling Evaluation Tests - - func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() { - // Given - let evaluators = [expiredHost: DisabledEvaluator()] - let manager = Session(configuration: configuration, - serverTrustManager: ServerTrustManager(evaluators: evaluators)) - - let expectation = self.expectation(description: "\(expiredURLString)") - var error: Error? - - // When - manager.request(expiredURLString) - .response { resp in - error = resp.error - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(error, "error should be nil") - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/URLProtocolTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/URLProtocolTests.swift deleted file mode 100644 index 7d3399a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/URLProtocolTests.swift +++ /dev/null @@ -1,165 +0,0 @@ -// -// URLProtocolTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class ProxyURLProtocol: URLProtocol { - // MARK: Properties - - struct PropertyKeys { - static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol" - } - - lazy var session: URLSession = { - let configuration: URLSessionConfiguration = { - let configuration = URLSessionConfiguration.ephemeral - configuration.headers = HTTPHeaders.default - - return configuration - }() - - let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil) - - return session - }() - - var activeTask: URLSessionTask? - - // MARK: Class Request Methods - - override class func canInit(with request: URLRequest) -> Bool { - if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil { - return false - } - - return true - } - - override class func canonicalRequest(for request: URLRequest) -> URLRequest { - if let headers = request.allHTTPHeaderFields { - do { - return try URLEncoding.default.encode(request, with: headers) - } catch { - return request - } - } - - return request - } - - override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { - return false - } - - // MARK: Loading Methods - - override func startLoading() { - // rdar://26849668 - URLProtocol had some API's that didn't make the value type conversion - let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest - URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest) - activeTask = session.dataTask(with: urlRequest as URLRequest) - activeTask?.resume() - } - - override func stopLoading() { - activeTask?.cancel() - } -} - -// MARK: - - -extension ProxyURLProtocol: URLSessionDataDelegate { - // MARK: NSURLSessionDelegate - - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - client?.urlProtocol(self, didLoad: data) - } - - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - if let response = task.response { - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - } - - client?.urlProtocolDidFinishLoading(self) - } -} - -// MARK: - - -class URLProtocolTestCase: BaseTestCase { - var manager: Session! - - // MARK: Setup and Teardown - - override func setUp() { - super.setUp() - - manager = { - let configuration: URLSessionConfiguration = { - let configuration = URLSessionConfiguration.default - configuration.protocolClasses = [ProxyURLProtocol.self] - configuration.headers["Session-Configuration-Header"] = "foo" - - return configuration - }() - - return Session(configuration: configuration) - }() - } - - // MARK: Tests - - func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() { - // Given - let urlString = "https://httpbin.org/response-headers" - let url = URL(string: urlString)! - - var urlRequest = URLRequest(url: url) - urlRequest.method = .get - urlRequest.headers["Request-Header"] = "foobar" - - let expectation = self.expectation(description: "GET request should succeed") - - var response: DataResponse? - - // When - manager.request(urlRequest) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - XCTAssertEqual(response?.response?.headers["Request-Header"], "foobar") - XCTAssertEqual(response?.response?.headers["Session-Configuration-Header"], "foo") - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift deleted file mode 100644 index f2e0cf3..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift +++ /dev/null @@ -1,734 +0,0 @@ -// -// UploadTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Alamofire -import Foundation -import XCTest - -class UploadFileInitializationTestCase: BaseTestCase { - func testUploadClassMethodWithMethodURLAndFile() { - // Given - let urlString = "https://httpbin.org/post" - let imageURL = url(forResource: "rainbow", withExtension: "jpg") - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(imageURL, to: urlString).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - XCTAssertNotNil(request.response, "response should not be nil") - } - - func testUploadClassMethodWithMethodURLHeadersAndFile() { - // Given - let urlString = "https://httpbin.org/post" - let headers: HTTPHeaders = ["Authorization": "123456"] - let imageURL = url(forResource: "rainbow", withExtension: "jpg") - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(imageURL, to: urlString, method: .post, headers: headers).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - - let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" - XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") - - XCTAssertNotNil(request.response, "response should not be nil") - } -} - -// MARK: - - -class UploadDataInitializationTestCase: BaseTestCase { - func testUploadClassMethodWithMethodURLAndData() { - // Given - let urlString = "https://httpbin.org/post" - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(Data(), to: urlString).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - XCTAssertNotNil(request.response, "response should not be nil") - } - - func testUploadClassMethodWithMethodURLHeadersAndData() { - // Given - let urlString = "https://httpbin.org/post" - let headers: HTTPHeaders = ["Authorization": "123456"] - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(Data(), to: urlString, headers: headers).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - - let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" - XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") - - XCTAssertNotNil(request.response, "response should not be nil") - } -} - -// MARK: - - -class UploadStreamInitializationTestCase: BaseTestCase { - func testUploadClassMethodWithMethodURLAndStream() { - // Given - let urlString = "https://httpbin.org/post" - let imageURL = url(forResource: "rainbow", withExtension: "jpg") - let imageStream = InputStream(url: imageURL)! - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(imageStream, to: urlString).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - XCTAssertNotNil(request.response, "response should not be nil") - } - - func testUploadClassMethodWithMethodURLHeadersAndStream() { - // Given - let urlString = "https://httpbin.org/post" - let imageURL = url(forResource: "rainbow", withExtension: "jpg") - let headers: HTTPHeaders = ["Authorization": "123456"] - let imageStream = InputStream(url: imageURL)! - let expectation = self.expectation(description: "upload should complete") - - // When - let request = AF.upload(imageStream, to: urlString, headers: headers).response { _ in - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request.request, "request should not be nil") - XCTAssertEqual(request.request?.httpMethod, "POST", "request HTTP method should be POST") - XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal") - - let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" - XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") - - XCTAssertNotNil(request.response, "response should not be nil, tasks: \(request.tasks)") - } -} - -// MARK: - - -class UploadDataTestCase: BaseTestCase { - func testUploadDataRequest() { - // Given - let urlString = "https://httpbin.org/post" - let data = Data("Lorem ipsum dolor sit amet".utf8) - - let expectation = self.expectation(description: "Upload request should succeed: \(urlString)") - var response: DataResponse? - - // When - AF.upload(data, to: urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNil(response?.error) - } - - func testUploadDataRequestWithProgress() { - // Given - let urlString = "https://httpbin.org/post" - let string = String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", count: 100) - let data = Data(string.utf8) - - let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)") - - var uploadProgressValues: [Double] = [] - var downloadProgressValues: [Double] = [] - - var response: DataResponse? - - // When - AF.upload(data, to: urlString) - .uploadProgress { progress in - uploadProgressValues.append(progress.fractionCompleted) - } - .downloadProgress { progress in - downloadProgressValues.append(progress.fractionCompleted) - } - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0 - - for progress in uploadProgressValues { - XCTAssertGreaterThanOrEqual(progress, previousUploadProgress) - previousUploadProgress = progress - } - - if let lastProgressValue = uploadProgressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in uploadProgressValues should not be nil") - } - - var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0 - - for progress in downloadProgressValues { - XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress) - previousDownloadProgress = progress - } - - if let lastProgressValue = downloadProgressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in downloadProgressValues should not be nil") - } - } -} - -// MARK: - - -class UploadMultipartFormDataTestCase: BaseTestCase { - // MARK: Tests - - func testThatUploadingMultipartFormDataSetsContentTypeHeader() { - // Given - let urlString = "https://httpbin.org/post" - let uploadData = Data("upload_data".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - - var formData: MultipartFormData? - var response: DataResponse? - - // When - AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(uploadData, withName: "upload_data") - formData = multipartFormData - }, - to: urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - if - let request = response?.request, - let multipartFormData = formData, - let contentType = request.value(forHTTPHeaderField: "Content-Type") { - XCTAssertEqual(contentType, multipartFormData.contentType) - } else { - XCTFail("Content-Type header value should not be nil") - } - } - - func testThatCustomBoundaryCanBeSetWhenUploadingMultipartFormData() throws { - // Given - let urlRequest = try URLRequest(url: "https://httpbin.org/post", method: .post) - let uploadData = Data("upload_data".utf8) - - let formData = MultipartFormData(fileManager: .default, boundary: "custom-test-boundary") - formData.append(uploadData, withName: "upload_data") - - let expectation = self.expectation(description: "multipart form data upload should succeed") - var response: DataResponse? - - // When - AF.upload(multipartFormData: formData, with: urlRequest).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - if let request = response?.request, let contentType = request.value(forHTTPHeaderField: "Content-Type") { - XCTAssertEqual(contentType, formData.contentType) - XCTAssertTrue(contentType.contains("boundary=custom-test-boundary")) - } else { - XCTFail("Content-Type header value should not be nil") - } - } - - func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() { - // Given - let urlString = "https://httpbin.org/post" - let frenchData = Data("français".utf8) - let japaneseData = Data("日本語".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - var response: DataResponse? - - // When - AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(frenchData, withName: "french") - multipartFormData.append(japaneseData, withName: "japanese") - }, - to: urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - } - - func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() { - executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) - } - - func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { - executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) - } - - func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() { - // Given - let urlString = "https://httpbin.org/post" - let frenchData = Data("français".utf8) - let japaneseData = Data("日本語".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - var response: DataResponse? - - // When - let request = AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(frenchData, withName: "french") - multipartFormData.append(japaneseData, withName: "japanese") - }, - to: urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - guard let uploadable = request.uploadable, case .data = uploadable else { - XCTFail("Uploadable is not .data") - return - } - - XCTAssertTrue(response?.result.isSuccess == true) - } - - func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() { - // Given - let urlString = "https://httpbin.org/post" - let uploadData = Data("upload_data".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - - var formData: MultipartFormData? - var response: DataResponse? - - // When - let request = AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(uploadData, withName: "upload_data") - formData = multipartFormData - }, - to: urlString) - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - guard let uploadable = request.uploadable, case .data = uploadable else { - XCTFail("Uploadable is not .data") - return - } - - if - let request = response?.request, - let multipartFormData = formData, - let contentType = request.value(forHTTPHeaderField: "Content-Type") { - XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") - } else { - XCTFail("Content-Type header value should not be nil") - } - } - - func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() { - // Given - let urlString = "https://httpbin.org/post" - let frenchData = Data("français".utf8) - let japaneseData = Data("日本語".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - var response: DataResponse? - - // When - let request = AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(frenchData, withName: "french") - multipartFormData.append(japaneseData, withName: "japanese") - }, - to: urlString, - usingThreshold: 0).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - guard let uploadable = request.uploadable, case let .file(url, _) = uploadable else { - XCTFail("Uploadable is not .file") - return - } - - XCTAssertTrue(response?.result.isSuccess == true) - XCTAssertFalse(FileManager.default.fileExists(atPath: url.path)) - } - - func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() { - // Given - let urlString = "https://httpbin.org/post" - let uploadData = Data("upload_data".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - var response: DataResponse? - var formData: MultipartFormData? - - // When - let request = AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(uploadData, withName: "upload_data") - formData = multipartFormData - }, - to: urlString, - usingThreshold: 0).response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - guard let uploadable = request.uploadable, case .file = uploadable else { - XCTFail("Uploadable is not .file") - return - } - - XCTAssertTrue(response?.result.isSuccess == true) - - if - let request = response?.request, - let multipartFormData = formData, - let contentType = request.value(forHTTPHeaderField: "Content-Type") { - XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") - } else { - XCTFail("Content-Type header value should not be nil") - } - } - -#if os(macOS) - func disabled_testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { - // Given - let manager: Session = { - let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)" - let configuration = URLSessionConfiguration.background(withIdentifier: identifier) - - return Session(configuration: configuration) - }() - - let urlString = "https://httpbin.org/post" - let french = Data("français".utf8) - let japanese = Data("日本語".utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - - var request: URLRequest? - var response: HTTPURLResponse? - var data: Data? - var error: AFError? - - // When - let upload = manager.upload(multipartFormData: { multipartFormData in - multipartFormData.append(french, withName: "french") - multipartFormData.append(japanese, withName: "japanese") - }, - to: urlString) - .response { defaultResponse in - request = defaultResponse.request - response = defaultResponse.response - data = defaultResponse.data - error = defaultResponse.error - - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(request, "request should not be nil") - XCTAssertNotNil(response, "response should not be nil") - XCTAssertNotNil(data, "data should not be nil") - XCTAssertNil(error, "error should be nil") - - guard let uploadable = upload.uploadable, case .file = uploadable else { - XCTFail("Uploadable is not .file") - return - } - } -#endif - - // MARK: Combined Test Execution - - private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) { - // Given - let urlString = "https://httpbin.org/post" - let loremData1 = Data(String(repeating: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", - count: 100).utf8) - let loremData2 = Data(String(repeating: "Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.", - count: 100).utf8) - - let expectation = self.expectation(description: "multipart form data upload should succeed") - - var uploadProgressValues: [Double] = [] - var downloadProgressValues: [Double] = [] - - var response: DataResponse? - - // When - AF.upload(multipartFormData: { multipartFormData in - multipartFormData.append(loremData1, withName: "lorem1") - multipartFormData.append(loremData2, withName: "lorem2") - }, - to: urlString, - usingThreshold: streamFromDisk ? 0 : 100_000_000) - .uploadProgress { progress in - uploadProgressValues.append(progress.fractionCompleted) - } - .downloadProgress { progress in - downloadProgressValues.append(progress.fractionCompleted) - } - .response { resp in - response = resp - expectation.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - XCTAssertNotNil(response?.data) - XCTAssertNil(response?.error) - - var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0 - - for progress in uploadProgressValues { - XCTAssertGreaterThanOrEqual(progress, previousUploadProgress) - previousUploadProgress = progress - } - - if let lastProgressValue = uploadProgressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in uploadProgressValues should not be nil") - } - - var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0 - - for progress in downloadProgressValues { - XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress) - previousDownloadProgress = progress - } - - if let lastProgressValue = downloadProgressValues.last { - XCTAssertEqual(lastProgressValue, 1.0) - } else { - XCTFail("last item in downloadProgressValues should not be nil") - } - } -} - -final class UploadRequestEventsTestCase: BaseTestCase { - func testThatUploadRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(eventMonitors: [eventMonitor]) - - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didCreateUploadable = expectation(description: "didCreateUploadable should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() } - eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidResumeTask = { _, _ in didResumeTask.fulfill() } - eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() } - eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() } - - // When - let request = session.upload(Data("PAYLOAD".utf8), - with: URLRequest.makeHTTPBinRequest(path: "post", method: .post)).response { _ in - responseHandler.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .finished) - } - - func testThatCancelledUploadRequestTriggersAllAppropriateLifetimeEvents() { - // Given - let eventMonitor = ClosureEventMonitor() - let session = Session(startRequestsImmediately: false, eventMonitors: [eventMonitor]) - - let taskDidFinishCollecting = expectation(description: "taskDidFinishCollecting should fire") - let didCreateInitialURLRequest = expectation(description: "didCreateInitialURLRequest should fire") - let didCreateURLRequest = expectation(description: "didCreateURLRequest should fire") - let didCreateTask = expectation(description: "didCreateTask should fire") - let didGatherMetrics = expectation(description: "didGatherMetrics should fire") - let didComplete = expectation(description: "didComplete should fire") - let didFinish = expectation(description: "didFinish should fire") - let didResume = expectation(description: "didResume should fire") - let didResumeTask = expectation(description: "didResumeTask should fire") - let didCreateUploadable = expectation(description: "didCreateUploadable should fire") - let didParseResponse = expectation(description: "didParseResponse should fire") - let didCancel = expectation(description: "didCancel should fire") - let didCancelTask = expectation(description: "didCancelTask should fire") - let responseHandler = expectation(description: "responseHandler should fire") - - eventMonitor.taskDidFinishCollectingMetrics = { _, _, _ in taskDidFinishCollecting.fulfill() } - eventMonitor.requestDidCreateInitialURLRequest = { _, _ in didCreateInitialURLRequest.fulfill() } - eventMonitor.requestDidCreateURLRequest = { _, _ in didCreateURLRequest.fulfill() } - eventMonitor.requestDidCreateTask = { _, _ in didCreateTask.fulfill() } - eventMonitor.requestDidGatherMetrics = { _, _ in didGatherMetrics.fulfill() } - eventMonitor.requestDidCompleteTaskWithError = { _, _, _ in didComplete.fulfill() } - eventMonitor.requestDidFinish = { _ in didFinish.fulfill() } - eventMonitor.requestDidResume = { _ in didResume.fulfill() } - eventMonitor.requestDidCreateUploadable = { _, _ in didCreateUploadable.fulfill() } - eventMonitor.requestDidParseResponse = { _, _ in didParseResponse.fulfill() } - eventMonitor.requestDidCancel = { _ in didCancel.fulfill() } - eventMonitor.requestDidCancelTask = { _, _ in didCancelTask.fulfill() } - - // When - let request = session.upload(Data("PAYLOAD".utf8), - with: URLRequest.makeHTTPBinRequest(path: "post", method: .post)).response { _ in - responseHandler.fulfill() - } - - eventMonitor.requestDidResumeTask = { _, _ in - request.cancel() - didResumeTask.fulfill() - } - - request.resume() - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(request.state, .cancelled) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ValidationTests.swift b/Lesson12/Carthage/Checkouts/Alamofire/Tests/ValidationTests.swift deleted file mode 100644 index 9ce93d8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/Tests/ValidationTests.swift +++ /dev/null @@ -1,902 +0,0 @@ -// -// ValidationTests.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -@testable import Alamofire -import Foundation -import XCTest - -final class StatusCodeValidationTestCase: BaseTestCase { - func testThatValidationForRequestWithAcceptableStatusCodeResponseSucceeds() { - // Given - let urlString = "https://httpbin.org/status/200" - - let expectation1 = expectation(description: "request should return 200 status code") - let expectation2 = expectation(description: "download should return 200 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(statusCode: 200..<300) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(statusCode: 200..<300) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() { - // Given - let urlString = "https://httpbin.org/status/404" - - let expectation1 = expectation(description: "request should return 404 status code") - let expectation2 = expectation(description: "download should return 404 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(statusCode: [200]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(statusCode: [200]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableStatusCode, true) - XCTAssertEqual(error?.responseCode, 404) - } - } - - func testThatValidationForRequestWithNoAcceptableStatusCodesFails() { - // Given - let urlString = "https://httpbin.org/status/201" - - let expectation1 = expectation(description: "request should return 201 status code") - let expectation2 = expectation(description: "download should return 201 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(statusCode: []) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(statusCode: []) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableStatusCode, true) - XCTAssertEqual(error?.responseCode, 201) - } - } -} - -// MARK: - - -final class ContentTypeValidationTestCase: BaseTestCase { - func testThatValidationForRequestWithAcceptableContentTypeResponseSucceeds() { - // Given - let urlString = "https://httpbin.org/ip" - - let expectation1 = expectation(description: "request should succeed and return ip") - let expectation2 = expectation(description: "download should succeed and return ip") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: ["application/json"]) - .validate(contentType: ["application/json; charset=utf-8"]) - .validate(contentType: ["application/json; q=0.8; charset=utf-8"]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: ["application/json"]) - .validate(contentType: ["application/json; charset=utf-8"]) - .validate(contentType: ["application/json; q=0.8; charset=utf-8"]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() { - // Given - let urlString = "https://httpbin.org/ip" - - let expectation1 = expectation(description: "request should succeed and return ip") - let expectation2 = expectation(description: "download should succeed and return ip") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: ["*/*"]) - .validate(contentType: ["application/*"]) - .validate(contentType: ["*/json"]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: ["*/*"]) - .validate(contentType: ["application/*"]) - .validate(contentType: ["*/json"]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() { - // Given - let urlString = "https://httpbin.org/xml" - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "download should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: ["application/octet-stream"]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: ["application/octet-stream"]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableContentType, true) - XCTAssertEqual(error?.responseContentType, "application/xml") - XCTAssertEqual(error?.acceptableContentTypes?.first, "application/octet-stream") - } - } - - func testThatValidationForRequestWithNoAcceptableContentTypeResponseFails() { - // Given - let urlString = "https://httpbin.org/xml" - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "download should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: []) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: []) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableContentType, true) - XCTAssertEqual(error?.responseContentType, "application/xml") - XCTAssertEqual(error?.acceptableContentTypes?.isEmpty, true) - } - } - - func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() { - // Given - let urlString = "https://httpbin.org/status/204" - - let expectation1 = expectation(description: "request should succeed and return no data") - let expectation2 = expectation(description: "download should succeed and return no data") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: []) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: []) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceedsWhenResponseIsNil() { - // Given - class MockManager: Session { - override func request(_ convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil) -> DataRequest { - let request = MockDataRequest(convertible: convertible, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self) - - perform(request) - - return request - } - - override func download(_ convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination?) - -> DownloadRequest { - let request = MockDownloadRequest(downloadable: .request(convertible), - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self, - destination: destination ?? MockDownloadRequest.defaultDestination) - - perform(request) - - return request - } - } - - class MockDataRequest: DataRequest { - override var response: HTTPURLResponse? { - return MockHTTPURLResponse(url: request!.url!, - statusCode: 204, - httpVersion: "HTTP/1.1", - headerFields: nil) - } - } - - class MockDownloadRequest: DownloadRequest { - override var response: HTTPURLResponse? { - return MockHTTPURLResponse(url: request!.url!, - statusCode: 204, - httpVersion: "HTTP/1.1", - headerFields: nil) - } - } - - class MockHTTPURLResponse: HTTPURLResponse { - override var mimeType: String? { return nil } - } - - let manager: Session = { - let configuration: URLSessionConfiguration = { - let configuration = URLSessionConfiguration.ephemeral - configuration.headers = HTTPHeaders.default - - return configuration - }() - - return MockManager(configuration: configuration) - }() - - let urlString = "https://httpbin.org/delete" - - let expectation1 = expectation(description: "request should be stubbed and return 204 status code") - let expectation2 = expectation(description: "download should be stubbed and return 204 status code") - - var requestResponse: DataResponse? - var downloadResponse: DownloadResponse? - - // When - manager.request(urlString, method: .delete) - .validate(contentType: ["*/*"]) - .response { resp in - requestResponse = resp - expectation1.fulfill() - } - - manager.download(urlString, method: .delete) - .validate(contentType: ["*/*"]) - .response { resp in - downloadResponse = resp - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestResponse?.response) - XCTAssertNotNil(requestResponse?.data) - XCTAssertNil(requestResponse?.error) - - XCTAssertEqual(requestResponse?.response?.statusCode, 204) - XCTAssertNil(requestResponse?.response?.mimeType) - - XCTAssertNotNil(downloadResponse?.response) - XCTAssertNotNil(downloadResponse?.fileURL) - XCTAssertNil(downloadResponse?.error) - - XCTAssertEqual(downloadResponse?.response?.statusCode, 204) - XCTAssertNil(downloadResponse?.response?.mimeType) - } -} - -// MARK: - - -final class MultipleValidationTestCase: BaseTestCase { - func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() { - // Given - let urlString = "https://httpbin.org/ip" - - let expectation1 = expectation(description: "request should succeed and return ip") - let expectation2 = expectation(description: "request should succeed and return ip") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(statusCode: 200..<300) - .validate(contentType: ["application/json"]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() { - // Given - let urlString = "https://httpbin.org/xml" - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "download should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(statusCode: 400..<600) - .validate(contentType: ["application/octet-stream"]) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(statusCode: 400..<600) - .validate(contentType: ["application/octet-stream"]) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableStatusCode, true) - XCTAssertEqual(error?.responseCode, 200) - } - } - - func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() { - // Given - let urlString = "https://httpbin.org/xml" - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "download should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(contentType: ["application/octet-stream"]) - .validate(statusCode: 400..<600) - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(contentType: ["application/octet-stream"]) - .validate(statusCode: 400..<600) - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableContentType, true) - XCTAssertEqual(error?.responseContentType, "application/xml") - XCTAssertEqual(error?.acceptableContentTypes?.first, "application/octet-stream") - } - } -} - -// MARK: - - -final class AutomaticValidationTestCase: BaseTestCase { - func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() { - // Given - let url = URL(string: "https://httpbin.org/ip")! - var urlRequest = URLRequest(url: url) - urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") - - let expectation1 = expectation(description: "request should succeed and return ip") - let expectation2 = expectation(description: "download should succeed and return ip") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlRequest).validate().response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlRequest).validate().response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() { - // Given - let urlString = "https://httpbin.org/status/404" - - let expectation1 = expectation(description: "request should return 404 status code") - let expectation2 = expectation(description: "download should return 404 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate() - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate() - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableStatusCode, true) - XCTAssertEqual(error?.responseCode, 404) - } - } - - func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() { - // Given - let url = URL(string: "https://httpbin.org/ip")! - var urlRequest = URLRequest(url: url) - urlRequest.setValue("application/*", forHTTPHeaderField: "Accept") - - let expectation1 = expectation(description: "request should succeed and return ip") - let expectation2 = expectation(description: "download should succeed and return ip") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlRequest).validate().response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlRequest).validate().response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() { - // Given - let url = URL(string: "https://httpbin.org/xml")! - var urlRequest = URLRequest(url: url) - - let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5" - urlRequest.setValue(headerValue, forHTTPHeaderField: "Accept") - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "request should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlRequest).validate().response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlRequest).validate().response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() { - // Given - let url = URL(string: "https://httpbin.org/xml")! - var urlRequest = URLRequest(url: url) - urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") - - let expectation1 = expectation(description: "request should succeed and return xml") - let expectation2 = expectation(description: "download should succeed and return xml") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlRequest).validate().response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlRequest).validate().response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNotNil(requestError) - XCTAssertNotNil(downloadError) - - for error in [requestError, downloadError] { - XCTAssertEqual(error?.isUnacceptableContentType, true) - XCTAssertEqual(error?.responseContentType, "application/xml") - XCTAssertEqual(error?.acceptableContentTypes?.first, "application/json") - } - } -} - -// MARK: - - -private enum ValidationError: Error { - case missingData, missingFile, fileReadFailed -} - -extension DataRequest { - func validateDataExists() -> Self { - return validate { _, _, data in - guard data != nil else { return .failure(ValidationError.missingData) } - return .success(Void()) - } - } - - func validate(with error: Error) -> Self { - return validate { _, _, _ in .failure(error) } - } -} - -extension DownloadRequest { - func validateDataExists() -> Self { - return validate { _, _, _ in - let fileURL = self.fileURL - - guard let validFileURL = fileURL else { return .failure(ValidationError.missingFile) } - - do { - _ = try Data(contentsOf: validFileURL) - return .success(Void()) - } catch { - return .failure(ValidationError.fileReadFailed) - } - } - } - - func validate(with error: Error) -> Self { - return validate { _, _, _ in .failure(error) } - } -} - -// MARK: - - -final class CustomValidationTestCase: BaseTestCase { - func testThatCustomValidationClosureHasAccessToServerResponseData() { - // Given - let urlString = "https://httpbin.org/get" - - let expectation1 = expectation(description: "request should return 200 status code") - let expectation2 = expectation(description: "download should return 200 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate { _, _, data in - guard data != nil else { return .failure(ValidationError.missingData) } - return .success(Void()) - } - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate { _, _, fileURL in - guard let fileURL = fileURL else { return .failure(ValidationError.missingFile) } - - do { - _ = try Data(contentsOf: fileURL) - return .success(Void()) - } catch { - return .failure(ValidationError.fileReadFailed) - } - } - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatCustomValidationCanThrowCustomError() { - // Given - let urlString = "https://httpbin.org/get" - - let expectation1 = expectation(description: "request should return 200 status code") - let expectation2 = expectation(description: "download should return 200 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate { _, _, _ in .failure(ValidationError.missingData) } - .validate { _, _, _ in .failure(ValidationError.missingFile) } // should be ignored - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate { _, _, _ in .failure(ValidationError.missingFile) } - .validate { _, _, _ in .failure(ValidationError.fileReadFailed) } // should be ignored - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(requestError?.asAFError?.underlyingError as? ValidationError, .missingData) - XCTAssertEqual(downloadError?.asAFError?.underlyingError as? ValidationError, .missingFile) - } - - func testThatValidationExtensionHasAccessToServerResponseData() { - // Given - let urlString = "https://httpbin.org/get" - - let expectation1 = expectation(description: "request should return 200 status code") - let expectation2 = expectation(description: "download should return 200 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validateDataExists() - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validateDataExists() - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertNil(requestError) - XCTAssertNil(downloadError) - } - - func testThatValidationExtensionCanThrowCustomError() { - // Given - let urlString = "https://httpbin.org/get" - - let expectation1 = expectation(description: "request should return 200 status code") - let expectation2 = expectation(description: "download should return 200 status code") - - var requestError: AFError? - var downloadError: AFError? - - // When - AF.request(urlString) - .validate(with: ValidationError.missingData) - .validate(with: ValidationError.missingFile) // should be ignored - .response { resp in - requestError = resp.error - expectation1.fulfill() - } - - AF.download(urlString) - .validate(with: ValidationError.missingFile) - .validate(with: ValidationError.fileReadFailed) // should be ignored - .response { resp in - downloadError = resp.error - expectation2.fulfill() - } - - waitForExpectations(timeout: timeout, handler: nil) - - // Then - XCTAssertEqual(requestError?.asAFError?.underlyingError as? ValidationError, .missingData) - XCTAssertEqual(downloadError?.asAFError?.underlyingError as? ValidationError, .missingFile) - } -} diff --git a/Lesson12/Carthage/Checkouts/Alamofire/alamofire.png b/Lesson12/Carthage/Checkouts/Alamofire/alamofire.png deleted file mode 100644 index 2c27732..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/alamofire.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes.html deleted file mode 100644 index 8036fca..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes.html +++ /dev/null @@ -1,1503 +0,0 @@ - - - - Classes Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Classes

-

The following classes are available globally.

- -
-
- -
-
-
- -
-
-
    -
  • -
    - - - - MultipartFormData - -
    -
    -
    -
    -
    -
    -

    Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode -multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.

    - -

    For more information on multipart/form-data in general, please refer to the RFC-2388 and RFC-2045 specs as well -and the w3 form documentation.

    - - - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class MultipartFormData
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and -WiFi network interfaces.

    - -

    Reachability can be used to determine background information about why a network operation failed, or to retry -network requests when a connection is established. It should not be used to prevent a user from initiating a network -request, as it’s possible that an initial request may be required to establish reachability.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class NetworkReachabilityManager
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Request - -
    -
    -
    -
    -
    -
    -

    Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback -handling.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - JSONParameterEncoder - -
    -
    -
    -
    -
    -
    -

    A ParameterEncoder that encodes types as JSON body data.

    - -

    If no Content-Type header is already set on the provided URLRequests, it’s set to application/json.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class JSONParameterEncoder : ParameterEncoder
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -on the Destination set.

    - -

    If no Content-Type header is already set on the provided URLRequests, it will be set to -application/x-www-form-urlencoded; charset=utf-8.

    - -

    Encoding behavior can be customized by passing an instance of URLEncodedFormEncoder to the initializer.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class URLEncodedFormParameterEncoder : ParameterEncoder
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DataRequest - -
    -
    -
    -
    -
    -
    -

    Request subclass which handles in-memory Data download using URLSessionDataTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class DataRequest : Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DownloadRequest - -
    -
    -
    -
    -
    -
    -

    Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class DownloadRequest : Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - UploadRequest - -
    -
    -
    -
    -
    -
    -

    DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class UploadRequest : DataRequest
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
-
- -
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a -request returning nil or no data is considered an error. However, if the response is has a status code valid for -empty responses (204, 205), then an empty Data value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DataResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no -data is considered an error. However, if the response is has a status code valid for empty responses (204, 205), -then an empty String is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class StringResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning -nil or no data is considered an error. However, if the response is has a status code valid for empty responses -(204, 205), then an NSNull value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class JSONResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data as a generic value using any type that conforms to -DataDecoder. By default, this is an instance of JSONDecoder. Additionally, a request returning nil or no data -is considered an error. However, if the response is has a status code valid for empty responses (204, 205), then -the Empty.value value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DecodableResponseSerializer<T> : ResponseSerializer where T : Decodable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RetryPolicy - -
    -
    -
    -
    -
    -
    -

    A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -as well as certain types of networking errors.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class RetryPolicy : RequestInterceptor
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A retry policy that automatically retries idempotent requests for network connection lost errors. For more -information about retrying network connection lost errors, please refer to Apple’s -technical document.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class ConnectionLostRetryPolicy : RetryPolicy
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
    -
  • -
    - - - - DefaultTrustEvaluator - -
    -
    -
    -
    -
    -
    -

    An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -host provided by the challenge. Applications are encouraged to always validate the host in production environments -to guarantee the validity of the server’s certificate chain.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DefaultTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -environments to guarantee the validity of the server’s certificate chain.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class RevocationTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -certificates match one of the server certificates. By validating both the certificate chain and host, certificate -pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class PinnedCertificatesTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -public keys match one of the server certificate public keys. By validating both the certificate chain and host, -public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class PublicKeysTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -evaluators consider it valid.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class CompositeTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DisabledEvaluator - -
    -
    -
    -
    -
    -
    -

    Disables all evaluation which in turn will always consider any server trust as valid.

    - -

    THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DisabledEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Session - -
    -
    -
    -
    -
    -
    -

    Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common -functionality for all Requests, including queuing, interception, trust management, redirect handling, and response -cache handling.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class Session
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - SessionDelegate - -
    -
    -
    -
    -
    -
    -

    Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class SessionDelegate : NSObject
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLEncodedFormEncoder - -
    -
    -
    -
    -
    -
    -

    An object that encodes instances into URL-encoded query strings.

    - -

    There is no published specification for how to encode collection types. By default, the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

    - -

    BoolEncoding can be used to configure how Bool values are encoded. The default behavior is to encode -true as 1 and false as 0.

    - -

    DateEncoding can be used to configure how Date values are encoded. By default, the .deferredToDate -strategy is used, which formats dates from their structure.

    - -

    SpaceEncoding can be used to configure how spaces are encoded. Modern encodings use percent replacement (%20), -while older encodings may expect spaces to be replaced with +.

    - -

    This type is largely based on Vapor’s url-encoded-form project.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class URLEncodedFormEncoder
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Adapter.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Adapter.html deleted file mode 100644 index a813e98..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Adapter.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - Adapter Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Adapter

-
-
-
open class Adapter : RequestInterceptor
- -
-
-

Closure-based RequestAdapter.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ adaptHandler: @escaping AdaptHandler)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - adaptHandler - - -
    -

    AdaptHandler closure to be executed when handling request adaptation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/AlamofireNotifications.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/AlamofireNotifications.html deleted file mode 100644 index eafae49..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/AlamofireNotifications.html +++ /dev/null @@ -1,659 +0,0 @@ - - - - AlamofireNotifications Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireNotifications

-
-
-
public final class AlamofireNotifications : EventMonitor
- -
-
-

EventMonitor that provides Alamofire’s notifications.

- -
-
- -
-
-
-
    -
  • -
    - - - - requestDidResume(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidResume(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidSuspend(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidSuspend(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidCancel(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidCancel(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidFinish(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidFinish(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didResumeTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didSuspendTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didCancelTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ClosureEventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ClosureEventMonitor.html deleted file mode 100644 index 90cea72..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ClosureEventMonitor.html +++ /dev/null @@ -1,2636 +0,0 @@ - - - - ClosureEventMonitor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ClosureEventMonitor

-
-
-
open class ClosureEventMonitor : EventMonitor
- -
-
-

EventMonitor that allows optional closures to be set to receive events.

- -
-
- -
-
-
- -
-
- - -
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeEventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeEventMonitor.html deleted file mode 100644 index 8d17ddb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeEventMonitor.html +++ /dev/null @@ -1,1572 +0,0 @@ - - - - CompositeEventMonitor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CompositeEventMonitor

-
-
-
public final class CompositeEventMonitor : EventMonitor
- -
-
-

An EventMonitor which can contain multiple EventMonitors and calls their methods on their queues.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeTrustEvaluator.html deleted file mode 100644 index a3bd6f0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/CompositeTrustEvaluator.html +++ /dev/null @@ -1,524 +0,0 @@ - - - - CompositeTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CompositeTrustEvaluator

-
-
-
public final class CompositeTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -evaluators consider it valid.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(evaluators:) - -
    -
    -
    -
    -
    -
    -

    Creates a CompositeTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(evaluators: [ServerTrustEvaluating])
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - evaluators - - -
    -

    The ServerTrustEvaluating values used to evaluate the server trust.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ConnectionLostRetryPolicy.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ConnectionLostRetryPolicy.html deleted file mode 100644 index 36dedcd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ConnectionLostRetryPolicy.html +++ /dev/null @@ -1,542 +0,0 @@ - - - - ConnectionLostRetryPolicy Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionLostRetryPolicy

-
-
-
open class ConnectionLostRetryPolicy : RetryPolicy
- -
-
-

A retry policy that automatically retries idempotent requests for network connection lost errors. For more -information about retrying network connection lost errors, please refer to Apple’s -technical document.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataRequest.html deleted file mode 100644 index 29487ce..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataRequest.html +++ /dev/null @@ -1,1240 +0,0 @@ - - - - DataRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataRequest

-
-
-
public class DataRequest : Request
- -
-
-

Request subclass which handles in-memory Data download using URLSessionDataTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - convertible - -
    -
    -
    -
    -
    -
    -

    URLRequestConvertible value used to create URLRequests for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let convertible: URLRequestConvertible
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    Data read from the server so far.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var data: Data? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(_:) - -
    -
    -
    -
    -
    -
    -

    Validates the request, using the specified closure.

    -
    -

    Note

    -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate(_ validation: @escaping Validation) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validation - - -
    -

    Validation closure used to validate the response.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
    -                                                                 responseSerializer: Serializer,
    -                                                                 completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default

    -
    -
    - - responseSerializer - - -
    -

    The response serializer responsible for serializing the request, response, and data.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseData(queue: DispatchQueue = .main,
    -                         completionHandler: @escaping (AFDataResponse<Data>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseString(queue: DispatchQueue = .main,
    -                           encoding: String.Encoding? = nil,
    -                           completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - encoding - - -
    -

    The string encoding. Defaults to nil, in which case the encoding will be determined from - the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseJSON(queue: DispatchQueue = .main,
    -                         options: JSONSerialization.ReadingOptions = .allowFragments,
    -                         completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - options - - -
    -

    The JSON serialization reading options. .allowFragments by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
    -                                            queue: DispatchQueue = .main,
    -                                            decoder: DataDecoder = JSONDecoder(),
    -                                            completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - type - - -
    -

    Decodable type to decode from response data.

    -
    -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - decoder - - -
    -

    DataDecoder to use to decode the response. JSONDecoder() by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Validation - -
    -
    -
    -
    -
    -
    -

    A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the -request was valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(statusCode:) - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sequence, S.Element == Int
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - range - - -
    -

    The range of acceptable status codes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates that the response has a content type in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - contentType - - -
    -

    The acceptable content types, which may specify wildcard types and/or subtypes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the default acceptable range of 200…299, and that the content -type matches any specified in the Accept HTTP header field.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataResponseSerializer.html deleted file mode 100644 index d3e9ea9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DataResponseSerializer.html +++ /dev/null @@ -1,629 +0,0 @@ - - - - DataResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponseSerializer

-
-
-
public final class DataResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a -request returning nil or no data is considered an error. However, if the response is has a status code valid for -empty responses (204, 205), then an empty Data value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
    -            emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DecodableResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DecodableResponseSerializer.html deleted file mode 100644 index cecd9d9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DecodableResponseSerializer.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - DecodableResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DecodableResponseSerializer

-
-
-
public final class DecodableResponseSerializer<T> : ResponseSerializer where T : Decodable
- -
-
-

A ResponseSerializer that decodes the response data as a generic value using any type that conforms to -DataDecoder. By default, this is an instance of JSONDecoder. Additionally, a request returning nil or no data -is considered an error. However, if the response is has a status code valid for empty responses (204, 205), then -the Empty.value value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - decoder - -
    -
    -
    -
    -
    -
    -

    The DataDecoder instance used to decode responses.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let decoder: DataDecoder
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the values provided.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
    -            decoder: DataDecoder = JSONDecoder(),
    -            emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - decoder - - -
    -

    The DataDecoder. JSONDecoder() by default.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DefaultTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DefaultTrustEvaluator.html deleted file mode 100644 index 2384515..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DefaultTrustEvaluator.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - DefaultTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DefaultTrustEvaluator

-
-
-
public final class DefaultTrustEvaluator : ServerTrustEvaluating
- -
-
-

An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -host provided by the challenge. Applications are encouraged to always validate the host in production environments -to guarantee the validity of the server’s certificate chain.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(validateHost:) - -
    -
    -
    -
    -
    -
    -

    Creates a DefaultTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host. true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DisabledEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DisabledEvaluator.html deleted file mode 100644 index 66f02a1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DisabledEvaluator.html +++ /dev/null @@ -1,506 +0,0 @@ - - - - DisabledEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DisabledEvaluator

-
-
-
public final class DisabledEvaluator : ServerTrustEvaluating
- -
-
-

Disables all evaluation which in turn will always consider any server trust as valid.

- -

THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest.html deleted file mode 100644 index 667fd36..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest.html +++ /dev/null @@ -1,1585 +0,0 @@ - - - - DownloadRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadRequest

-
-
-
public class DownloadRequest : Request
- -
-
-

Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - Options - -
    -
    -
    -
    -
    -
    -

    A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination -URL.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Options : OptionSet
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - Destination - -
    -
    -
    -
    -
    -
    -

    A closure executed once a download request has successfully completed in order to determine where to move the -temporary file written to during the download process. The closure takes two arguments: the temporary file URL -and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and -the options defining how the file should be moved.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Destination = (_ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a download file destination closure which uses the default file manager to move the temporary file to a -file URL in the first available directory with the specified search path directory and search path domain mask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
    -                                               in domain: FileManager.SearchPathDomainMask = .userDomainMask,
    -                                               options: Options = []) -> Destination
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - directory - - -
    -

    The search path directory. .documentDirectory by default.

    -
    -
    - - domain - - -
    -

    The search path domain mask. .userDomainMask by default.

    -
    -
    - - options - - -
    -

    DownloadRequest.Options used when moving the downloaded file to its destination. None by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The Destination closure.

    -
    -
    -
    -
  • -
  • -
    - - - - Downloadable - -
    -
    -
    -
    -
    -
    -

    Type describing the source used to create the underlying URLSessionDownloadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Downloadable
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - resumeData - -
    -
    -
    -
    -
    -
    -

    If the download is resumable and eventually cancelled, this value may be used to resume the download using the -download(resumingWith data:) API.

    -
    -

    Note

    - For more information about resumeData, see Apple’s documentation. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var resumeData: Data? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileURL - -
    -
    -
    -
    -
    -
    -

    If the download is successful, the URL where the file was downloaded.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var fileURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - downloadable - -
    -
    -
    -
    -
    -
    -

    Downloadable value used for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let downloadable: Downloadable
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a URLSessionTask from the provided resume data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - data - - -
    -

    Data used to resume the download.

    -
    -
    - - session - - -
    -

    URLSession used to create the URLSessionTask.

    -
    -
    -
    -
    -

    Return Value

    -

    The URLSessionTask created.

    -
    -
    -
    -
  • -
  • -
    - - - - cancel() - -
    -
    -
    -
    -
    -
    -

    Cancels the instance. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

    -
    -

    Note

    -

    This method will NOT produce resume data. If you wish to cancel and produce resume data, use - cancel(producingResumeData:) or cancel(byProducingResumeData:).

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public override func cancel() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Cancels the instance, optionally producing resume data. Once cancelled, a DownloadRequest can no longer be -resumed or suspended.

    -
    -

    Note

    -

    If producingResumeData is true, the resumeData property will be populated with any resume data, if - available.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Cancels the instance while producing resume data. Once cancelled, a DownloadRequest can no longer be resumed -or suspended.

    -
    -

    Note

    -

    The resume data passed to the completion handler will also be available on the instance’s resumeData - property.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - completionHandler - - -
    -

    The completion handler that is called when the download has been successfully - cancelled. It is not guaranteed to be called on a particular queue, so you may - want use an appropriate queue to perform your work.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - validate(_:) - -
    -
    -
    -
    -
    -
    -

    Validates the request, using the specified closure.

    -
    -

    Note

    -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate(_ validation: @escaping Validation) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validation - - -
    -

    Validation closure to validate the response.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response(queue: DispatchQueue = .main,
    -                     completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response<T: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
    -                                                            responseSerializer: T,
    -                                                            completionHandler: @escaping (AFDownloadResponse<T.SerializedObject>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - responseSerializer - - -
    -

    The response serializer responsible for serializing the request, response, and data - contained in the destination URL.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseData(queue: DispatchQueue = .main,
    -                         completionHandler: @escaping (AFDownloadResponse<Data>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseString(queue: DispatchQueue = .main,
    -                           encoding: String.Encoding? = nil,
    -                           completionHandler: @escaping (AFDownloadResponse<String>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - encoding - - -
    -

    The string encoding. Defaults to nil, in which case the encoding will be determined from - the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseJSON(queue: DispatchQueue = .main,
    -                         options: JSONSerialization.ReadingOptions = .allowFragments,
    -                         completionHandler: @escaping (AFDownloadResponse<Any>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - options - - -
    -

    The JSON serialization reading options. .allowFragments by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Validation - -
    -
    -
    -
    -
    -
    -

    A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a -destination URL, and returns whether the request was valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse, _ fileURL: URL?) -> ValidationResult
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(statusCode:) - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sequence, S.Element == Int
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - range - - -
    -

    The range of acceptable status codes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates that the response has a content type in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - contentType - - -
    -

    The acceptable content types, which may specify wildcard types and/or subtypes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the default acceptable range of 200…299, and that the content -type matches any specified in the Accept HTTP header field.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Downloadable.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Downloadable.html deleted file mode 100644 index 7e50954..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Downloadable.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - Downloadable Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Downloadable

-
-
-
public enum Downloadable
- -
-
-

Type describing the source used to create the underlying URLSessionDownloadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - request(_:) - -
    -
    -
    -
    -
    -
    -

    Download should be started from the URLRequest produced by the associated URLRequestConvertible value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case request(URLRequestConvertible)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumeData(_:) - -
    -
    -
    -
    -
    -
    -

    Download should be started from the associated resume Data value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case resumeData(Data)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Options.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Options.html deleted file mode 100644 index 8acc68e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/DownloadRequest/Options.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - Options Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Options

-
-
-
public struct Options : OptionSet
- -
-
-

A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination -URL.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Specifies that intermediate directories for the destination URL should be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let createIntermediateDirectories: DownloadRequest.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - removePreviousFile - -
    -
    -
    -
    -
    -
    -

    Specifies that any previous file at the destination URL should be removed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let removePreviousFile: DownloadRequest.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    -

    Returns the raw bitmask value of the option and satisfies the RawRepresentable protocol.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: Int
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: Int)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Interceptor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Interceptor.html deleted file mode 100644 index 3f3364c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Interceptor.html +++ /dev/null @@ -1,734 +0,0 @@ - - - - Interceptor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Interceptor

-
-
-
open class Interceptor : RequestInterceptor
- -
-
-

RequestInterceptor which can use multiple RequestAdapter and RequestRetrier values.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONParameterEncoder.html deleted file mode 100644 index b1845a4..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONParameterEncoder.html +++ /dev/null @@ -1,635 +0,0 @@ - - - - JSONParameterEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONParameterEncoder

-
-
-
open class JSONParameterEncoder : ParameterEncoder
- -
-
-

A ParameterEncoder that encodes types as JSON body data.

- -

If no Content-Type header is already set on the provided URLRequests, it’s set to application/json.

- -
-
- -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with default parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - prettyPrinted - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with JSONEncoder.outputFormatting set to .prettyPrinted.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var prettyPrinted: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sortedKeys - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with JSONEncoder.outputFormatting set to .sortedKeys.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
    -public static var sortedKeys: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoder - -
    -
    -
    -
    -
    -
    -

    JSONEncoder used to encode parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let encoder: JSONEncoder
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(encoder:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance with the provided JSONEncoder.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(encoder: JSONEncoder = JSONEncoder())
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - encoder - - -
    -

    The JSONEncoder. JSONEncoder() by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:into:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func encode<Parameters: Encodable>(_ parameters: Parameters?,
    -                                        into request: URLRequest) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONResponseSerializer.html deleted file mode 100644 index 9747d00..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/JSONResponseSerializer.html +++ /dev/null @@ -1,669 +0,0 @@ - - - - JSONResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONResponseSerializer

-
-
-
public final class JSONResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning -nil or no data is considered an error. However, if the response is has a status code valid for empty responses -(204, 205), then an NSNull value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    JSONSerialization.ReadingOptions used when serializing a response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let options: JSONSerialization.ReadingOptions
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance with the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
    -            emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
    -            options: JSONSerialization.ReadingOptions = .allowFragments)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    - - options - - -
    -

    The options to use. .allowFragments by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartFormData.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartFormData.html deleted file mode 100644 index 6c9e81d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartFormData.html +++ /dev/null @@ -1,1205 +0,0 @@ - - - - MultipartFormData Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartFormData

-
-
-
open class MultipartFormData
- -
-
-

Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode -multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.

- -

For more information on multipart/form-data in general, please refer to the RFC-2388 and RFC-2045 specs as well -and the w3 form documentation.

- - - -
-
- -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Default memory threshold used when encoding MultipartFormData, in bytes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let encodingMemoryThreshold: UInt64
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - contentType - -
    -
    -
    -
    -
    -
    -

    The Content-Type header value containing the boundary used to generate the multipart/form-data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open lazy var contentType: String { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - contentLength - -
    -
    -
    -
    -
    -
    -

    The content length of all body parts used to generate the multipart/form-data not including the boundaries.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var contentLength: UInt64 { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boundary - -
    -
    -
    -
    -
    -
    -

    The boundary used to separate the body parts in the encoded form data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boundary: String
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(fileManager: FileManager = .default, boundary: String? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - fileManager - - -
    -

    FileManager to use for file operations, if needed.

    -
    -
    - - boundary - - -
    -

    Boundary String used to separate body parts.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the data and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - data - - -
    -

    Data to encoding into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the Data in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the Data in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the data in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - append(_:withName:) - -
    -
    -
    -
    -
    -
    -

    Creates a body part from the file and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{generated filename} (HTTP Header)
    • -
    • Content-Type: #{generated mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary
    • -
    - -

    The filename in the Content-Disposition HTTP header is generated from the last path component of the -fileURL. The Content-Type HTTP header MIME type is generated by mapping the fileURL extension to the -system associated MIME type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ fileURL: URL, withName name: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - fileURL - - -
    -

    URL of the file whose content will be encoded into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the file and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - fileURL - - -
    -

    URL of the file whose content will be encoded into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the file content in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the stream and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded stream data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ stream: InputStream,
    -                   withLength length: UInt64,
    -                   name: String,
    -                   fileName: String,
    -                   mimeType: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - stream - - -
    -

    InputStream to encode into the instance.

    -
    -
    - - length - - -
    -

    Length, in bytes, of the stream.

    -
    -
    - - name - - -
    -

    Name to associate with the stream content in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the stream content in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the stream content in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part with the stream, length, and headers and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • HTTP headers
    • -
    • Encoded stream data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - stream - - -
    -

    InputStream to encode into the instance.

    -
    -
    - - length - - -
    -

    Length, in bytes, of the stream.

    -
    -
    - - headers - - -
    -

    HTTPHeaders for the body part.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode() - -
    -
    -
    -
    -
    -
    -

    Encodes all appended body parts into a single Data value.

    -
    -

    Note

    -

    This method will load all the appended body parts into memory all at the same time. This method should - only be used when the encoded data will have a small memory footprint. For large data cases, please use - the writeEncodedData(to:)) method.

    - -
    -
    -

    Throws

    -

    An AFError if encoding encounters an error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode() throws -> Data
    - -
    -
    -
    -

    Return Value

    -

    The encoded Data, if encoding is successful.

    -
    -
    -
    -
  • -
  • -
    - - - - writeEncodedData(to:) - -
    -
    -
    -
    -
    -
    -

    Writes all appended body parts to the given file URL.

    - -

    This process is facilitated by reading and writing with input and output streams, respectively. Thus, -this approach is very memory efficient and should be used for large body part data.

    -
    -

    Throws

    - An AFError if encoding encounters an error. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func writeEncodedData(to fileURL: URL) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - fileURL - - -
    -

    File URL to which to write the form data.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartUpload.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartUpload.html deleted file mode 100644 index 3af213d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/MultipartUpload.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - MultipartUpload Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartUpload

-
-
-
open class MultipartUpload
- -
-
-

Undocumented

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Default memory threshold used when encoding MultipartFormData, in bytes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let encodingMemoryThreshold: UInt64
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - createUploadable() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func createUploadable() throws -> UploadRequest.Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager.html deleted file mode 100644 index 95813dd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager.html +++ /dev/null @@ -1,917 +0,0 @@ - - - - NetworkReachabilityManager Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

NetworkReachabilityManager

-
-
-
open class NetworkReachabilityManager
- -
-
-

The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and -WiFi network interfaces.

- -

Reachability can be used to determine background information about why a network operation failed, or to retry -network requests when a connection is established. It should not be used to prevent a user from initiating a network -request, as it’s possible that an initial request may be required to establish reachability.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Defines the various states of network reachability.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum NetworkReachabilityStatus
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - Listener - -
    -
    -
    -
    -
    -
    -

    A closure executed when the network reachability status changes. The closure takes a single argument: the -network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Listener = (NetworkReachabilityStatus) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Default NetworkReachabilityManager for the zero address and a listenerQueue of .main.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let `default`: NetworkReachabilityManager?
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isReachable - -
    -
    -
    -
    -
    -
    -

    Whether the network is currently reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachable: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isReachableOnCellular - -
    -
    -
    -
    -
    -
    -

    Whether the network is currently reachable over the cellular interface.

    -
    -

    Note

    - Using this property to decide whether to make a high or low bandwidth request is not recommended. - Instead, set the allowsCellularAccess on any URLRequests being issued. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachableOnCellular: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Whether the network is currently reachable over Ethernet or WiFi interface.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachableOnEthernetOrWiFi: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - reachabilityQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue on which reachability will update.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let reachabilityQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - flags - -
    -
    -
    -
    -
    -
    -

    Flags of the current reachability type, if any.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var flags: SCNetworkReachabilityFlags? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - status - -
    -
    -
    -
    -
    -
    -

    The current network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var status: NetworkReachabilityStatus { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(host:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance with the specified host.

    -
    -

    Note

    -

    The host value must not contain a scheme, just the hostname.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init?(host: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    Host used to evaluate network reachability. Must not include the scheme (e.g. https).

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an instance that monitors the address 0.0.0.0.

    - -

    Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing -status of the device, both IPv4 and IPv6.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init?()
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Starts listening for changes in network reachability status.

    -
    -

    Note

    -

    Stops and removes any existing listener.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -open func startListening(onQueue queue: DispatchQueue = .main,
    -                         onUpdatePerforming listener: @escaping Listener) -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    DispatchQueue on which to call the listener closure. .main by default.

    -
    -
    - - listener - - -
    -

    Listener closure called when reachability changes.

    -
    -
    -
    -
    -

    Return Value

    -

    true if listening was started successfully, false otherwise.

    -
    -
    -
    -
  • -
  • -
    - - - - stopListening() - -
    -
    -
    -
    -
    -
    -

    Stops listening for changes in network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func stopListening()
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/ConnectionType.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/ConnectionType.html deleted file mode 100644 index 7c985da..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/ConnectionType.html +++ /dev/null @@ -1,490 +0,0 @@ - - - - ConnectionType Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionType

-
-
-
public enum ConnectionType
- -
-
-

Defines the various connection types detected by reachability flags.

- -
-
- -
-
-
-
    -
  • -
    - - - - ethernetOrWiFi - -
    -
    -
    -
    -
    -
    -

    The connection type is either over Ethernet or WiFi.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case ethernetOrWiFi
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - wwan - -
    -
    -
    -
    -
    -
    -

    The connection type is a WWAN connection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case wwan
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html deleted file mode 100644 index e266c59..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html +++ /dev/null @@ -1,560 +0,0 @@ - - - - NetworkReachabilityStatus Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

NetworkReachabilityStatus

-
-
-
public enum NetworkReachabilityStatus
- -
-
-

Defines the various states of network reachability.

- -
-
- -
-
-
-
    -
  • -
    - - - - unknown - -
    -
    -
    -
    -
    -
    -

    It is unknown whether the network is reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unknown
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - notReachable - -
    -
    -
    -
    -
    -
    -

    The network is not reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case notReachable
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - reachable(_:) - -
    -
    -
    -
    -
    -
    -

    The network is reachable on the associated ConnectionType.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case reachable(ConnectionType)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ConnectionType - -
    -
    -
    -
    -
    -
    -

    Defines the various connection types detected by reachability flags.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ConnectionType
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html deleted file mode 100644 index 60e2a93..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ConnectionType Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionType

-
-
-
public enum ConnectionType
- -
-
-

Defines the various connection types detected by reachability flags.

- -
-
- -
-
-
-
    -
  • -
    - - - - ethernetOrWiFi - -
    -
    -
    -
    -
    -
    -

    The connection type is either over Ethernet or WiFi.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case ethernetOrWiFi
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cellular - -
    -
    -
    -
    -
    -
    -

    The connection type is a cellular connection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cellular
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PinnedCertificatesTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PinnedCertificatesTrustEvaluator.html deleted file mode 100644 index 3b2ce6f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PinnedCertificatesTrustEvaluator.html +++ /dev/null @@ -1,572 +0,0 @@ - - - - PinnedCertificatesTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PinnedCertificatesTrustEvaluator

-
-
-
public final class PinnedCertificatesTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -certificates match one of the server certificates. By validating both the certificate chain and host, certificate -pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Creates a PinnedCertificatesTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
    -            acceptSelfSignedCertificates: Bool = false,
    -            performDefaultValidation: Bool = true,
    -            validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - certificates - - -
    -

    The certificates to use to evaluate the trust. All cer, crt, and der - certificates in Bundle.main by default.

    -
    -
    - - acceptSelfSignedCertificates - - -
    -

    Adds the provided certificates as anchors for the trust evaluation, allowing - self-signed certificates to pass. false by default. THIS SETTING SHOULD BE - FALSE IN PRODUCTION!

    -
    -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition - to performing the default evaluation, even if performDefaultValidation is - false. true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PublicKeysTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PublicKeysTrustEvaluator.html deleted file mode 100644 index a163875..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/PublicKeysTrustEvaluator.html +++ /dev/null @@ -1,563 +0,0 @@ - - - - PublicKeysTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PublicKeysTrustEvaluator

-
-
-
public final class PublicKeysTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -public keys match one of the server certificate public keys. By validating both the certificate chain and host, -public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Creates a PublicKeysTrustEvaluator.

    -
    -

    Note

    -

    Default and host validation will fail when using this evaluator with self-signed certificates. Use - PinnedCertificatesTrustEvaluator if you need to use self-signed certificates.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(keys: [SecKey] = Bundle.main.af.publicKeys,
    -            performDefaultValidation: Bool = true,
    -            validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - keys - - -
    -

    The SecKeys to use to validate public keys. Defaults to the public keys of all - certificates included in the main bundle.

    -
    -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition to - performing the default evaluation, even if performDefaultValidation is false. - true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request.html deleted file mode 100644 index 06988a3..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request.html +++ /dev/null @@ -1,2516 +0,0 @@ - - - - Request Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Request

-
-
-
public class Request
- -
-
-

Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback -handling.

- -
-
- -
-
-
- -
-
- -
    -
  • -
    - - - - id - -
    -
    -
    -
    -
    -
    -

    UUID providing a unique identifier for the Request, used in the Hashable and Equatable conformances.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let id: UUID
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - underlyingQueue - -
    -
    -
    -
    -
    -
    -

    The serial queue for all internal async actions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let underlyingQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationQueue - -
    -
    -
    -
    -
    -
    -

    The queue used for all serialization actions. By default it’s a serial queue that targets underlyingQueue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - eventMonitor - -
    -
    -
    -
    -
    -
    -

    EventMonitor used for event callbacks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let eventMonitor: EventMonitor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - interceptor - -
    -
    -
    -
    -
    -
    -

    The Request‘s interceptor.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let interceptor: RequestInterceptor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delegate - -
    -
    -
    -
    -
    -
    -

    The Request‘s delegate.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public private(set) weak var delegate: RequestDelegate?
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - state - -
    -
    -
    -
    -
    -
    -

    State of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var state: State { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isInitialized - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .initialized.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isInitialized: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isResumed - -
    -
    -
    -
    -
    -
    -

    Returns whether state is.resumed`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResumed: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSuspended - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .suspended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSuspended: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isCancelled - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .cancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCancelled: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isFinished - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isFinished: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ProgressHandler - -
    -
    -
    -
    -
    -
    -

    Closure type executed when monitoring the upload or download progress of a request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias ProgressHandler = (Progress) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - uploadProgress - -
    -
    -
    -
    -
    -
    -

    Progress of the upload of the body of the executed URLRequest. Reset to 0 if the Request is retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let uploadProgress: Progress
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - downloadProgress - -
    -
    -
    -
    -
    -
    -

    Progress of the download of any response data. Reset to 0 if the Request is retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let downloadProgress: Progress
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- - -
-
- -
    -
  • -
    - - - - credential - -
    -
    -
    -
    -
    -
    -

    URLCredential used for authentication challenges. Created by calling one of the authenticate methods.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public private(set) var credential: URLCredential? { get set }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - requests - -
    -
    -
    -
    -
    -
    -

    All URLRequests created on behalf of the Request, including original and adapted requests.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var requests: [URLRequest] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstRequest - -
    -
    -
    -
    -
    -
    -

    First URLRequest created on behalf of the Request. May not be the first one actually executed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastRequest - -
    -
    -
    -
    -
    -
    -

    Last URLRequest created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    Current URLRequest created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var request: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - performedRequests - -
    -
    -
    -
    -
    -
    -

    URLRequests from all of the URLSessionTasks executed on behalf of the Request. May be different from -requests due to URLSession manipulation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var performedRequests: [URLRequest] { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    HTTPURLResponse received from the server, if any. If the Request was retried, this is the response of the -last URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var response: HTTPURLResponse? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Tasks

-
-
-
    -
  • -
    - - - - tasks - -
    -
    -
    -
    -
    -
    -

    All URLSessionTasks created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var tasks: [URLSessionTask] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstTask - -
    -
    -
    -
    -
    -
    -

    First URLSessionTask created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstTask: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastTask - -
    -
    -
    -
    -
    -
    -

    Last URLSessionTask crated on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastTask: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - task - -
    -
    -
    -
    -
    -
    -

    Current URLSessionTask created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var task: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - allMetrics - -
    -
    -
    -
    -
    -
    -

    All URLSessionTaskMetrics gathered on behalf of the Request. Should correspond to the tasks created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var allMetrics: [URLSessionTaskMetrics] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstMetrics - -
    -
    -
    -
    -
    -
    -

    First URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstMetrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastMetrics - -
    -
    -
    -
    -
    -
    -

    Last URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastMetrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    Current URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var metrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - retryCount - -
    -
    -
    -
    -
    -
    -

    Number of times the Request has been retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var retryCount: Int { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Error

-
-
-
    -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Error returned from Alamofire internally, from the network request directly, or any validators executed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public fileprivate(set) var error: AFError? { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

State

-
-
-
    -
  • -
    - - - - cancel() - -
    -
    -
    -
    -
    -
    -

    Cancels the instance. Once cancelled, a Request can no longer be resumed or suspended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - suspend() - -
    -
    -
    -
    -
    -
    -

    Suspends the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func suspend() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - resume() - -
    -
    -
    -
    -
    -
    -

    Resumes the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func resume() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Associates a credential using the provided values with the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - username - - -
    -

    The username.

    -
    -
    - - password - - -
    -

    The password.

    -
    -
    - - persistence - - -
    -

    The URLCredential.Persistence for the created URLCredential. .forSession by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - authenticate(with:) - -
    -
    -
    -
    -
    -
    -

    Associates the provided credential with the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func authenticate(with credential: URLCredential) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - credential - - -
    -

    The URLCredential.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.

    -
    -

    Note

    -

    Only the last closure provided is used.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The DispatchQueue to execute the closure on. .main by default.

    -
    -
    - - closure - - -
    -

    The closure to be executed periodically as data is read from the server.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.

    -
    -

    Note

    -

    Only the last closure provided is used.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The DispatchQueue to execute the closure on. .main by default.

    -
    -
    - - closure - - -
    -

    The closure to be executed periodically as data is sent to the server.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - redirect(using:) - -
    -
    -
    -
    -
    -
    -

    Sets the redirect handler for the instance which will be used if a redirect response is encountered.

    -
    -

    Note

    -

    Attempting to set the redirect handler more than once is a logic error and will crash.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func redirect(using handler: RedirectHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - -
    -

    The RedirectHandler.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - cacheResponse(using:) - -
    -
    -
    -
    -
    -
    -

    Sets the cached response handler for the Request which will be used when attempting to cache a response.

    -
    -

    Note

    -

    Attempting to set the cache handler more than once is a logic error and will crash.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cacheResponse(using handler: CachedResponseHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a handler to be called when the cURL description of the request is available.

    -
    -

    Note

    -

    When waiting for a Request‘s URLRequest to be created, only the last handler will be called.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - -
    -

    Closure to be called when the cURL description is available.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - didResumeNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is resumed. The Notification contains the resumed Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didResumeNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a Request is suspended. The Notification contains the suspended Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didSuspendNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didCancelNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is cancelled. The Notification contains the cancelled Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCancelNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didFinishNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is finished. The Notification contains the completed Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didFinishNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is resumed. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didResumeTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is suspended. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didSuspendTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is cancelled. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCancelTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is completed. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCompleteTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ==(_:_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func == (lhs: Request, rhs: Request) -> Bool
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - hash(into:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func hash(into hasher: inout Hasher)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    A textual representation of this instance, including the HTTPMethod and URL if the URLRequest has been -created, as well as the response status code, if a response has been received.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - cURLDescription() - -
    -
    -
    -
    -
    -
    -

    cURL representation of the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cURLDescription() -> String
    - -
    -
    -
    -

    Return Value

    -

    The cURL equivalent of the instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ValidationResult - -
    -
    -
    -
    -
    -
    -

    Used to represent whether a validation succeeded or failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias ValidationResult = Result<Void, Error>
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request/State.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request/State.html deleted file mode 100644 index 4c19fef..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Request/State.html +++ /dev/null @@ -1,592 +0,0 @@ - - - - State Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

State

-
-
-
public enum State
- -
-
-

State of the Request, with managed transitions between states set when calling resume(), suspend(), or -cancel() on the Request.

- -
-
- -
-
-
-
    -
  • -
    - - - - initialized - -
    -
    -
    -
    -
    -
    -

    Initial state of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case initialized
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumed - -
    -
    -
    -
    -
    -
    -

    State set when resume() is called. Any tasks created for the Request will have resume() called on -them in this state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case resumed
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - suspended - -
    -
    -
    -
    -
    -
    -

    State set when suspend() is called. Any tasks created for the Request will have suspend() called on -them in this state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case suspended
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cancelled - -
    -
    -
    -
    -
    -
    -

    State set when cancel() is called. Any tasks created for the Request will have cancel() called on -them. Unlike resumed or suspended, once in the cancelled state, the Request can no longer transition -to any other state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cancelled
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - finished - -
    -
    -
    -
    -
    -
    -

    State set when all response serialization completion closures have been cleared on the Request and -enqueued on their respective queues.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case finished
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Retrier.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Retrier.html deleted file mode 100644 index fb14705..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Retrier.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - Retrier Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Retrier

-
-
-
open class Retrier : RequestInterceptor
- -
-
-

Closure-based RequestRetrier.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ retryHandler: @escaping RetryHandler)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - retryHandler - - -
    -

    RetryHandler closure to be executed when handling request retry.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func retry(_ request: Request,
    -                for session: Session,
    -                dueTo error: Error,
    -                completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RetryPolicy.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RetryPolicy.html deleted file mode 100644 index 7515cb8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RetryPolicy.html +++ /dev/null @@ -1,921 +0,0 @@ - - - - RetryPolicy Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RetryPolicy

-
-
-
open class RetryPolicy : RequestInterceptor
- -
-
-

A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -as well as certain types of networking errors.

- -
-
- -
-
-
-
    -
  • -
    - - - - defaultRetryLimit - -
    -
    -
    -
    -
    -
    -

    The default retry limit for retry policies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryLimit: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default exponential backoff base for retry policies (must be a minimum of 2).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultExponentialBackoffBase: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default exponential backoff scale for retry policies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultExponentialBackoffScale: Double
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default HTTP methods to retry. -See RFC 2616 - Section 9.1.2 for more information.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableHTTPMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default HTTP status codes to retry. -See RFC 2616 - Section 10 for more information.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableHTTPStatusCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default URL error codes to retry.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableURLErrorCodes: Set<URLError.Code>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryLimit - -
    -
    -
    -
    -
    -
    -

    The total number of times the request is allowed to be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryLimit: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The base of the exponential backoff policy (should always be greater than or equal to 2).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let exponentialBackoffBase: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The scale of the exponential backoff.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let exponentialBackoffScale: Double
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryableHTTPMethods - -
    -
    -
    -
    -
    -
    -

    The HTTP methods that are allowed to be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableHTTPMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The HTTP status codes that are automatically retried by the policy.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableHTTPStatusCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The URL error codes that are automatically retried by the policy.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableURLErrorCodes: Set<URLError.Code>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an ExponentialBackoffRetryPolicy from the specified parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
    -            exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
    -            exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
    -            retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
    -            retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
    -            retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - retryLimit - - -
    -

    The total number of times the request is allowed to be retried. 2 by default.

    -
    -
    - - exponentialBackoffBase - - -
    -

    The base of the exponential backoff policy. 2 by default.

    -
    -
    - - exponentialBackoffScale - - -
    -

    The scale of the exponential backoff. 0.5 by default.

    -
    -
    - - retryableHTTPMethods - - -
    -

    The HTTP methods that are allowed to be retried. - RetryPolicy.defaultRetryableHTTPMethods by default.

    -
    -
    - - retryableHTTPStatusCodes - - -
    -

    The HTTP status codes that are automatically retried by the policy. - RetryPolicy.defaultRetryableHTTPStatusCodes by default.

    -
    -
    - - retryableURLErrorCodes - - -
    -

    The URL error codes that are automatically retried by the policy. - RetryPolicy.defaultRetryableURLErrorCodes by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func retry(_ request: Request,
    -                for session: Session,
    -                dueTo error: Error,
    -                completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator.html deleted file mode 100644 index af7f782..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator.html +++ /dev/null @@ -1,590 +0,0 @@ - - - - RevocationTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RevocationTrustEvaluator

-
-
-
public final class RevocationTrustEvaluator : ServerTrustEvaluating
- -
-
-

An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -environments to guarantee the validity of the server’s certificate chain.

- -
-
- -
-
-
-
    -
  • -
    - - - - Options - -
    -
    -
    -
    -
    -
    -

    Represents the options to be use when evaluating the status of a certificate. -Only Revocation Policy Constants are valid, and can be found in Apple’s documentation.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Options : OptionSet
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a RevocationTrustEvaluator.

    -
    -

    Note

    -

    Default and host validation will fail when using this evaluator with self-signed certificates. Use - PinnedCertificatesTrustEvaluator if you need to use self-signed certificates.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition - to performing the default evaluation, even if performDefaultValidation is - false. true by default.

    -
    -
    - - options - - -
    -

    The Options to use to check the revocation status of the certificate. .any - by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator/Options.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator/Options.html deleted file mode 100644 index 9dec048..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/RevocationTrustEvaluator/Options.html +++ /dev/null @@ -1,689 +0,0 @@ - - - - Options Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Options

-
-
-
public struct Options : OptionSet
- -
-
-

Represents the options to be use when evaluating the status of a certificate. -Only Revocation Policy Constants are valid, and can be found in Apple’s documentation.

- -
-
- -
-
-
-
    -
  • -
    - - - - crl - -
    -
    -
    -
    -
    -
    -

    Perform revocation checking using the CRL (Certification Revocation List) method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let crl: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - networkAccessDisabled - -
    -
    -
    -
    -
    -
    -

    Consult only locally cached replies; do not use network access.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let networkAccessDisabled: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ocsp - -
    -
    -
    -
    -
    -
    -

    Perform revocation checking using OCSP (Online Certificate Status Protocol).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let ocsp: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preferCRL - -
    -
    -
    -
    -
    -
    -

    Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let preferCRL: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a -best attempt basis, where failure to reach the server is not considered fatal.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let requirePositiveResponse: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - any - -
    -
    -
    -
    -
    -
    -

    Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the -certificate and the value of preferCRL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let any: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    -

    The raw value of the option.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: CFOptionFlags
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    -

    Creates an Options value with the given CFOptionFlags.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: CFOptionFlags)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - rawValue - - -
    -

    The CFOptionFlags value to initialize with.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ServerTrustManager.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ServerTrustManager.html deleted file mode 100644 index e3db39b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/ServerTrustManager.html +++ /dev/null @@ -1,628 +0,0 @@ - - - - ServerTrustManager Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustManager

-
-
-
open class ServerTrustManager
- -
-
-

Responsible for managing the mapping of ServerTrustEvaluating values to given hosts.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether all hosts for this ServerTrustManager must be evaluated. true by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let allHostsMustBeEvaluated: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluators - -
    -
    -
    -
    -
    -
    -

    The dictionary of policies mapped to a particular host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let evaluators: [String : ServerTrustEvaluating]
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Initializes the ServerTrustManager instance with the given evaluators.

    - -

    Since different servers and web services can have different leaf certificates, intermediate and even root -certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This -allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key -pinning for host3 and disabling evaluation for host4.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String : ServerTrustEvaluating])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - allHostsMustBeEvaluated - - -
    -

    The value determining whether all hosts for this instance must be evaluated. true - by default.

    -
    -
    - - evaluators - - -
    -

    A dictionary of evaluators mapped to hosts.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns the ServerTrustEvaluating value for the given host, if one is set.

    - -

    By default, this method will return the policy that perfectly matches the given host. Subclasses could override -this method and implement more complex mapping implementations such as wildcards.

    -
    -

    Throws

    -

    AFError.serverTrustEvaluationFailed if allHostsMustBeEvaluated is true and no matching - evaluators are found.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The host to use when searching for a matching policy.

    -
    -
    -
    -
    -

    Return Value

    -

    The ServerTrustEvaluating value for the given host if found, nil otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Session.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Session.html deleted file mode 100644 index 4604000..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/Session.html +++ /dev/null @@ -1,3365 +0,0 @@ - - - - Session Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Session

-
-
-
open class Session
- -
-
-

Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common -functionality for all Requests, including queuing, interception, trust management, redirect handling, and response -cache handling.

- -
-
- -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Shared singleton instance used by all AF.request APIs. Cannot be modified.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let `default`: Session
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - session - -
    -
    -
    -
    -
    -
    -

    Underlying URLSession used to create URLSessionTasks for this instance, and for which this instance’s -delegate handles URLSessionDelegate callbacks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let session: URLSession
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delegate - -
    -
    -
    -
    -
    -
    -

    Instance’s SessionDelegate, which handles the URLSessionDelegate methods and Request interaction.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let delegate: SessionDelegate
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rootQueue - -
    -
    -
    -
    -
    -
    -

    Root DispatchQueue for all internal callbacks and state update. MUST be a serial queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rootQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Value determining whether this instance automatically calls resume() on all created Requests.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let startRequestsImmediately: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue on which URLRequests are created asynchronously. By default this queue uses rootQueue as its -target, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile -and test before introducing an additional queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let requestQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue passed to all Requests on which they perform their response serialization. By default this -queue uses rootQueue as its target but a separate queue can be used if response serialization is determined -to be a bottleneck. Always profile and test before introducing an additional queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - interceptor - -
    -
    -
    -
    -
    -
    -

    RequestInterceptor used for all Request created by the instance. RequestInterceptors can also be set on a -per-Request basis, in which case the Request‘s interceptor takes precedence over this value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let interceptor: RequestInterceptor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serverTrustManager - -
    -
    -
    -
    -
    -
    -

    ServerTrustManager instance used to evaluate all trust challenges and provide certificate and key pinning.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serverTrustManager: ServerTrustManager?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - redirectHandler - -
    -
    -
    -
    -
    -
    -

    RedirectHandler instance used to provide customization for request redirection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let redirectHandler: RedirectHandler?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    CachedResponseHandler instance used to provide customization of cached response handling.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let cachedResponseHandler: CachedResponseHandler?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - eventMonitor - -
    -
    -
    -
    -
    -
    -

    CompositeEventMonitor used to compose Alamofire’s defaultEventMonitors and any passed EventMonitors.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let eventMonitor: CompositeEventMonitor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEventMonitors - -
    -
    -
    -
    -
    -
    -

    EventMonitors included in all instances. [AlamofireNotifications()] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let defaultEventMonitors: [EventMonitor]
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a Session from a URLSession and other parameters.

    -
    -

    Note

    -

    When passing a URLSession, you must create the URLSession with a specific delegateQueue value and - pass the delegateQueue‘s underlyingQueue as the rootQueue parameter of this initializer.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(session: URLSession,
    -            delegate: SessionDelegate,
    -            rootQueue: DispatchQueue,
    -            startRequestsImmediately: Bool = true,
    -            requestQueue: DispatchQueue? = nil,
    -            serializationQueue: DispatchQueue? = nil,
    -            interceptor: RequestInterceptor? = nil,
    -            serverTrustManager: ServerTrustManager? = nil,
    -            redirectHandler: RedirectHandler? = nil,
    -            cachedResponseHandler: CachedResponseHandler? = nil,
    -            eventMonitors: [EventMonitor] = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - session - - -
    -

    Underlying URLSession for this instance.

    -
    -
    - - delegate - - -
    -

    SessionDelegate that handles session‘s delegate callbacks as well as Request - interaction.

    -
    -
    - - rootQueue - - -
    -

    Root DispatchQueue for all internal callbacks and state updates. MUST be a - serial queue.

    -
    -
    - - startRequestsImmediately - - -
    -

    Determines whether this instance will automatically start all Requests. true - by default. If set to false, all Requests created must have .resume() called. - on them for them to start.

    -
    -
    - - requestQueue - - -
    -

    DispatchQueue on which to perform URLRequest creation. By default this queue - will use the rootQueue as its target. A separate queue can be used if it’s - determined request creation is a bottleneck, but that should only be done after - careful testing and profiling. nil by default.

    -
    -
    - - serializationQueue - - -
    -

    DispatchQueue on which to perform all response serialization. By default this - queue will use the rootQueue as its target. A separate queue can be used if - it’s determined response serialization is a bottleneck, but that should only be - done after careful testing and profiling. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor to be used for all Requests created by this instance. nil - by default.

    -
    -
    - - serverTrustManager - - -
    -

    ServerTrustManager to be used for all trust evaluations by this instance. nil - by default.

    -
    -
    - - redirectHandler - - -
    -

    RedirectHandler to be used by all Requests created by this instance. nil by - default.

    -
    -
    - - cachedResponseHandler - - -
    -

    CachedResponseHandler to be used by all Requests created by this instance. - nil by default.

    -
    -
    - - eventMonitors - - -
    -

    Additional EventMonitors used by the instance. Alamofire always adds a - AlamofireNotifications EventMonitor to the array passed here. [] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a Session from a URLSessionConfiguration.

    -
    -

    Note

    -

    This initializer lets Alamofire handle the creation of the underlying URLSession and its - delegateQueue, and is the recommended initializer for most uses.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
    -                        delegate: SessionDelegate = SessionDelegate(),
    -                        rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
    -                        startRequestsImmediately: Bool = true,
    -                        requestQueue: DispatchQueue? = nil,
    -                        serializationQueue: DispatchQueue? = nil,
    -                        interceptor: RequestInterceptor? = nil,
    -                        serverTrustManager: ServerTrustManager? = nil,
    -                        redirectHandler: RedirectHandler? = nil,
    -                        cachedResponseHandler: CachedResponseHandler? = nil,
    -                        eventMonitors: [EventMonitor] = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - configuration - - -
    -

    URLSessionConfiguration to be used to create the underlying URLSession. Changes - to this value after being passed to this initializer will have no effect. - URLSessionConfiguration.af.default by default.

    -
    -
    - - delegate - - -
    -

    SessionDelegate that handles session‘s delegate callbacks as well as Request - interaction. SessionDelegate() by default.

    -
    -
    - - rootQueue - - -
    -

    Root DispatchQueue for all internal callbacks and state updates. MUST be a - serial queue. DispatchQueue(label: "org.alamofire.session.rootQueue") by default.

    -
    -
    - - startRequestsImmediately - - -
    -

    Determines whether this instance will automatically start all Requests. true - by default. If set to false, all Requests created must have .resume() called. - on them for them to start.

    -
    -
    - - requestQueue - - -
    -

    DispatchQueue on which to perform URLRequest creation. By default this queue - will use the rootQueue as its target. A separate queue can be used if it’s - determined request creation is a bottleneck, but that should only be done after - careful testing and profiling. nil by default.

    -
    -
    - - serializationQueue - - -
    -

    DispatchQueue on which to perform all response serialization. By default this - queue will use the rootQueue as its target. A separate queue can be used if - it’s determined response serialization is a bottleneck, but that should only be - done after careful testing and profiling. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor to be used for all Requests created by this instance. nil - by default.

    -
    -
    - - serverTrustManager - - -
    -

    ServerTrustManager to be used for all trust evaluations by this instance. nil - by default.

    -
    -
    - - redirectHandler - - -
    -

    RedirectHandler to be used by all Requests created by this instance. nil by - default.

    -
    -
    - - cachedResponseHandler - - -
    -

    CachedResponseHandler to be used by all Requests created by this instance. - nil by default.

    -
    -
    - - eventMonitors - - -
    -

    Additional EventMonitors used by the instance. Alamofire always adds a - AlamofireNotifications EventMonitor to the array passed here. [] by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Cancel all active Requests, optionally calling a completion handler when complete.

    -
    -

    Note

    -

    This is an asynchronous operation and does not block the creation of future Requests. Cancelled - Requests may not cancel immediately due internal work, and may not cancel at all if they are close to - completion when cancelled.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    DispatchQueue on which the completion handler is run. .main by default.

    -
    -
    - - completion - - -
    -

    Closure to be called when all Requests have been cancelled.

    -
    -
    -
    -
    -
    -
  • -
-
-
- - -
-
- - -
-
-
- - - -

Data

-
-
- -
-
-
- - - -

File

-
-
- -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the multipart form data built using a closure and sent using the provided -URLRequest components and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                 to url: URLConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 method: HTTPMethod = .post,
    -                 headers: HTTPHeaders? = nil,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - convertible - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible -value, and a RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                 with request: URLRequestConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components -and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: MultipartFormData,
    -                 to url: URLConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 method: HTTPMethod = .post,
    -                 headers: HTTPHeaders? = nil,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - url - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible -value and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: MultipartFormData,
    -                 with request: URLRequestConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager instance to be used by the returned UploadRequest. .default instance by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - sessionConfiguration - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var sessionConfiguration: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - startImmediately - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var startImmediately: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup(after:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cleanup(after request: Request)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/SessionDelegate.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/SessionDelegate.html deleted file mode 100644 index 28b2285..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/SessionDelegate.html +++ /dev/null @@ -1,916 +0,0 @@ - - - - SessionDelegate Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SessionDelegate

-
-
-
open class SessionDelegate : NSObject
- -
-
-

Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(fileManager:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from the given FileManager.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(fileManager: FileManager = .default)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - fileManager - - -
    -

    FileManager to use for underlying file management, such as moving downloaded files. - .default by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     didReceive challenge: URLAuthenticationChallenge,
    -                     completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     didSendBodyData bytesSent: Int64,
    -                     totalBytesSent: Int64,
    -                     totalBytesExpectedToSend: Int64)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     willPerformHTTPRedirection response: HTTPURLResponse,
    -                     newRequest request: URLRequest,
    -                     completionHandler: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     dataTask: URLSessionDataTask,
    -                     willCacheResponse proposedResponse: CachedURLResponse,
    -                     completionHandler: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/StringResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/StringResponseSerializer.html deleted file mode 100644 index a4a4658..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/StringResponseSerializer.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - StringResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

StringResponseSerializer

-
-
-
public final class StringResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no -data is considered an error. However, if the response is has a status code valid for empty responses (204, 205), -then an empty String is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoding - -
    -
    -
    -
    -
    -
    -

    Optional string encoding used to validate the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let encoding: String.Encoding?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance with the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
    -            encoding: String.Encoding? = nil,
    -            emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - encoding - - -
    -

    A string encoding. Defaults to nil, in which case the encoding will be determined - from the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder.html deleted file mode 100644 index a7103f1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder.html +++ /dev/null @@ -1,1138 +0,0 @@ - - - - URLEncodedFormEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncodedFormEncoder

-
-
-
public final class URLEncodedFormEncoder
- -
-
-

An object that encodes instances into URL-encoded query strings.

- -

There is no published specification for how to encode collection types. By default, the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

- -

BoolEncoding can be used to configure how Bool values are encoded. The default behavior is to encode -true as 1 and false as 0.

- -

DateEncoding can be used to configure how Date values are encoded. By default, the .deferredToDate -strategy is used, which formats dates from their structure.

- -

SpaceEncoding can be used to configure how spaces are encoded. Modern encodings use percent replacement (%20), -while older encodings may expect spaces to be replaced with +.

- -

This type is largely based on Vapor’s url-encoded-form project.

- -
-
- -
-
-
-
    -
  • -
    - - - - ArrayEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Array values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - BoolEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Bool values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum BoolEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DataEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Data values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum DataEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DateEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Date values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum DateEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - KeyEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for keys.

    - -

    This type is derived from JSONEncoder‘s KeyEncodingStrategy -and XMLEncoders KeyEncodingStrategy.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum KeyEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - SpaceEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for spaces.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum SpaceEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - Error - -
    -
    -
    -
    -
    - -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Error : Swift.Error
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Whether or not to sort the encoded key value pairs.

    -
    -

    Note

    - This setting ensures a consistent ordering for all encodings of the same parameters. When set to false, - encoded Dictionary values may have a different encoded order each time they’re encoded due to - Dictionary‘s random storage order, but Encodable types will maintain their encoded order. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let alphabetizeKeyValuePairs: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - arrayEncoding - -
    -
    -
    -
    -
    -
    -

    The ArrayEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let arrayEncoding: ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boolEncoding - -
    -
    -
    -
    -
    -
    -

    The BoolEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boolEncoding: BoolEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - dataEncoding - -
    -
    -
    -
    -
    -
    -

    THe DataEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataEncoding: DataEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - dateEncoding - -
    -
    -
    -
    -
    -
    -

    The DateEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dateEncoding: DateEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - keyEncoding - -
    -
    -
    -
    -
    -
    -

    The KeyEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let keyEncoding: KeyEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - spaceEncoding - -
    -
    -
    -
    -
    -
    -

    The SpaceEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let spaceEncoding: SpaceEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - allowedCharacters - -
    -
    -
    -
    -
    -
    -

    The CharacterSet of allowed (non-escaped) characters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var allowedCharacters: CharacterSet
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance from the supplied parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(alphabetizeKeyValuePairs: Bool = true,
    -            arrayEncoding: ArrayEncoding = .brackets,
    -            boolEncoding: BoolEncoding = .numeric,
    -            dataEncoding: DataEncoding = .base64,
    -            dateEncoding: DateEncoding = .deferredToDate,
    -            keyEncoding: KeyEncoding = .useDefaultKeys,
    -            spaceEncoding: SpaceEncoding = .percentEscaped,
    -            allowedCharacters: CharacterSet = .afURLQueryAllowed)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - alphabetizeKeyValuePairs - - -
    -

    Whether or not to sort the encoded key value pairs. true by default.

    -
    -
    - - arrayEncoding - - -
    -

    The ArrayEncoding to use. .brackets by default.

    -
    -
    - - boolEncoding - - -
    -

    The BoolEncoding to use. .numeric by default.

    -
    -
    - - dataEncoding - - -
    -

    The DataEncoding to use. .base64 by default.

    -
    -
    - - dateEncoding - - -
    -

    The DateEncoding to use. .deferredToDate by default.

    -
    -
    - - keyEncoding - - -
    -

    The KeyEncoding to use. .useDefaultKeys by default.

    -
    -
    - - spaceEncoding - - -
    -

    The SpaceEncoding to use. .percentEscaped by default.

    -
    -
    - - allowedCharacters - - -
    -

    The CharacterSet of allowed (non-escaped) characters. .afURLQueryAllowed by - default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes the value as a URL form encoded String.

    -
    -

    Throws

    -

    An Error or EncodingError instance if encoding fails.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ value: Encodable) throws -> String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Encodable value.`

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded String.

    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes the value as Data. This is performed by first creating an encoded String and then returning the -.utf8 data.

    -
    -

    Throws

    -

    An Error or EncodingError instance if encoding fails.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ value: Encodable) throws -> Data
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Encodable value.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded Data.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/ArrayEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/ArrayEncoding.html deleted file mode 100644 index d663d6a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/ArrayEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ArrayEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ArrayEncoding

-
-
-
public enum ArrayEncoding
- -
-
-

Encoding to use for Array values.

- -
-
- -
-
-
-
    -
  • -
    - - - - brackets - -
    -
    -
    -
    -
    -
    -

    An empty set of square brackets ([]) are appended to the key for every value. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case brackets
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noBrackets - -
    -
    -
    -
    -
    -
    -

    No brackets are appended to the key and the key is encoded as is.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noBrackets
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/BoolEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/BoolEncoding.html deleted file mode 100644 index ec3b7e2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/BoolEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - BoolEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

BoolEncoding

-
-
-
public enum BoolEncoding
- -
-
-

Encoding to use for Bool values.

- -
-
- -
-
-
-
    -
  • -
    - - - - numeric - -
    -
    -
    -
    -
    -
    -

    Encodes true as 1, false as 0.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case numeric
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - literal - -
    -
    -
    -
    -
    -
    -

    Encodes true as true, false as false. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case literal
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DataEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DataEncoding.html deleted file mode 100644 index 0000525..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DataEncoding.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - DataEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataEncoding

-
-
-
public enum DataEncoding
- -
-
-

Encoding to use for Data values.

- -
-
- -
-
-
-
    -
  • -
    - - - - deferredToData - -
    -
    -
    -
    -
    -
    -

    Defers encoding to the Data type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case deferredToData
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - base64 - -
    -
    -
    -
    -
    -
    -

    Encodes Data as a Base64-encoded string. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case base64
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    Encode the Data as a custom value encoded by the given closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((Data) throws -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DateEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DateEncoding.html deleted file mode 100644 index 6853d4e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/DateEncoding.html +++ /dev/null @@ -1,613 +0,0 @@ - - - - DateEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DateEncoding

-
-
-
public enum DateEncoding
- -
-
-

Encoding to use for Date values.

- -
-
- -
-
-
-
    -
  • -
    - - - - deferredToDate - -
    -
    -
    -
    -
    -
    -

    Defers encoding to the Date type. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case deferredToDate
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - secondsSince1970 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates as seconds since midnight UTC on January 1, 1970.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case secondsSince1970
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - millisecondsSince1970 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates as milliseconds since midnight UTC on January 1, 1970.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case millisecondsSince1970
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - iso8601 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates according to the ISO8601 and RFC3339 standards.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case iso8601
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - formatted(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes Dates using the given DateFormatter.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case formatted(DateFormatter)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes Dates using the given closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((Date) throws -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/Error.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/Error.html deleted file mode 100644 index 5e24530..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/Error.html +++ /dev/null @@ -1,478 +0,0 @@ - - - - Error Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Error

-
-
-
public enum Error : Swift.Error
- -
-
-

URLEncodedFormEncoder error.

- -
-
- -
-
-
-
    -
  • -
    - - - - invalidRootObject(_:) - -
    -
    -
    -
    -
    -
    -

    An invalid root object was created by the encoder. Only keyed values are valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case invalidRootObject(String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/KeyEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/KeyEncoding.html deleted file mode 100644 index ce9a1d1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/KeyEncoding.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - KeyEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

KeyEncoding

-
-
-
public enum KeyEncoding
- -
-
-

Encoding to use for keys.

- -

This type is derived from JSONEncoder‘s KeyEncodingStrategy -and XMLEncoders KeyEncodingStrategy.

- -
-
- -
-
-
-
    -
  • -
    - - - - useDefaultKeys - -
    -
    -
    -
    -
    -
    -

    Use the keys specified by each type. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case useDefaultKeys
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - convertToSnakeCase - -
    -
    -
    -
    -
    -
    -

    Convert from camelCaseKeys to snake_case_keys before writing a key.

    - -

    Capital characters are determined by testing membership in -CharacterSet.uppercaseLetters and CharacterSet.lowercaseLetters -(Unicode General Categories Lu and Lt). -The conversion to lower case uses Locale.system, also known as -the ICU root locale. This means the result is consistent -regardless of the current user’s locale and language preferences.

    - -

    Converting from camel case to snake case:

    - -
      -
    1. Splits words at the boundary of lower-case to upper-case
    2. -
    3. Inserts _ between words
    4. -
    5. Lowercases the entire string
    6. -
    7. Preserves starting and ending _.
    8. -
    - -

    For example, oneTwoThree becomes one_two_three. _oneTwoThree_ becomes _one_two_three_.

    -
    -

    Note

    - Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case convertToSnakeCase
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - convertToKebabCase - -
    -
    -
    -
    -
    -
    -

    Same as convertToSnakeCase, but using - instead of _. -For example oneTwoThree becomes one-two-three.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case convertToKebabCase
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - capitalized - -
    -
    -
    -
    -
    -
    -

    Capitalize the first letter only. -For example oneTwoThree becomes OneTwoThree.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case capitalized
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - uppercased - -
    -
    -
    -
    -
    -
    -

    Uppercase all letters. -For example oneTwoThree becomes ONETWOTHREE.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case uppercased
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lowercased - -
    -
    -
    -
    -
    -
    -

    Lowercase all letters. -For example oneTwoThree becomes onetwothree.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case lowercased
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    A custom encoding using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((String) -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/SpaceEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/SpaceEncoding.html deleted file mode 100644 index 8361bbb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormEncoder/SpaceEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - SpaceEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SpaceEncoding

-
-
-
public enum SpaceEncoding
- -
-
-

Encoding to use for spaces.

- -
-
- -
-
-
-
    -
  • -
    - - - - percentEscaped - -
    -
    -
    -
    -
    -
    -

    Encodes spaces according to normal percent escaping rules (%20).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case percentEscaped
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - plusReplaced - -
    -
    -
    -
    -
    -
    -

    Encodes spaces as +,

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case plusReplaced
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder.html deleted file mode 100644 index 572435e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder.html +++ /dev/null @@ -1,651 +0,0 @@ - - - - URLEncodedFormParameterEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncodedFormParameterEncoder

-
-
-
open class URLEncodedFormParameterEncoder : ParameterEncoder
- -
-
-

A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -on the Destination set.

- -

If no Content-Type header is already set on the provided URLRequests, it will be set to -application/x-www-form-urlencoded; charset=utf-8.

- -

Encoding behavior can be customized by passing an instance of URLEncodedFormEncoder to the initializer.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder/Destination.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder/Destination.html deleted file mode 100644 index 1c26e9f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/URLEncodedFormParameterEncoder/Destination.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - Destination Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Destination

-
-
-
public enum Destination
- -
-
-

Defines where the URL-encoded string should be set for each URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - methodDependent - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to any existing query string for .get, .head, and .delete request. -Sets it to the httpBody for all other methods.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case methodDependent
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to any existing query string from the URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case queryString
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to the httpBody of the URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpBody
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest.html deleted file mode 100644 index 8a6ea06..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest.html +++ /dev/null @@ -1,609 +0,0 @@ - - - - UploadRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

UploadRequest

-
-
-
public class UploadRequest : DataRequest
- -
-
-

DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - Uploadable - -
    -
    -
    -
    -
    -
    -

    Type describing the origin of the upload, whether Data, file, or stream.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - upload - -
    -
    -
    -
    -
    -
    -

    The UploadableConvertible value used to produce the Uploadable value for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let upload: UploadableConvertible
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileManager - -
    -
    -
    -
    -
    -
    -

    FileManager used to perform cleanup tasks, including the removal of multipart form encoded payloads written -to disk.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let fileManager: FileManager
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - uploadable - -
    -
    -
    -
    -
    -
    -

    Uploadable value used by the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var uploadable: UploadRequest.Uploadable?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public override func cleanup()
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest/Uploadable.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest/Uploadable.html deleted file mode 100644 index 99fe7e7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Classes/UploadRequest/Uploadable.html +++ /dev/null @@ -1,570 +0,0 @@ - - - - Uploadable Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Uploadable

-
-
-
public enum Uploadable
- -
-
-

Type describing the origin of the upload, whether Data, file, or stream.

- -
-
- -
-
-
-
    -
  • -
    - - - - data(_:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided Data value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case data(Data)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - file(_:shouldRemove:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided file URL, as well as a Bool determining whether the source file should be -automatically removed once uploaded.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case file(URL, shouldRemove: Bool)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - stream(_:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided InputStream.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case stream(InputStream)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - createUploadable() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func createUploadable() throws -> UploadRequest.Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums.html deleted file mode 100644 index f007ef2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - Enumerations Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Enumerations

-

The following enumerations are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AFError - -
    -
    -
    -
    -
    -
    -

    AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with -their own associated reasons.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum AFError : Error
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - AF - -
    -
    -
    -
    -
    -
    -

    Global namespace containing API for the default Session instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum AF
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RetryResult - -
    -
    -
    -
    -
    -
    -

    Outcome of determination whether retry is necessary.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum RetryResult
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AF.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AF.html deleted file mode 100644 index 019be1b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AF.html +++ /dev/null @@ -1,2419 +0,0 @@ - - - - AF Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AF

-
-
-
public enum AF
- -
-
-

Global namespace containing API for the default Session instance.

- -
-
- -
-
-
- - -
-
- - -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a DownloadRequest using the Session.default from the resumeData produced from a previous -DownloadRequest cancellation to retrieve the contents of the original request and save them to the destination.

    -
    -

    Note

    -

    If destination is not specified, the download will be moved to a temporary location determined by - Alamofire.

    - -
    -
    -

    Note

    -

    On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), -resumeData is broken on background URL session configurations. There’s an underlying bug in the resumeData -generation logic where the data is written incorrectly and will always fail to resume the download. For more -information about the bug and possible workarounds, please refer to the this Stack Overflow post.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func download(resumingWith resumeData: Data,
    -                            interceptor: RequestInterceptor? = nil,
    -                            to destination: DownloadRequest.Destination? = nil) -> DownloadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - resumeData - - -
    -

    The resume Data. This is an opaque blob produced by URLSessionDownloadTask when a task is - cancelled. See Apple’s documentation - for more information.

    -
    -
    - - interceptor - - -
    -

    The RequestInterceptor, nil by default.

    -
    -
    - - destination - - -
    -

    The DownloadRequest.Destination closure used to determine the destination of the downloaded - file. nil by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created DownloadRequest.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
- -
-
-
- - - -

File

-
-
- -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the multipart form data built using a closure and sent using the provided -URLRequest components and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                          to url: URLConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          method: HTTPMethod = .post,
    -                          headers: HTTPHeaders? = nil,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - convertible - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible -value, and a RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                          with request: URLRequestConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components -and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: MultipartFormData,
    -                          to url: URLConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          method: HTTPMethod = .post,
    -                          headers: HTTPHeaders? = nil,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - url - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible -value and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: MultipartFormData,
    -                          with request: URLRequestConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager instance to be used by the returned UploadRequest. .default instance by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError.html deleted file mode 100644 index 760dcdd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError.html +++ /dev/null @@ -1,1855 +0,0 @@ - - - - AFError Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AFError

-
-
-
public enum AFError : Error
- -
-
-

AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with -their own associated reasons.

- -
-
- -
-
-
- -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .sessionDeinitialized.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionDeinitializedError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .sessionInvalidated.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionInvalidatedError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .explicitlyCancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isExplicitlyCancelledError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isInvalidURLError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is .invalidURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isInvalidURLError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .parameterEncodingFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isParameterEncodingError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .parameterEncoderFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isParameterEncoderError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .multipartEncodingFailed. When true, the url and underlyingError -properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isMultipartEncodingError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .requestAdaptationFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isRequestAdaptationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .responseValidationFailed. When true, the acceptableContentTypes, -responseContentType, responseCode, and underlyingError properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResponseValidationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .responseSerializationFailed. When true, the failedStringEncoding and -underlyingError properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResponseSerializationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .serverTrustEvaluationFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isServerTrustEvaluationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isRequestRetryError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is requestRetryFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isRequestRetryError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is createUploadableFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCreateUploadableError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCreateURLRequestError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is downloadedFileMoveFailed. When true, the destination and underlyingError properties will -contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isDownloadedFileMoveError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSessionTaskError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionTaskError: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlConvertible - -
    -
    -
    -
    -
    -
    -

    The URLConvertible associated with the error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var urlConvertible: URLConvertible? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - url - -
    -
    -
    -
    -
    -
    -

    The URL associated with the error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var url: URL? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - underlyingError - -
    -
    -
    -
    -
    -
    -

    The underlying Error responsible for generating the failure associated with .sessionInvalidated, -.parameterEncodingFailed, .parameterEncoderFailed, .multipartEncodingFailed, .requestAdaptationFailed, -.responseSerializationFailed, .requestRetryFailed errors.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var underlyingError: Error? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The acceptable Content-Types of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var acceptableContentTypes: [String]? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - responseContentType - -
    -
    -
    -
    -
    -
    -

    The response Content-Type of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var responseContentType: String? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - responseCode - -
    -
    -
    -
    -
    -
    -

    The response code of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var responseCode: Int? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - failedStringEncoding - -
    -
    -
    -
    -
    -
    -

    The String.Encoding associated with a failed .stringResponse() call.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var failedStringEncoding: String.Encoding? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sourceURL - -
    -
    -
    -
    -
    -
    -

    The source URL of a .downloadedFileMoveFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var sourceURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - destinationURL - -
    -
    -
    -
    -
    -
    -

    The destination URL of a .downloadedFileMoveFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var destinationURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - errorDescription - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var errorDescription: String? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/MultipartEncodingFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/MultipartEncodingFailureReason.html deleted file mode 100644 index 1a4fa3a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/MultipartEncodingFailureReason.html +++ /dev/null @@ -1,802 +0,0 @@ - - - - MultipartEncodingFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartEncodingFailureReason

-
-
-
public enum MultipartEncodingFailureReason
- -
-
-

The underlying reason the .multipartEncodingFailed error occurred.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The fileURL provided for reading an encodable body part isn’t a file URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartURLInvalid(url: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The filename of the fileURL provided has either an empty lastPathComponent or `pathExtension.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFilenameInvalid(in: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file at the fileURL provided was not reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileNotReachable(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Attempting to check the reachability of the fileURL provided threw an error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file at the fileURL provided is actually a directory.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileIsDirectory(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The size of the file at the fileURL provided was not returned by the system.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileSizeNotAvailable(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to find the size of the file at the fileURL provided threw an error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An InputStream could not be created for the provided fileURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartInputStreamCreationFailed(for: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An OutputStream could not be created when attempting to write the encoded data to disk.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamCreationFailed(for: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The encoded body data could not be written to disk because a file already exists at the provided fileURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamFileAlreadyExists(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The fileURL provided for writing the encoded body data to disk is not a file URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamURLInvalid(url: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to write the encoded body data to disk failed with an underlying error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamWriteFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to read an encoded body part InputStream failed with underlying system error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputStreamReadFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason.html deleted file mode 100644 index c14953f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - ParameterEncoderFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoderFailureReason

-
-
-
public enum ParameterEncoderFailureReason
- -
-
-

The underlying reason the .parameterEncoderFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - RequiredComponent - -
    -
    -
    -
    -
    -
    -

    Possible missing components.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum RequiredComponent
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A RequiredComponent was missing during encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingRequiredComponent(RequiredComponent)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoderFailed(error:) - -
    -
    -
    -
    -
    -
    -

    The underlying encoder failed with the associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case encoderFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html deleted file mode 100644 index 864fc1d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - RequiredComponent Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequiredComponent

-
-
-
public enum RequiredComponent
- -
-
-

Possible missing components.

- -
-
- -
-
-
-
    -
  • -
    - - - - url - -
    -
    -
    -
    -
    -
    -

    The URL was missing or unable to be extracted from the passed URLRequest or during encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case url
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpMethod(rawValue:) - -
    -
    -
    -
    -
    -
    -

    The HTTPMethod could not be extracted from the passed URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpMethod(rawValue: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncodingFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncodingFailureReason.html deleted file mode 100644 index 3995a8e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ParameterEncodingFailureReason.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - ParameterEncodingFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncodingFailureReason

-
-
-
public enum ParameterEncodingFailureReason
- -
-
-

The underlying reason the .parameterEncodingFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - missingURL - -
    -
    -
    -
    -
    -
    -

    The URLRequest did not have a URL to encode.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingURL
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    JSON serialization failed with an underlying system error during the encoding process.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case jsonEncodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom parameter encoding failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customEncodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseSerializationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseSerializationFailureReason.html deleted file mode 100644 index 7740740..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseSerializationFailureReason.html +++ /dev/null @@ -1,667 +0,0 @@ - - - - ResponseSerializationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseSerializationFailureReason

-
-
-
public enum ResponseSerializationFailureReason
- -
-
-

The underlying reason the response serialization error occurred.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The server response contained no data or the data was zero length.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputDataNilOrZeroLength
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - inputFileNil - -
    -
    -
    -
    -
    -
    -

    The file containing the server response did not exist.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputFileNil
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file containing the server response could not be read from the associated URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputFileReadFailed(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    String serialization failed using the provided String.Encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case stringSerializationFailed(encoding: String.Encoding)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    JSON serialization failed with an underlying system error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case jsonSerializationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A DataDecoder failed to decode the response due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case decodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A custom response serializer failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customSerializationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Generic serialization failed for an empty response that wasn’t type Empty but instead the associated type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case invalidEmptyResponse(type: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseValidationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseValidationFailureReason.html deleted file mode 100644 index d537ea6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ResponseValidationFailureReason.html +++ /dev/null @@ -1,614 +0,0 @@ - - - - ResponseValidationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseValidationFailureReason

-
-
-
public enum ResponseValidationFailureReason
- -
-
-

The underlying reason the .responseValidationFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataFileNil - -
    -
    -
    -
    -
    -
    -

    The data file containing the server response did not exist.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case dataFileNil
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The data file containing the server response at the associated URL could not be read.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case dataFileReadFailed(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response did not contain a Content-Type and the acceptableContentTypes provided did not contain a -wildcard type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingContentType(acceptableContentTypes: [String])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response Content-Type did not match any type in the provided acceptableContentTypes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response status code was not acceptable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unacceptableStatusCode(code: Int)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom response validation failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customValidationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason.html deleted file mode 100644 index 22f7b83..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason.html +++ /dev/null @@ -1,830 +0,0 @@ - - - - ServerTrustFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustFailureReason

-
-
-
public enum ServerTrustFailureReason
- -
-
-

Underlying reason a server trust evaluation error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - Output - -
    -
    -
    -
    -
    -
    -

    The output of a server trust evaluation.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Output
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    No ServerTrustEvaluator was found for the associated host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noRequiredEvaluator(host: String)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noCertificatesFound - -
    -
    -
    -
    -
    -
    -

    No certificates were found with which to perform the trust evaluation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noCertificatesFound
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noPublicKeysFound - -
    -
    -
    -
    -
    -
    -

    No public keys were found with which to perform the trust evaluation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noPublicKeysFound
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, application of the associated SecPolicy failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, setting the associated anchor certificates failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, creation of the revocation policy failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case revocationPolicyCreationFailed
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    SecTrust evaluation failed with the associated Error, if one was produced.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case trustEvaluationFailed(error: Error?)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Default evaluation failed with the associated Output.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case defaultEvaluationFailed(output: Output)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Host validation failed with the associated Output.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case hostValidationFailed(output: Output)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Revocation check failed with the associated Output and options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Certificate pinning failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Public key pinning failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom server trust evaluation failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customEvaluationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason/Output.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason/Output.html deleted file mode 100644 index da099f5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/ServerTrustFailureReason/Output.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - Output Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Output

-
-
-
public struct Output
- -
-
-

The output of a server trust evaluation.

- -
-
- -
-
-
-
    -
  • -
    - - - - host - -
    -
    -
    -
    -
    -
    -

    The host for which the evaluation was performed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let host: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trust - -
    -
    -
    -
    -
    -
    -

    The SecTrust value which was evaluated.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let trust: SecTrust
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - status - -
    -
    -
    -
    -
    -
    -

    The OSStatus of evaluation operation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let status: OSStatus
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of the evaluation operation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: SecTrustResultType
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/URLRequestValidationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/URLRequestValidationFailureReason.html deleted file mode 100644 index 1fb0129..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/AFError/URLRequestValidationFailureReason.html +++ /dev/null @@ -1,478 +0,0 @@ - - - - URLRequestValidationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequestValidationFailureReason

-
-
-
public enum URLRequestValidationFailureReason
- -
-
-

The underlying reason the .urlRequestValidationFailed

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    URLRequest with GET method had body data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyDataInGETRequest(Data)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/HTTPMethod.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/HTTPMethod.html deleted file mode 100644 index dbdfd33..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/HTTPMethod.html +++ /dev/null @@ -1,681 +0,0 @@ - - - - HTTPMethod Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPMethod

-
-
-
public enum HTTPMethod : String
- -
-
-

HTTP method definitions.

- -

See https://tools.ietf.org/html/rfc7231#section-4.3

- -
-
- -
-
-
-
    -
  • -
    - - - - connect - -
    -
    -
    -
    -
    -
    -

    CONNECT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case connect = "CONNECT"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delete - -
    -
    -
    -
    -
    -
    -

    DELETE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case delete = "DELETE"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - get - -
    -
    -
    -
    -
    -
    -

    GET method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case get = "GET"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - head - -
    -
    -
    -
    -
    -
    -

    HEAD method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case head = "HEAD"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    OPTIONS method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case options = "OPTIONS"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - patch - -
    -
    -
    -
    -
    -
    -

    PATCH method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case patch = "PATCH"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - post - -
    -
    -
    -
    -
    -
    -

    POST method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case post = "POST"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - put - -
    -
    -
    -
    -
    -
    -

    PUT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case put = "PUT"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trace - -
    -
    -
    -
    -
    -
    -

    TRACE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case trace = "TRACE"
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/Result.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/Result.html deleted file mode 100644 index 3c425f6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/Result.html +++ /dev/null @@ -1,1242 +0,0 @@ - - - - Result Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Result

-
-
-
public enum Result<Value>
- -
-
-

Used to represent whether a request was successful or encountered an error.

- -
    -
  • success: The request and all post processing operations were successful resulting in the serialization of the - provided associated value.

  • -
  • failure: The request encountered an error resulting in a failure. The associated values are the original data - provided by the server as well as the error that caused the failure.

  • -
- -
-
- -
-
-
-
    -
  • -
    - - - - success(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case success(Value)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - failure(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case failure(Error)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns true if the result is a success, false otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isFailure - -
    -
    -
    -
    -
    -
    -

    Returns true if the result is a failure, false otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isFailure: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value if the result is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Value? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Error? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes whether the result was a -success or failure in addition to the value or error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(value:) - -
    -
    -
    -
    -
    -
    -

    Creates a Result instance from the result of a closure.

    - -

    A failure result is created when the closure throws, and a success result is created when the closure -succeeds without throwing an error.

    -
    func someString() throws -> String { ... }
    -
    -let result = Result(value: {
    -    return try someString()
    -})
    -
    -// The type of result is Result<String>
    -
    - -

    The trailing closure syntax is also supported:

    -
    let result = Result { try someString() }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(value: () throws -> Value)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The closure to execute and create the result for.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - unwrap() - -
    -
    -
    -
    -
    -
    -

    Returns the success value, or throws the failure error.

    -
    let possibleString: Result<String> = .success("success")
    -try print(possibleString.unwrap())
    -// Prints "success"
    -
    -let noString: Result<String> = .failure(error)
    -try print(noString.unwrap())
    -// Throws error
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func unwrap() throws -> Value
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: Result<Data> = .success(Data())
    -let possibleInt = possibleData.map { $0.count }
    -try print(possibleInt.unwrap())
    -// Prints "0"
    -
    -let noData: Result<Data> = .failure(error)
    -let noInt = noData.map { $0.count }
    -try print(noInt.unwrap())
    -// Throws error
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<T>(_ transform: (Value) -> T) -> Result<T>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the Result instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result containing the result of the given closure. If this instance is a failure, returns the - same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - flatMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the flatMap method with a closure that may throw an error. For example:

    -
    let possibleData: Result<Data> = .success(Data(...))
    -let possibleObject = possibleData.flatMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result containing the result of the given closure. If this instance is a failure, returns the - same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: Result<Data> = .failure(someError)
    -let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<T>(_ transform: (Error) -> T) -> Result where T : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result instance containing the result of the transform. If this instance is a success, returns - the same instance.

    -
    -
    -
    -
  • -
  • -
    - - - - flatMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the flatMapError function with a closure that may throw an error. For example:

    -
    let possibleData: Result<Data> = .success(Data(...))
    -let possibleObject = possibleData.flatMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func flatMapError<T>(_ transform: (Error) throws -> T) -> Result where T : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result instance containing the result of the transform. If this instance is a success, returns - the same instance.

    -
    -
    -
    -
  • -
  • -
    - - - - withValue(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the withValue function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A closure that takes the success value of this instance.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - withError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the withError function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func withError(_ closure: (Error) throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A closure that takes the success value of this instance.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - ifSuccess(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success.

    - -

    Use the ifSuccess function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A Void closure.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - ifFailure(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure.

    - -

    Use the ifFailure function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func ifFailure(_ closure: () throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A Void closure.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/RetryResult.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/RetryResult.html deleted file mode 100644 index 76ef180..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Enums/RetryResult.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - RetryResult Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RetryResult

-
-
-
public enum RetryResult
- -
-
-

Outcome of determination whether retry is necessary.

- -
-
- -
-
-
-
    -
  • -
    - - - - retry - -
    -
    -
    -
    -
    -
    -

    Retry should be attempted immediately.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case retry
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryWithDelay(_:) - -
    -
    -
    -
    -
    -
    -

    Retry should be attempted after the associated TimeInterval.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case retryWithDelay(TimeInterval)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotRetry - -
    -
    -
    -
    -
    -
    -

    Do not retry.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotRetry
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Do not retry due to the associated AFError.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotRetryWithError(Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions.html deleted file mode 100644 index 9bae0aa..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions.html +++ /dev/null @@ -1,751 +0,0 @@ - - - - Extensions Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Extensions

-

The following extensions are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - Error - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension Error
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - URLRequest - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension URLRequest
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - HTTPURLResponse - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension HTTPURLResponse
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public extension URLSessionConfiguration
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Notification - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension Notification
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- -
-
-
    -
  • -
    - - - - CharacterSet - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public extension CharacterSet
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Array.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Array.html deleted file mode 100644 index 10f8663..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Array.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - Array Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Array

-
-
-
@frozen
-public extension Array where Element == ServerTrustEvaluating
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given SecTrust value for the given host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - trust - - -
    -

    The SecTrust value to evaluate.

    -
    -
    - - host - - -
    -

    The host for which to evaluate the SecTrust value.

    -
    -
    -
    -
    -

    Return Value

    -

    Whether or not the evaluator considers the SecTrust value valid for host.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Bundle.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Bundle.html deleted file mode 100644 index 210c154..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Bundle.html +++ /dev/null @@ -1,494 +0,0 @@ - - - - Bundle Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Bundle

-
-
-
class Bundle : NSObject
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Returns all valid cer, crt, and der certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    Returns all public keys for the valid certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/CharacterSet.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/CharacterSet.html deleted file mode 100644 index 2144003..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/CharacterSet.html +++ /dev/null @@ -1,488 +0,0 @@ - - - - CharacterSet Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CharacterSet

-
-
-
public extension CharacterSet
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - afURLQueryAllowed - -
    -
    -
    -
    -
    -
    -

    Creates a CharacterSet from RFC 3986 allowed characters.

    - -

    RFC 3986 states that the following characters are reserved characters.

    - -
      -
    • General Delimiters: :, #, [, ], @, ?, /
    • -
    • Sub-Delimiters: !, $, &, , (, ), *, +, ,, ;, =
    • -
    - -

    In RFC 3986 - Section 3.4, it states that the ? and / characters should not be escaped to allow -query strings to include a URL. Therefore, all reserved characters with the exception of ? and / -should be percent-escaped in the query string.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let afURLQueryAllowed: CharacterSet
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Error.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Error.html deleted file mode 100644 index f006796..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Error.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - Error Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Error

-
-
-
extension Error
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asAFError - -
    -
    -
    -
    -
    -
    -

    Returns the instance cast as an AFError.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var asAFError: AFError? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns the instance cast as an AFError. If casting fails, a fatalError with the specified message is thrown.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/HTTPURLResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/HTTPURLResponse.html deleted file mode 100644 index 9fffd9e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/HTTPURLResponse.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - HTTPURLResponse Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPURLResponse

-
-
-
extension HTTPURLResponse
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns allHeaderFields as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var headers: HTTPHeaders { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Notification.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Notification.html deleted file mode 100644 index 2fa2506..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/Notification.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - Notification Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Notification

-
-
-
extension Notification
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The Request contained by the instance’s userInfo, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var request: Request? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/SecTrust.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/SecTrust.html deleted file mode 100644 index 0ecff22..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/SecTrust.html +++ /dev/null @@ -1,683 +0,0 @@ - - - - SecTrust Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SecTrust

-
-
-
class SecTrust : _CFObject
- -
-
- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - apply(policy:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func apply(policy: SecPolicy) throws -> SecTrust
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func setAnchorCertificates(_ certificates: [SecCertificate]) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    The public keys contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificateData - -
    -
    -
    -
    -
    -
    -

    The Data values for all certificates contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificateData: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performDefaultEvaluation(forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validateHost(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validateHost(_ host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/String.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/String.html deleted file mode 100644 index 8579500..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/String.html +++ /dev/null @@ -1,487 +0,0 @@ - - - - String Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

String

-
-
-
@frozen
-extension String: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL if self can be used to initialize a URL instance, otherwise throws.

    -
    -

    Throws

    - An AFError.invalidURL instance. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL initialized with self.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URL.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URL.html deleted file mode 100644 index 7fb02ee..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URL.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - URL Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URL

-
-
-
extension URL: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLComponents.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLComponents.html deleted file mode 100644 index 852bc77..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLComponents.html +++ /dev/null @@ -1,486 +0,0 @@ - - - - URLComponents Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLComponents

-
-
-
extension URLComponents: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL if the self‘s url is not nil, otherwise throws.

    -
    -

    Throws

    - An AFError.invalidURL instance. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL from the url property.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLRequest.html deleted file mode 100644 index b8cec70..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLRequest.html +++ /dev/null @@ -1,645 +0,0 @@ - - - - URLRequest Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequest

-
-
-
extension URLRequest
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns allHTTPHeaderFields as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var headers: HTTPHeaders { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    -

    Returns self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - method - -
    -
    -
    -
    -
    -
    -

    Returns the httpMethod as Alamofire’s HTTPMethod type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var method: HTTPMethod? { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate() throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLSessionConfiguration.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLSessionConfiguration.html deleted file mode 100644 index 64abc67..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Extensions/URLSessionConfiguration.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - URLSessionConfiguration Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLSessionConfiguration

-
-
-
public extension URLSessionConfiguration
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns httpAdditionalHeaders as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var headers: HTTPHeaders { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Functions.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Functions.html deleted file mode 100644 index 9debbb7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Functions.html +++ /dev/null @@ -1,494 +0,0 @@ - - - - Functions Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (77% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Functions

-

The following functions are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - ==(_:_:) - -
    -
    -
    -
    -
    -
    -

    Returns whether the two network reachability status values are equal.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func ==(
    -    lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
    -    rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
    -    -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - lhs - - -
    -

    The left-hand side value to compare.

    -
    -
    - - rhs - - -
    -

    The right-hand side value to compare.

    -
    -
    -
    -
    -

    Return Value

    -

    true if the two values are equal, false otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols.html deleted file mode 100644 index 64e6f3b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols.html +++ /dev/null @@ -1,1134 +0,0 @@ - - - - Protocols Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Protocols

-

The following protocols are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AlamofireExtended - -
    -
    -
    -
    -
    -
    -

    Protocol describing the af extension points for Alamofire extended types.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol AlamofireExtended
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - CachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    A type that handles whether the data task should store the HTTP response in the cache.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol CachedResponseHandler
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - EventMonitor - -
    -
    -
    -
    -
    -
    -

    Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -URLSession delegate protocols as well as various events from the lifetime of Request and its subclasses.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol EventMonitor
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ParameterEncoder - -
    -
    -
    -
    -
    -
    -

    A type that can encode any Encodable type into a URLRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ParameterEncoder
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ParameterEncoding - -
    -
    -
    -
    -
    -
    -

    A type used to define how a set of parameters are applied to a URLRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RedirectHandler - -
    -
    -
    -
    -
    -
    -

    A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RedirectHandler
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - RequestDelegate - -
    -
    -
    -
    -
    -
    -

    Protocol abstraction for Request‘s communication back to the SessionDelegate.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestDelegate : AnyObject
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
    -
  • -
    - - - - RequestAdapter - -
    -
    -
    -
    -
    -
    -

    A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestAdapter
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RequestRetrier - -
    -
    -
    -
    -
    -
    -

    A type that determines whether a request should be retried after being executed by the specified session manager -and encountering an error.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestRetrier
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    The type to which all data response serializers must conform in order to serialize a response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The type to which all download response serializers must conform in order to serialize a response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DownloadResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ResponseSerializer - -
    -
    -
    -
    -
    -
    -

    A serializer that can handle both data and download responses.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ResponseSerializer : DataResponseSerializerProtocol, DownloadResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DataPreprocessor - -
    -
    -
    -
    -
    -
    -

    Type used to preprocess Data before it handled by a serializer.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataPreprocessor
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - EmptyResponse - -
    -
    -
    -
    -
    -
    -

    Protocol representing an empty response. Use T.emptyValue() to get an instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol EmptyResponse
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DataDecoder - -
    -
    -
    -
    -
    -
    -

    Any type which can decode Data into a Decodable type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataDecoder
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ServerTrustEvaluating - -
    -
    -
    -
    -
    -
    -

    A protocol describing the API used to evaluate server trusts.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLConvertible - -
    -
    -
    -
    -
    -
    -

    Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct -URLRequests.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol URLConvertible
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLRequestConvertible - -
    -
    -
    -
    -
    -
    -

    Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol URLRequestConvertible
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/AlamofireExtended.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/AlamofireExtended.html deleted file mode 100644 index eaa2cca..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/AlamofireExtended.html +++ /dev/null @@ -1,541 +0,0 @@ - - - - AlamofireExtended Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireExtended

-
-
-
public protocol AlamofireExtended
- -
-
-

Protocol describing the af extension points for Alamofire extended types.

- -
-
- -
-
-
-
    -
  • -
    - - - - ExtendedType - -
    -
    -
    -
    -
    -
    -

    Type being extended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype ExtendedType
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - af - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Static Alamofire extension point.

    - -
    -

    Default Implementation

    -
    -

    Static Alamofire extension point.

    -

    Instance Alamofire extension point.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static var af: AlamofireExtension<ExtendedType>.Type { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - af - -
    -
    -
    -
    -
    -
    -

    Instance Alamofire extension point.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var af: AlamofireExtension<ExtendedType> { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/CachedResponseHandler.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/CachedResponseHandler.html deleted file mode 100644 index 5c797ea..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/CachedResponseHandler.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - CachedResponseHandler Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CachedResponseHandler

-
-
-
public protocol CachedResponseHandler
- -
-
-

A type that handles whether the data task should store the HTTP response in the cache.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether the HTTP response should be stored in the cache.

    - -

    The completion closure should be passed one of three possible options:

    - -
      -
    1. The cached response provided by the server (this is the most common use case).
    2. -
    3. A modified version of the cached response (you may want to modify it in some way before caching).
    4. -
    5. A nil value to prevent the cached response from being stored in the cache.
    6. -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func dataTask(_ task: URLSessionDataTask, willCacheResponse response: CachedURLResponse, completion: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - task - - -
    -

    The data task whose request resulted in the cached response.

    -
    -
    - - response - - -
    -

    The cached response to potentially store in the cache.

    -
    -
    - - completion - - -
    -

    The closure to execute containing cached response, a modified response, or nil.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataDecoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataDecoder.html deleted file mode 100644 index b419233..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataDecoder.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - DataDecoder Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataDecoder

-
-
-
public protocol DataDecoder
- -
-
-

Any type which can decode Data into a Decodable type.

- -
-
- -
-
-
-
    -
  • -
    - - - - decode(_:from:) - -
    -
    -
    -
    -
    -
    -

    Decode Data into the provided type.

    -
    -

    Throws

    -

    Any error that occurs during decode.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func decode<D>(_ type: D.Type, from data: Data) throws -> D where D : Decodable
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - type - - -
    -

    The Type to be decoded.

    -
    -
    - - data - - -
    -

    The Data to be decoded.

    -
    -
    -
    -
    -

    Return Value

    -

    The decoded value of type D.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataPreprocessor.html deleted file mode 100644 index eaad83d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataPreprocessor.html +++ /dev/null @@ -1,497 +0,0 @@ - - - - DataPreprocessor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataPreprocessor

-
-
-
public protocol DataPreprocessor
- -
-
-

Type used to preprocess Data before it handled by a serializer.

- -
-
- -
-
-
-
    -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    -

    Process Data before it’s handled by a serializer.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - data - - -
    -

    The raw Data to process.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataResponseSerializerProtocol.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataResponseSerializerProtocol.html deleted file mode 100644 index e985d88..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DataResponseSerializerProtocol.html +++ /dev/null @@ -1,569 +0,0 @@ - - - - DataResponseSerializerProtocol Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponseSerializerProtocol

-
-
-
public protocol DataResponseSerializerProtocol
- -
-
-

The type to which all data response serializers must conform in order to serialize a response.

- -
-
- -
-
-
-
    -
  • -
    - - - - SerializedObject - -
    -
    -
    -
    -
    -
    -

    The type of serialized object to be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype SerializedObject
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Serialize the response Data into the provided type..

    -
    -

    Throws

    -

    Any Error produced during serialization.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest which was used to perform the request, if any.

    -
    -
    - - response - - -
    -

    HTTPURLResponse received from the server, if any.

    -
    -
    - - data - - -
    -

    Data returned from the server, if any.

    -
    -
    - - error - - -
    -

    Error produced by Alamofire or the underlying URLSession during the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The SerializedObject.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DownloadResponseSerializerProtocol.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DownloadResponseSerializerProtocol.html deleted file mode 100644 index 3ad7dd3..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/DownloadResponseSerializerProtocol.html +++ /dev/null @@ -1,576 +0,0 @@ - - - - DownloadResponseSerializerProtocol Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadResponseSerializerProtocol

-
-
-
public protocol DownloadResponseSerializerProtocol
- -
-
-

The type to which all download response serializers must conform in order to serialize a response.

- -
-
- -
-
-
-
    -
  • -
    - - - - SerializedObject - -
    -
    -
    -
    -
    -
    -

    The type of serialized object to be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype SerializedObject
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializeDownload(request:response:fileURL:error:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Serialize the downloaded response Data from disk into the provided type..

    -
    -

    Throws

    -

    Any Error produced during serialization.

    - -
    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest which was used to perform the request, if any.

    -
    -
    - - response - - -
    -

    HTTPURLResponse received from the server, if any.

    -
    -
    - - fileURL - - -
    -

    File URL to which the response data was downloaded.

    -
    -
    - - error - - -
    -

    Error produced by Alamofire or the underlying URLSession during the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The SerializedObject.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EmptyResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EmptyResponse.html deleted file mode 100644 index b7876f0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EmptyResponse.html +++ /dev/null @@ -1,482 +0,0 @@ - - - - EmptyResponse Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

EmptyResponse

-
-
-
public protocol EmptyResponse
- -
-
-

Protocol representing an empty response. Use T.emptyValue() to get an instance.

- -
-
- -
-
-
-
    -
  • -
    - - - - emptyValue() - -
    -
    -
    -
    -
    -
    -

    Empty value for the conforming type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func emptyValue() -> Self
    - -
    -
    -
    -

    Return Value

    -

    Value of Self to use for empty values.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EventMonitor.html deleted file mode 100644 index e871a0b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/EventMonitor.html +++ /dev/null @@ -1,1957 +0,0 @@ - - - - EventMonitor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

EventMonitor

-
-
-
public protocol EventMonitor
- -
-
-

Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -URLSession delegate protocols as well as various events from the lifetime of Request and its subclasses.

- -
-
- -
-
-
-
    -
  • -
    - - - - queue - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    The DispatchQueue onto which Alamofire’s root CompositeEventMonitor will dispatch events. .main by default.

    - -
    -

    Default Implementation

    -
    -

    The default queue on which CompositeEventMonitors will call the EventMonitor methods. .main by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var queue: DispatchQueue { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:didBecomeInvalidWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDelegate‘s urlSession(_:didBecomeInvalidWithError:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:task:didReceive:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didReceive:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:taskNeedsNewBodyStream:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:needNewBodyStream:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:willPerformHTTPRedirection:newRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:didFinishCollecting:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didFinishCollecting:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:didCompleteWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didCompleteWithError:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:taskIsWaitingForConnectivity:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:taskIsWaitingForConnectivity:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
    -func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:dataTask:didReceive:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:didReceive:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:dataTask:willCacheResponse:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:willCacheResponse:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:downloadTask:didFinishDownloadingTo:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didFinishDownloadingTo:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - request(_:didCreateInitialURLRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a URLRequest is first created for a Request. If a RequestAdapter is active, the -URLRequest will be adapted before being issued.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToCreateURLRequestWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when the attempt to create a URLRequest from a Request‘s original URLRequestConvertible value fails.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didAdaptInitialRequest:to:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a RequestAdapter adapts the Request‘s initial URLRequest.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToAdaptURLRequest:withError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a RequestAdapter fails to adapt the Request‘s initial URLRequest.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCreateURLRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a final URLRequest is created for a Request.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCreateTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a URLSessionTask subclass instance is created for a Request.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didGatherMetrics:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a URLSessionTaskMetrics value.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailTask:earlyWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request fails due to an error created by Alamofire. e.g. When certificate pinning fails.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCompleteTask:with:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s task completes, possibly with an error. A Request may receive this event -multiple times if it is retried.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestIsRetrying(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request is about to be retried.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestIsRetrying(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidFinish(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request finishes and response serializers are being called.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidFinish(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidResume(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a resume call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidResume(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didResumeTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is resumed.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didResumeTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidSuspend(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a suspend call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidSuspend(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didSuspendTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is suspended.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didSuspendTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidCancel(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a cancel call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidCancel(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCancelTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is cancelled.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCancelTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- -
    -
  • -
    - - - - request(_:didCreateUploadable:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest creates its Uploadable value, indicating the type of upload it represents.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToCreateUploadableWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest failed to create its Uploadable value due to an error.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didProvideInputStream:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest provides the InputStream from its Uploadable value. This only occurs if -the InputStream does not wrap a Data value or file URL.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoder.html deleted file mode 100644 index bc140d7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoder.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - ParameterEncoder Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoder

-
-
-
public protocol ParameterEncoder
- -
-
-

A type that can encode any Encodable type into a URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - encode(_:into:) - -
    -
    -
    -
    -
    -
    -

    Encode the provided Encodable parameters into request.

    -
    -

    Throws

    -

    An Error when encoding fails. For Alamofire provided encoders, this will be an instance of - AFError.parameterEncoderFailed with an associated ParameterEncoderFailureReason.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func encode<Parameters>(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest where Parameters : Encodable
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - parameters - - -
    -

    The Encodable parameter value.

    -
    -
    - - request - - -
    -

    The URLRequest into which to encode the parameters.

    -
    -
    -
    -
    -

    Return Value

    -

    A URLRequest with the result of the encoding.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoding.html deleted file mode 100644 index 4a4e7ff..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ParameterEncoding.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - ParameterEncoding Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoding

-
-
-
public protocol ParameterEncoding
- -
-
-

A type used to define how a set of parameters are applied to a URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    -

    Creates a URLRequest by encoding parameters and applying them on the passed request.

    -
    -

    Throws

    -

    Any Error produced during parameter encoding.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - urlRequest - - -
    -

    URLRequestConvertible value onto which parameters will be encoded.

    -
    -
    - - parameters - - -
    -

    Parameters to encode onto the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded URLRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RedirectHandler.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RedirectHandler.html deleted file mode 100644 index b0b1594..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RedirectHandler.html +++ /dev/null @@ -1,541 +0,0 @@ - - - - RedirectHandler Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RedirectHandler

-
-
-
public protocol RedirectHandler
- -
-
-

A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines how the HTTP redirect response should be redirected to the new request.

    - -

    The completion closure should be passed one of three possible options:

    - -
      -
    1. The new request specified by the redirect (this is the most common use case).
    2. -
    3. A modified version of the new request (you may want to route it somewhere else).
    4. -
    5. A nil value to deny the redirect request and return the body of the redirect response.
    6. -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func task(_ task: URLSessionTask, willBeRedirectedTo request: URLRequest, for response: HTTPURLResponse, completion: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - task - - -
    -

    The task whose request resulted in a redirect.

    -
    -
    - - request - - -
    -

    The URL request object to the new location specified by the redirect response.

    -
    -
    - - response - - -
    -

    The response containing the server’s response to the original request.

    -
    -
    - - completion - - -
    -

    The closure to execute containing the new request, a modified request, or nil.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestAdapter.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestAdapter.html deleted file mode 100644 index 78891bb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestAdapter.html +++ /dev/null @@ -1,521 +0,0 @@ - - - - RequestAdapter Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestAdapter

-
-
-
public protocol RequestAdapter
- -
-
-

A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Inspects and adapts the specified URLRequest in some manner and calls the completion handler with the Result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - urlRequest - - -
    -

    The URLRequest to adapt.

    -
    -
    - - session - - -
    -

    The Session that will execute the URLRequest.

    -
    -
    - - completion - - -
    -

    The completion handler that must be called when adaptation is complete.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestDelegate.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestDelegate.html deleted file mode 100644 index f98fa8d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestDelegate.html +++ /dev/null @@ -1,679 +0,0 @@ - - - - RequestDelegate Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestDelegate

-
-
-
public protocol RequestDelegate : AnyObject
- -
-
-

Protocol abstraction for Request‘s communication back to the SessionDelegate.

- -
-
- -
-
-
-
    -
  • -
    - - - - sessionConfiguration - -
    -
    -
    -
    -
    -
    -

    URLSessionConfiguration used to create the underlying URLSessionTasks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var sessionConfiguration: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - startImmediately - -
    -
    -
    -
    -
    -
    -

    Determines whether the Request should automatically call resume() when adding the first response handler.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var startImmediately: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup(after:) - -
    -
    -
    -
    -
    -
    -

    Notifies the delegate the Request has reached a point where it needs cleanup.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func cleanup(after request: Request)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - request - - -
    -

    The Request to cleanup after.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Asynchronously ask the delegate whether a Request will be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - request - - -
    -

    Request which failed.

    -
    -
    - - error - - -
    -

    Error which produced the failure.

    -
    -
    - - completion - - -
    -

    Closure taking the RetryResult for evaluation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Asynchronously retry the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - request - - -
    -

    Request which will be retried.

    -
    -
    - - timeDelay - - -
    -

    TimeInterval after which the retry will be triggered.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestInterceptor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestInterceptor.html deleted file mode 100644 index 1cf9116..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestInterceptor.html +++ /dev/null @@ -1,512 +0,0 @@ - - - - RequestInterceptor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestInterceptor

-
-
-
public protocol RequestInterceptor : RequestAdapter, RequestRetrier
- -
-
-

Type that provides both RequestAdapter and RequestRetrier functionality.

- -
-
- -
-
-
-
    -
  • -
    - - - - adapt(_:for:completion:) - - - Extension method - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retry(_:for:dueTo:completion:) - - - Extension method - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retry(_ request: Request,
    -                  for session: Session,
    -                  dueTo error: Error,
    -                  completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestRetrier.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestRetrier.html deleted file mode 100644 index 70a7a5d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/RequestRetrier.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - RequestRetrier Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestRetrier

-
-
-
public protocol RequestRetrier
- -
-
-

A type that determines whether a request should be retried after being executed by the specified session manager -and encountering an error.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether the Request should be retried by calling the completion closure.

    - -

    This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs -to be retried. The one requirement is that the completion closure is called to ensure the request is properly -cleaned up after.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    Request that failed due to the provided Error.

    -
    -
    - - session - - -
    -

    Session that produced the Request.

    -
    -
    - - error - - -
    -

    Error encountered while executing the Request.

    -
    -
    - - completion - - -
    -

    Completion closure to be executed when a retry decision has been determined.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ResponseSerializer.html deleted file mode 100644 index ab8e5c1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ResponseSerializer.html +++ /dev/null @@ -1,825 +0,0 @@ - - - - ResponseSerializer Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseSerializer

-
-
-
public protocol ResponseSerializer : DataResponseSerializerProtocol, DownloadResponseSerializerProtocol
- -
-
-

A serializer that can handle both data and download responses.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    DataPreprocessor used to prepare incoming Data for serialization.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var dataPreprocessor: DataPreprocessor { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    HTTPMethods for which empty response bodies are considered appropriate.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var emptyRequestMethods: Set<HTTPMethod> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    HTTP response codes for which empty response bodies are considered appropriate.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var emptyResponseCodes: Set<Int> { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - defaultDataPreprocessor - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Default DataPreprocessor. PassthroughPreprocessor by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultDataPreprocessor: DataPreprocessor { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEmptyRequestMethods - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Default HTTPMethods for which empty response bodies are considered appropriate. [.head] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultEmptyRequestMethods: Set<HTTPMethod> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEmptyResponseCodes - - - Extension method - -
    -
    -
    -
    -
    -
    -

    HTTP response codes for which empty response bodies are considered appropriate. [204, 205] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultEmptyResponseCodes: Set<Int> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestAllowsEmptyResponseData(_:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether the request allows empty response bodies, if request exists.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - request - - -
    -

    URLRequest to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    Bool representing the outcome of the evaluation, or nil if request was nil.

    -
    -
    -
    -
  • -
  • -
    - - - - responseAllowsEmptyResponseData(_:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether the response allows empty response bodies, if response exists`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - response - - -
    -

    HTTPURLResponse to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    Bool representing the outcome of the evaluation, or nil if response was nil.

    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseAllowed(forRequest:response:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether request and response allow empty response bodies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest to evaluate.

    -
    -
    - - response - - -
    -

    HTTPURLResponse to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    true if request or response allow empty bodies, false otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ServerTrustEvaluating.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ServerTrustEvaluating.html deleted file mode 100644 index e432683..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/ServerTrustEvaluating.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - ServerTrustEvaluating Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustEvaluating

-
-
-
public protocol ServerTrustEvaluating
- -
-
-

A protocol describing the API used to evaluate server trusts.

- -
-
- -
-
-
-
    -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given SecTrust value for the given host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - trust - - -
    -

    The SecTrust value to evaluate.

    -
    -
    - - host - - -
    -

    The host for which to evaluate the SecTrust value.

    -
    -
    -
    -
    -

    Return Value

    -

    A Bool indicating whether the evaluator considers the SecTrust value valid for host.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/SessionStateProvider.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/SessionStateProvider.html deleted file mode 100644 index 695f181..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/SessionStateProvider.html +++ /dev/null @@ -1,630 +0,0 @@ - - - - SessionStateProvider Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SessionStateProvider

-
-
-
public protocol SessionStateProvider : AnyObject
- -
-
-

Undocumented

- -
-
- -
-
-
-
    -
  • -
    - - - - serverTrustManager - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var serverTrustManager: ServerTrustManager? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - redirectHandler - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var redirectHandler: RedirectHandler? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var cachedResponseHandler: CachedResponseHandler? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(for:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(for task: URLSessionTask) -> Request?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didCompleteTask(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func didCompleteTask(_ task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - credential(for:in:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func cancelRequestsForSessionInvalidation(with error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLConvertible.html deleted file mode 100644 index 74f2fc1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLConvertible.html +++ /dev/null @@ -1,488 +0,0 @@ - - - - URLConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLConvertible

-
-
-
public protocol URLConvertible
- -
-
-

Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct -URLRequests.

- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL from the conforming instance or throws.

    -
    -

    Throws

    - Any error thrown while creating the URL. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL created from the instance.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLRequestConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLRequestConvertible.html deleted file mode 100644 index ef46800..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/URLRequestConvertible.html +++ /dev/null @@ -1,521 +0,0 @@ - - - - URLRequestConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequestConvertible

-
-
-
public protocol URLRequestConvertible
- -
-
-

Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

- -
-
- -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    -

    Returns a URLRequest or throws if an Error was encountered.

    -
    -

    Throws

    - Any error thrown while constructing the URLRequest. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -

    Return Value

    -

    A URLRequest.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - urlRequest - - - Extension method - -
    -
    -
    -
    -
    -
    -

    The URLRequest returned by discarding any Error encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var urlRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/UploadableConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/UploadableConvertible.html deleted file mode 100644 index 000b5ad..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Protocols/UploadableConvertible.html +++ /dev/null @@ -1,487 +0,0 @@ - - - - UploadableConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- - -
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs.html deleted file mode 100644 index aaeea16..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs.html +++ /dev/null @@ -1,892 +0,0 @@ - - - - Structures Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Structures

-

The following structures are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AlamofireExtension - -
    -
    -
    -
    -
    -
    -

    Type that acts as a generic extension point for all AlamofireExtended types.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct AlamofireExtension<ExtendedType>
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ResponseCacher - -
    -
    -
    -
    -
    -
    -

    ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached -response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct ResponseCacher
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - HTTPHeaders - -
    -
    -
    -
    -
    -
    -

    An order-preserving and case-insensitive representation of HTTP headers.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPHeaders
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - HTTPHeader - -
    -
    -
    -
    -
    -
    -

    A representation of a single HTTP header’s name / value pair.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPHeader : Hashable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - HTTPMethod - -
    -
    -
    -
    -
    -
    -

    Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so -HTTPMethod.get != HTTPMethod(rawValue: "get").

    - -

    See https://tools.ietf.org/html/rfc7231#section-4.3

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPMethod : RawRepresentable, Equatable, Hashable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLEncoding - -
    -
    -
    -
    -
    -
    -

    Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -the HTTP body depends on the destination of the encoding.

    - -

    The Content-Type HTTP header field of an encoded request with HTTP body is set to -application/x-www-form-urlencoded; charset=utf-8.

    - -

    There is no published specification for how to encode collection types. By default the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

    - -

    BoolEncoding can be used to configure how boolean values are encoded. The default behavior is to encode -true as 1 and false as 0.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct URLEncoding : ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - JSONEncoding - -
    -
    -
    -
    -
    -
    -

    Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the -request. The Content-Type HTTP header field of an encoded request is set to application/json.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct JSONEncoding : ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Redirector - -
    -
    -
    -
    -
    -
    -

    Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Redirector
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - DataResponse - -
    -
    -
    -
    -
    -
    -

    Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct DataResponse<Success, Failure> where Failure : Error
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - DownloadResponse - -
    -
    -
    -
    -
    -
    -

    Used to store all data associated with a serialized response of a download request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct DownloadResponse<Success, Failure> where Failure : Error
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - Empty - -
    -
    -
    -
    -
    -
    -

    Type representing an empty response. Use Empty.value to get the static instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Empty : Decodable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/AlamofireExtension.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/AlamofireExtension.html deleted file mode 100644 index 6e636af..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/AlamofireExtension.html +++ /dev/null @@ -1,1427 +0,0 @@ - - - - AlamofireExtension Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireExtension

-
-
-
public struct AlamofireExtension<ExtendedType>
- -
-
-

Type that acts as a generic extension point for all AlamofireExtended types.

- -
-
- -
-
-
- -
    -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Returns all valid cer, crt, and der certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    Returns all public keys for the valid certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns all pathnames for the resources identified by the provided file extensions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func paths(forResourcesOfTypes types: [String]) -> [String]
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - types - - -
    -

    The filename extensions locate.

    -
    -
    -
    -
    -

    Return Value

    -

    All pathnames for the given filename extensions.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Evaluates self after applying the SecPolicy value provided.

    -
    -

    Throws

    -

    Any Error from applying the SecPolicy or from evaluation.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS 12, OSX 10.14, tvOS 12, watchOS 5, *)
    -func evaluate(afterApplying policy: SecPolicy) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - policy - - -
    -

    The SecPolicy to apply to self before evaluation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Attempts to validate self using the SecPolicy provided and transforming any error produced using the closure passed.

    -
    -

    Throws

    - Any Error from applying the policy, or the result of errorProducer if validation fails. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:﹚")
    -@available(OSX, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:﹚")
    -@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:﹚")
    -@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:﹚")
    -func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - policy - - -
    -

    The SecPolicy used to evaluate self.

    -
    -
    - - errorProducer - - -
    -

    The closure used transform the failed OSStatus and SecTrustResultType.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - apply(policy:) - -
    -
    -
    -
    -
    -
    -

    Applies a SecPolicy to self, throwing if it fails.

    -
    -

    Throws

    -

    An AFError.serverTrustEvaluationFailed instance with a .policyApplicationFailed reason.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func apply(policy: SecPolicy) throws -> SecTrust
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - policy - - -
    -

    The SecPolicy.

    -
    -
    -
    -
    -

    Return Value

    -

    self, with the policy applied.

    -
    -
    -
    -
  • -
  • -
    - - - - evaluate() - -
    -
    -
    -
    -
    -
    -

    Evaluate self, throwing an Error if evaluation fails.

    -
    -

    Throws

    - AFError.serverTrustEvaluationFailed with reason .trustValidationFailed and associated error from - the underlying evaluation. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS 12, OSX 10.14, tvOS 12, watchOS 5, *)
    -func evaluate() throws
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validate self, passing any failure values through errorProducer.

    -
    -

    Throws

    - The Error produced by the errorProducer closure. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(﹚")
    -@available(OSX, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(﹚")
    -@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(﹚")
    -@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(﹚")
    -func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - errorProducer - - -
    -

    The closure used to transform the failed OSStatus and SecTrustResultType into an - Error.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a custom certificate chain on self, allowing full validation of a self-signed certificate and its chain.

    -
    -

    Throws

    - Any error produced when applying the new certificate chain. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func setAnchorCertificates(_ certificates: [SecCertificate]) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - certificates - - -
    -

    The SecCertificates to add to the chain.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    The public keys contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    The SecCertificates contained i self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificateData - -
    -
    -
    -
    -
    -
    -

    The Data values for all certificates contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificateData: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates self after applying SecPolicy.af.default. This evaluation does not validate the hostname.

    -
    -

    Throws

    - An AFError.serverTrustEvaluationFailed instance with a .defaultEvaluationFailed reason. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performDefaultValidation(forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The hostname, used only in the error output if validation fails.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates self after applying SecPolicy.af.hostname(host), which performs the default validation as well as -hostname validation.

    -
    -

    Throws

    - An AFError.serverTrustEvaluationFailed instance with a .defaultEvaluationFailed reason. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performValidation(forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The hostname to use in the validation.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy instance which will validate server certificates but not require a host name match.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let `default`: SecPolicy
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - hostname(_:) - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy instance which will validate server certificates and much match the provided hostname.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func hostname(_ hostname: String) -> SecPolicy
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - hostname - - -
    -

    The hostname to validate against.

    -
    -
    -
    -
    -

    Return Value

    -

    The SecPolicy.

    -
    -
    -
    -
  • -
  • -
    - - - - revocation(options:) - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy which checks the revocation of certificates.

    -
    -

    Throws

    -

    An AFError.serverTrustEvaluationFailed error with reason .revocationPolicyCreationFailed - if the policy cannot be created.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - options - - -
    -

    The RevocationTrustEvaluator.Options for evaluation.

    -
    -
    -
    -
    -

    Return Value

    -

    The SecPolicy.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    All Data values for the contained SecCertificates.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var data: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    All public SecKey values for the contained SecCertificates.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - publicKey - -
    -
    -
    -
    -
    -
    -

    The public key for self, if it can be extracted.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKey: SecKey? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns whether self is errSecSuccess.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns whether self is.unspecifiedor.proceed`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Alamofire’s default configuration. Same as URLSessionConfiguration.default but adds Alamofire default -Accept-Language, Accept-Encoding, and User-Agent headers.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DataResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DataResponse.html deleted file mode 100644 index 36cdb48..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DataResponse.html +++ /dev/null @@ -1,1071 +0,0 @@ - - - - DataResponse Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponse

-
-
-
public struct DataResponse<Success, Failure> where Failure : Error
- -
-
-

Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The URL request sent to the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let request: URLRequest?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    The server’s response to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let response: HTTPURLResponse?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    The data returned by the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let data: Data?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    The final metrics of the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let metrics: URLSessionTaskMetrics?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationDuration - -
    -
    -
    -
    -
    -
    -

    The time taken to serialize the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationDuration: TimeInterval
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: Result<Success, Failure>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value of the result if it is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Success? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result if it is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Failure? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a DataResponse instance with the specified parameters derived from the response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(request: URLRequest?,
    -            response: HTTPURLResponse?,
    -            data: Data?,
    -            metrics: URLSessionTaskMetrics?,
    -            serializationDuration: TimeInterval,
    -            result: Result<Success, Failure>)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    The URLRequest sent to the server.

    -
    -
    - - response - - -
    -

    The HTTPURLResponse from the server.

    -
    -
    - - data - - -
    -

    The Data returned by the server.

    -
    -
    - - metrics - - -
    -

    The URLSessionTaskMetrics of the DataRequest or UploadRequest.

    -
    -
    - - serializationDuration - - -
    -

    The duration taken by serialization.

    -
    -
    - - result - - -
    -

    The Result of response serialization.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes the URL request, the URL -response, the server data, the duration of the network and serialization actions, and the response serialization -result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the result of this DataResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleInt = possibleData.map { $0.count }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse whose result wraps the value returned by the given closure. If this instance’s - result is a failure, returns a response wrapping the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DataResponse is a success, passing the unwrapped result -value as a parameter.

    - -

    Use the tryMap method with a closure that may throw an error. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleObject = possibleData.tryMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A success or failure DataResponse depending on the result of the given closure. If this instance’s - result is a failure, returns the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let withMyError = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the tryMapError function with a closure that may throw an error. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleObject = possibleData.tryMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMapError<NewFailure>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DownloadResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DownloadResponse.html deleted file mode 100644 index 4a59706..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/DownloadResponse.html +++ /dev/null @@ -1,1123 +0,0 @@ - - - - DownloadResponse Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadResponse

-
-
-
public struct DownloadResponse<Success, Failure> where Failure : Error
- -
-
-

Used to store all data associated with a serialized response of a download request.

- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The URL request sent to the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let request: URLRequest?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    The server’s response to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let response: HTTPURLResponse?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileURL - -
    -
    -
    -
    -
    -
    -

    The final destination URL of the data returned from the server after it is moved.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let fileURL: URL?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumeData - -
    -
    -
    -
    -
    -
    -

    The resume data generated if the request was cancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let resumeData: Data?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    The final metrics of the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let metrics: URLSessionTaskMetrics?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationDuration - -
    -
    -
    -
    -
    -
    -

    The time taken to serialize the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationDuration: TimeInterval
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: Result<Success, Failure>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value of the result if it is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Success? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result if it is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Failure? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a DownloadResponse instance with the specified parameters derived from response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(request: URLRequest?,
    -            response: HTTPURLResponse?,
    -            fileURL: URL?,
    -            resumeData: Data?,
    -            metrics: URLSessionTaskMetrics?,
    -            serializationDuration: TimeInterval,
    -            result: Result<Success, Failure>)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    The URLRequest sent to the server.

    -
    -
    - - response - - -
    -

    The HTTPURLResponse from the server.

    -
    -
    - - temporaryURL - - -
    -

    The temporary destination URL of the data returned from the server.

    -
    -
    - - destinationURL - - -
    -

    The final destination URL of the data returned from the server, if it was moved.

    -
    -
    - - resumeData - - -
    -

    The resume Data generated if the request was cancelled.

    -
    -
    - - metrics - - -
    -

    The URLSessionTaskMetrics of the DownloadRequest.

    -
    -
    - - serializationDuration - - -
    -

    The duration taken by serialization.

    -
    -
    - - result - - -
    -

    The Result of response serialization.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes the URL request, the URL -response, the temporary and destination URLs, the resume data, the durations of the network and serialization -actions, and the response serialization result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleInt = possibleData.map { $0.count }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse whose result wraps the value returned by the given closure. If this instance’s - result is a failure, returns a response wrapping the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the tryMap method with a closure that may throw an error. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleObject = possibleData.tryMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A success or failure DownloadResponse depending on the result of the given closure. If this -instance’s result is a failure, returns the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let withMyError = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the tryMapError function with a closure that may throw an error. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleObject = possibleData.tryMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMapError<NewFailure>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Empty.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Empty.html deleted file mode 100644 index f1643f7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Empty.html +++ /dev/null @@ -1,515 +0,0 @@ - - - - Empty Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Empty

-
-
-
public struct Empty : Decodable
- -
-
-

Type representing an empty response. Use Empty.value to get the static instance.

- -
-
- -
-
-
-
    -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Static Empty instance used for all Empty responses.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let value: Empty
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - emptyValue() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func emptyValue() -> Empty
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/GoogleXSSIPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/GoogleXSSIPreprocessor.html deleted file mode 100644 index 9ee4520..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/GoogleXSSIPreprocessor.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - GoogleXSSIPreprocessor Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

GoogleXSSIPreprocessor

-
-
-
public struct GoogleXSSIPreprocessor : DataPreprocessor
- -
-
-

DataPreprocessor that trims Google’s typical )]}',\n XSSI JSON header.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeader.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeader.html deleted file mode 100644 index d27ba71..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeader.html +++ /dev/null @@ -1,1238 +0,0 @@ - - - - HTTPHeader Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPHeader

-
-
-
public struct HTTPHeader : Hashable
- -
-
-

A representation of a single HTTP header’s name / value pair.

- -
-
- -
-
-
-
    -
  • -
    - - - - name - -
    -
    -
    -
    -
    -
    -

    Name of the header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let name: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Value of the header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let value: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(name:value:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from the given name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The name of the header.

    -
    -
    - - value - - -
    -

    The value of the header.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - accept(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func accept(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptCharset(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Charset header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptCharset(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Charset value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptLanguage(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Language header.

    - -

    Alamofire offers a default Accept-Language header that accumulates and encodes the system’s preferred languages. -Use HTTPHeader.defaultAcceptLanguage.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptLanguage(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Language value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptEncoding(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Encoding header.

    - -

    Alamofire offers a default accept encoding value that provides the most common values. Use -HTTPHeader.defaultAcceptEncoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptEncoding(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Encoding value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Basic Authorization header using the username and password provided.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(username: String, password: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - username - - -
    -

    The username of the header.

    -
    -
    - - password - - -
    -

    The password of the header.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Bearer Authorization header using the bearerToken provided

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(bearerToken: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - bearerToken - - -
    -

    The bearer token.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - authorization(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Authorization header.

    - -

    Alamofire provides built-in methods to produce Authorization headers. For a Basic Authorization header use -HTTPHeader.authorization(username:password:). For a Bearer Authorization header, use -HTTPHeader.authorization(bearerToken:).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Authorization value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Content-Disposition header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func contentDisposition(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Content-Disposition value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - contentType(_:) - -
    -
    -
    -
    -
    -
    -

    Returns a Content-Type header.

    - -

    All Alamofire ParameterEncodings and ParameterEncoders set the Content-Type of the request, so it may not be necessary to manually -set this value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func contentType(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Content-Type value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - userAgent(_:) - -
    -
    -
    -
    -
    -
    -

    Returns a User-Agent header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func userAgent(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The User-Agent value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - defaultAcceptEncoding - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default Accept-Encoding header, appropriate for the encodings supported by particular OS -versions.

    - -

    See the Accept-Encoding HTTP header documentation .

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultAcceptEncoding: HTTPHeader
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultAcceptLanguage - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default Accept-Language header, generated by querying Locale for the user’s -preferredLanguages.

    - -

    See the Accept-Language HTTP header documentation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultAcceptLanguage: HTTPHeader
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultUserAgent - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default User-Agent header.

    - -

    See the User-Agent header documentation.

    - -

    Example: iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultUserAgent: HTTPHeader
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeaders.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeaders.html deleted file mode 100644 index a54387b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPHeaders.html +++ /dev/null @@ -1,1238 +0,0 @@ - - - - HTTPHeaders Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPHeaders

-
-
-
public struct HTTPHeaders
- -
-
-

An order-preserving and case-insensitive representation of HTTP headers.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an empty instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from an array of HTTPHeaders. Duplicate case-insensitive names are collapsed into the last -name and value encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ headers: [HTTPHeader])
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from a [String: String]. Duplicate case-insensitive names are collapsed into the last name -and value encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ dictionary: [String : String])
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - add(name:value:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func add(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The HTTPHeader name.

    -
    -
    - - value - - -
    -

    The `HTTPHeader value.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - add(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends the provided HTTPHeader into the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func add(_ header: HTTPHeader)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - header - - -
    -

    The HTTPHeader to update or append.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - update(name:value:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func update(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The HTTPHeader name.

    -
    -
    - - value - - -
    -

    The `HTTPHeader value.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - update(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends the provided HTTPHeader into the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func update(_ header: HTTPHeader)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - header - - -
    -

    The HTTPHeader to update or append.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - remove(name:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively removes an HTTPHeader, if it exists, from the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func remove(name: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the HTTPHeader to remove.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - sort() - -
    -
    -
    -
    -
    -
    -

    Sort the current instance by header name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func sort()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sorted() - -
    -
    -
    -
    -
    -
    -

    Returns an instance sorted by header name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func sorted() -> HTTPHeaders
    - -
    -
    -
    -

    Return Value

    -

    A copy of the current instance sorted by name.

    -
    -
    -
    -
  • -
  • -
    - - - - value(for:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively find a header’s value by name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func value(for name: String) -> String?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the header to search for, case-insensitively.

    -
    -
    -
    -
    -

    Return Value

    -

    The value of header, if it exists.

    -
    -
    -
    -
  • -
  • -
    - - - - subscript(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively access the header with the given name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public subscript(name: String) -> String? { get set }
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the header.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - dictionary - -
    -
    -
    -
    -
    -
    -

    The dictionary representation of all headers.

    - -

    This representation does not preserve the current order of the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var dictionary: [String : String] { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dictionaryLiteral elements: (String, String)...)
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - makeIterator() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func makeIterator() -> IndexingIterator<[HTTPHeader]>
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - startIndex - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var startIndex: Int { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - endIndex - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var endIndex: Int { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - subscript(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public subscript(position: Int) -> HTTPHeader { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - index(after:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func index(after i: Int) -> Int
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    The default set of HTTPHeaders used by Alamofire. Includes Accept-Encoding, Accept-Language, and -User-Agent.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let `default`: HTTPHeaders
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPMethod.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPMethod.html deleted file mode 100644 index 512f9be..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/HTTPMethod.html +++ /dev/null @@ -1,749 +0,0 @@ - - - - HTTPMethod Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPMethod

-
-
-
public struct HTTPMethod : RawRepresentable, Equatable, Hashable
- -
-
-

Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so -HTTPMethod.get != HTTPMethod(rawValue: "get").

- -

See https://tools.ietf.org/html/rfc7231#section-4.3

- -
-
- -
-
-
-
    -
  • -
    - - - - connect - -
    -
    -
    -
    -
    -
    -

    CONNECT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let connect: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delete - -
    -
    -
    -
    -
    -
    -

    DELETE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let delete: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - get - -
    -
    -
    -
    -
    -
    -

    GET method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let get: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - head - -
    -
    -
    -
    -
    -
    -

    HEAD method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let head: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    OPTIONS method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let options: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - patch - -
    -
    -
    -
    -
    -
    -

    PATCH method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let patch: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - post - -
    -
    -
    -
    -
    -
    -

    POST method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let post: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - put - -
    -
    -
    -
    -
    -
    -

    PUT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let put: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trace - -
    -
    -
    -
    -
    -
    -

    TRACE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let trace: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/JSONEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/JSONEncoding.html deleted file mode 100644 index 98a6069..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/JSONEncoding.html +++ /dev/null @@ -1,701 +0,0 @@ - - - - JSONEncoding Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONEncoding

-
-
-
public struct JSONEncoding : ParameterEncoding
- -
-
-

Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the -request. The Content-Type HTTP header field of an encoded request is set to application/json.

- -
-
- -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns a JSONEncoding instance with default writing options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: JSONEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - prettyPrinted - -
    -
    -
    -
    -
    -
    -

    Returns a JSONEncoding instance with .prettyPrinted writing options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var prettyPrinted: JSONEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    The options for writing the parameters as JSON data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let options: JSONSerialization.WritingOptions
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(options:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the specified WritingOptions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(options: JSONSerialization.WritingOptions = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - options - - -
    -

    JSONSerialization.WritingOptions to use.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Encodes any JSON compatible object into a URLRequest.

    -
    -

    Throws

    -

    Any Error produced during encoding.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - urlRequest - - -
    -

    URLRequestConvertible value into which the object will be encoded.

    -
    -
    - - jsonObject - - -
    -

    Any value (must be JSON compatibleto be encoded into theURLRequest.nil` by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded URLRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/PassthroughPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/PassthroughPreprocessor.html deleted file mode 100644 index fc44f37..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/PassthroughPreprocessor.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - PassthroughPreprocessor Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PassthroughPreprocessor

-
-
-
public struct PassthroughPreprocessor : DataPreprocessor
- -
-
-

DataPreprocessor that returns passed Data without any transform.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector.html deleted file mode 100644 index 0704e9c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector.html +++ /dev/null @@ -1,639 +0,0 @@ - - - - Redirector Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Redirector

-
-
-
public struct Redirector
- -
-
-

Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

- -
-
- -
-
-
-
    -
  • -
    - - - - Behavior - -
    -
    -
    -
    -
    -
    -

    Defines the behavior of the Redirector type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - follow - -
    -
    -
    -
    -
    -
    -

    Returns a Redirector with a .follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let follow: Redirector
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotFollow - -
    -
    -
    -
    -
    -
    -

    Returns a Redirector with a .doNotFollow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let doNotFollow: Redirector
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - behavior - -
    -
    -
    -
    -
    -
    -

    The Behavior of the Redirector.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let behavior: Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(behavior:) - -
    -
    -
    -
    -
    -
    -

    Creates a Redirector instance from the Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(behavior: Behavior)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - behavior - - -
    -

    The Behavior.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func task(_ task: URLSessionTask,
    -                 willBeRedirectedTo request: URLRequest,
    -                 for response: HTTPURLResponse,
    -                 completion: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector/Behavior.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector/Behavior.html deleted file mode 100644 index 9e1f452..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/Redirector/Behavior.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - Behavior Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Behavior

-
-
-
public enum Behavior
- -
-
-

Defines the behavior of the Redirector type.

- -
-
- -
-
-
-
    -
  • -
    - - - - follow - -
    -
    -
    -
    -
    -
    -

    Follow the redirect as defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case follow
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotFollow - -
    -
    -
    -
    -
    -
    -

    Do not follow the redirect defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotFollow
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - modify(_:) - -
    -
    -
    -
    -
    -
    -

    Modify the redirect request defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher.html deleted file mode 100644 index a7f7a11..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher.html +++ /dev/null @@ -1,639 +0,0 @@ - - - - ResponseCacher Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseCacher

-
-
-
public struct ResponseCacher
- -
-
-

ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached -response.

- -
-
- -
-
-
-
    -
  • -
    - - - - Behavior - -
    -
    -
    -
    -
    -
    -

    Defines the behavior of the ResponseCacher type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cache - -
    -
    -
    -
    -
    -
    -

    Returns a ResponseCacher with a follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let cache: ResponseCacher
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotCache - -
    -
    -
    -
    -
    -
    -

    Returns a ResponseCacher with a do not follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let doNotCache: ResponseCacher
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - behavior - -
    -
    -
    -
    -
    -
    -

    The Behavior of the ResponseCacher.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let behavior: Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(behavior:) - -
    -
    -
    -
    -
    -
    -

    Creates a ResponseCacher instance from the Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(behavior: Behavior)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - behavior - - -
    -

    The Behavior.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func dataTask(_ task: URLSessionDataTask,
    -                     willCacheResponse response: CachedURLResponse,
    -                     completion: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher/Behavior.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher/Behavior.html deleted file mode 100644 index 66d2691..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/ResponseCacher/Behavior.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - Behavior Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Behavior

-
-
-
public enum Behavior
- -
-
-

Defines the behavior of the ResponseCacher type.

- -
-
- -
-
-
-
    -
  • -
    - - - - cache - -
    -
    -
    -
    -
    -
    -

    Stores the cached response in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cache
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotCache - -
    -
    -
    -
    -
    -
    -

    Prevents the cached response from being stored in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotCache
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - modify(_:) - -
    -
    -
    -
    -
    -
    -

    Modifies the cached response before storing it in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding.html deleted file mode 100644 index b7b0ee5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding.html +++ /dev/null @@ -1,962 +0,0 @@ - - - - URLEncoding Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncoding

-
-
-
public struct URLEncoding : ParameterEncoding
- -
-
-

Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -the HTTP body depends on the destination of the encoding.

- -

The Content-Type HTTP header field of an encoded request with HTTP body is set to -application/x-www-form-urlencoded; charset=utf-8.

- -

There is no published specification for how to encode collection types. By default the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

- -

BoolEncoding can be used to configure how boolean values are encoded. The default behavior is to encode -true as 1 and false as 0.

- -
-
- -
-
-
- -
    -
  • -
    - - - - Destination - -
    -
    -
    -
    -
    -
    -

    Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the -resulting URL request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Destination
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ArrayEncoding - -
    -
    -
    -
    -
    -
    -

    Configures how Array parameters are encoded.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - BoolEncoding - -
    -
    -
    -
    -
    -
    -

    Configures how Bool parameters are encoded.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum BoolEncoding
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns a default URLEncoding instance with a .methodDependent destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Returns a URLEncoding instance with a .queryString destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var queryString: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Returns a URLEncoding instance with an .httpBody destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var httpBody: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - destination - -
    -
    -
    -
    -
    -
    -

    The destination defining where the encoded query string is to be applied to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let destination: Destination
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - arrayEncoding - -
    -
    -
    -
    -
    -
    -

    The encoding to use for Array parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let arrayEncoding: ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boolEncoding - -
    -
    -
    -
    -
    -
    -

    The encoding to use for Bool parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boolEncoding: BoolEncoding
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the specified parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(destination: Destination = .methodDependent,
    -            arrayEncoding: ArrayEncoding = .brackets,
    -            boolEncoding: BoolEncoding = .numeric)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - destination - - -
    -

    Destination defining where the encoded query string will be applied. .methodDependent by - default.

    -
    -
    - - arrayEncoding - - -
    -

    ArrayEncoding to use. .brackets by default.

    -
    -
    - - boolEncoding - - -
    -

    BoolEncoding to use. .numeric by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func queryComponents(fromKey key: String, value: Any) -> [(String, String)]
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - key - - -
    -

    Key of the query component.

    -
    -
    - - value - - -
    -

    Value of the query component.

    -
    -
    -
    -
    -

    Return Value

    -

    The percent-escaped, URL encoded query string components.

    -
    -
    -
    -
  • -
  • -
    - - - - escape(_:) - -
    -
    -
    -
    -
    -
    -

    Creates a percent-escaped string following RFC 3986 for a query string key or value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func escape(_ string: String) -> String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - string - - -
    -

    String to be percent-escaped.

    -
    -
    -
    -
    -

    Return Value

    -

    The percent-escaped String.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/ArrayEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/ArrayEncoding.html deleted file mode 100644 index e56c1d4..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/ArrayEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ArrayEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ArrayEncoding

-
-
-
public enum ArrayEncoding
- -
-
-

Configures how Array parameters are encoded.

- -
-
- -
-
-
-
    -
  • -
    - - - - brackets - -
    -
    -
    -
    -
    -
    -

    An empty set of square brackets is appended to the key for every value. This is the default behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case brackets
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noBrackets - -
    -
    -
    -
    -
    -
    -

    No brackets are appended. The key is encoded as is.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noBrackets
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/BoolEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/BoolEncoding.html deleted file mode 100644 index 135d90e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/BoolEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - BoolEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

BoolEncoding

-
-
-
public enum BoolEncoding
- -
-
-

Configures how Bool parameters are encoded.

- -
-
- -
-
-
-
    -
  • -
    - - - - numeric - -
    -
    -
    -
    -
    -
    -

    Encode true as 1 and false as 0. This is the default behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case numeric
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - literal - -
    -
    -
    -
    -
    -
    -

    Encode true and false as string literals.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case literal
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/Destination.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/Destination.html deleted file mode 100644 index 6511875..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Structs/URLEncoding/Destination.html +++ /dev/null @@ -1,534 +0,0 @@ - - - - Destination Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Destination

-
-
-
public enum Destination
- -
-
-

Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the -resulting URL request.

- -
-
- -
-
-
-
    -
  • -
    - - - - methodDependent - -
    -
    -
    -
    -
    -
    -

    Applies encoded query string result to existing query string for GET, HEAD and DELETE requests and -sets as the HTTP body for requests with any other HTTP method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case methodDependent
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Sets or appends encoded query string result to existing query string.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case queryString
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Sets encoded query string result as the HTTP body of the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpBody
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/Typealiases.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/Typealiases.html deleted file mode 100644 index 2b6f748..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/Typealiases.html +++ /dev/null @@ -1,619 +0,0 @@ - - - - Type Aliases Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Type Aliases

-

The following type aliases are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - Parameters - -
    -
    -
    -
    -
    -
    -

    A dictionary of parameters to apply to a URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Parameters = [String : Any]
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - AdaptHandler - -
    -
    -
    -
    -
    -
    -

    RequestAdapter closure definition.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result<URLRequest, Error>) -> Void) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - RetryHandler - -
    -
    -
    -
    -
    -
    -

    RequestRetrier closure definition.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - AFResult - -
    -
    -
    -
    -
    -
    -

    Default type of Result returned by Alamofire, with an AFError Failure type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias AFResult<Success> = Result<Success, AFError>
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/badge.svg b/Lesson12/Carthage/Checkouts/Alamofire/docs/badge.svg deleted file mode 100644 index f47d948..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/badge.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - documentation - - - documentation - - - 98% - - - 98% - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/css/highlight.css b/Lesson12/Carthage/Checkouts/Alamofire/docs/css/highlight.css deleted file mode 100644 index d0db0e1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/css/highlight.css +++ /dev/null @@ -1,200 +0,0 @@ -/* Credit to https://gist.github.com/wataru420/2048287 */ -.highlight { - /* Comment */ - /* Error */ - /* Keyword */ - /* Operator */ - /* Comment.Multiline */ - /* Comment.Preproc */ - /* Comment.Single */ - /* Comment.Special */ - /* Generic.Deleted */ - /* Generic.Deleted.Specific */ - /* Generic.Emph */ - /* Generic.Error */ - /* Generic.Heading */ - /* Generic.Inserted */ - /* Generic.Inserted.Specific */ - /* Generic.Output */ - /* Generic.Prompt */ - /* Generic.Strong */ - /* Generic.Subheading */ - /* Generic.Traceback */ - /* Keyword.Constant */ - /* Keyword.Declaration */ - /* Keyword.Pseudo */ - /* Keyword.Reserved */ - /* Keyword.Type */ - /* Literal.Number */ - /* Literal.String */ - /* Name.Attribute */ - /* Name.Builtin */ - /* Name.Class */ - /* Name.Constant */ - /* Name.Entity */ - /* Name.Exception */ - /* Name.Function */ - /* Name.Namespace */ - /* Name.Tag */ - /* Name.Variable */ - /* Operator.Word */ - /* Text.Whitespace */ - /* Literal.Number.Float */ - /* Literal.Number.Hex */ - /* Literal.Number.Integer */ - /* Literal.Number.Oct */ - /* Literal.String.Backtick */ - /* Literal.String.Char */ - /* Literal.String.Doc */ - /* Literal.String.Double */ - /* Literal.String.Escape */ - /* Literal.String.Heredoc */ - /* Literal.String.Interpol */ - /* Literal.String.Other */ - /* Literal.String.Regex */ - /* Literal.String.Single */ - /* Literal.String.Symbol */ - /* Name.Builtin.Pseudo */ - /* Name.Variable.Class */ - /* Name.Variable.Global */ - /* Name.Variable.Instance */ - /* Literal.Number.Integer.Long */ } - .highlight .c { - color: #999988; - font-style: italic; } - .highlight .err { - color: #a61717; - background-color: #e3d2d2; } - .highlight .k { - color: #000000; - font-weight: bold; } - .highlight .o { - color: #000000; - font-weight: bold; } - .highlight .cm { - color: #999988; - font-style: italic; } - .highlight .cp { - color: #999999; - font-weight: bold; } - .highlight .c1 { - color: #999988; - font-style: italic; } - .highlight .cs { - color: #999999; - font-weight: bold; - font-style: italic; } - .highlight .gd { - color: #000000; - background-color: #ffdddd; } - .highlight .gd .x { - color: #000000; - background-color: #ffaaaa; } - .highlight .ge { - color: #000000; - font-style: italic; } - .highlight .gr { - color: #aa0000; } - .highlight .gh { - color: #999999; } - .highlight .gi { - color: #000000; - background-color: #ddffdd; } - .highlight .gi .x { - color: #000000; - background-color: #aaffaa; } - .highlight .go { - color: #888888; } - .highlight .gp { - color: #555555; } - .highlight .gs { - font-weight: bold; } - .highlight .gu { - color: #aaaaaa; } - .highlight .gt { - color: #aa0000; } - .highlight .kc { - color: #000000; - font-weight: bold; } - .highlight .kd { - color: #000000; - font-weight: bold; } - .highlight .kp { - color: #000000; - font-weight: bold; } - .highlight .kr { - color: #000000; - font-weight: bold; } - .highlight .kt { - color: #445588; } - .highlight .m { - color: #009999; } - .highlight .s { - color: #d14; } - .highlight .na { - color: #008080; } - .highlight .nb { - color: #0086B3; } - .highlight .nc { - color: #445588; - font-weight: bold; } - .highlight .no { - color: #008080; } - .highlight .ni { - color: #800080; } - .highlight .ne { - color: #990000; - font-weight: bold; } - .highlight .nf { - color: #990000; } - .highlight .nn { - color: #555555; } - .highlight .nt { - color: #000080; } - .highlight .nv { - color: #008080; } - .highlight .ow { - color: #000000; - font-weight: bold; } - .highlight .w { - color: #bbbbbb; } - .highlight .mf { - color: #009999; } - .highlight .mh { - color: #009999; } - .highlight .mi { - color: #009999; } - .highlight .mo { - color: #009999; } - .highlight .sb { - color: #d14; } - .highlight .sc { - color: #d14; } - .highlight .sd { - color: #d14; } - .highlight .s2 { - color: #d14; } - .highlight .se { - color: #d14; } - .highlight .sh { - color: #d14; } - .highlight .si { - color: #d14; } - .highlight .sx { - color: #d14; } - .highlight .sr { - color: #009926; } - .highlight .s1 { - color: #d14; } - .highlight .ss { - color: #990073; } - .highlight .bp { - color: #999999; } - .highlight .vc { - color: #008080; } - .highlight .vg { - color: #008080; } - .highlight .vi { - color: #008080; } - .highlight .il { - color: #009999; } diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/css/jazzy.css b/Lesson12/Carthage/Checkouts/Alamofire/docs/css/jazzy.css deleted file mode 100644 index 833be0d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/css/jazzy.css +++ /dev/null @@ -1,378 +0,0 @@ -*, *:before, *:after { - box-sizing: inherit; } - -body { - margin: 0; - background: #fff; - color: #333; - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - letter-spacing: .2px; - -webkit-font-smoothing: antialiased; - box-sizing: border-box; } - -h1 { - font-size: 2rem; - font-weight: 700; - margin: 1.275em 0 0.6em; } - -h2 { - font-size: 1.75rem; - font-weight: 700; - margin: 1.275em 0 0.3em; } - -h3 { - font-size: 1.5rem; - font-weight: 700; - margin: 1em 0 0.3em; } - -h4 { - font-size: 1.25rem; - font-weight: 700; - margin: 1.275em 0 0.85em; } - -h5 { - font-size: 1rem; - font-weight: 700; - margin: 1.275em 0 0.85em; } - -h6 { - font-size: 1rem; - font-weight: 700; - margin: 1.275em 0 0.85em; - color: #777; } - -p { - margin: 0 0 1em; } - -ul, ol { - padding: 0 0 0 2em; - margin: 0 0 0.85em; } - -blockquote { - margin: 0 0 0.85em; - padding: 0 15px; - color: #858585; - border-left: 4px solid #e5e5e5; } - -img { - max-width: 100%; } - -a { - color: #4183c4; - text-decoration: none; } - a:hover, a:focus { - outline: 0; - text-decoration: underline; } - a.discouraged { - text-decoration: line-through; } - a.discouraged:hover, a.discouraged:focus { - text-decoration: underline line-through; } - -table { - background: #fff; - width: 100%; - border-collapse: collapse; - border-spacing: 0; - overflow: auto; - margin: 0 0 0.85em; } - -tr:nth-child(2n) { - background-color: #fbfbfb; } - -th, td { - padding: 6px 13px; - border: 1px solid #ddd; } - -pre { - margin: 0 0 1.275em; - padding: .85em 1em; - overflow: auto; - background: #f7f7f7; - font-size: .85em; - font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; } - -code { - font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; } - -p > code, li > code { - background: #f7f7f7; - padding: .2em; } - p > code:before, p > code:after, li > code:before, li > code:after { - letter-spacing: -.2em; - content: "\00a0"; } - -pre code { - padding: 0; - white-space: pre; } - -.content-wrapper { - display: flex; - flex-direction: column; } - @media (min-width: 768px) { - .content-wrapper { - flex-direction: row; } } - -.header { - display: flex; - padding: 8px; - font-size: 0.875em; - background: #444; - color: #999; } - -.header-col { - margin: 0; - padding: 0 8px; } - -.header-col--primary { - flex: 1; } - -.header-link { - color: #fff; } - -.header-icon { - padding-right: 6px; - vertical-align: -4px; - height: 16px; } - -.breadcrumbs { - font-size: 0.875em; - padding: 8px 16px; - margin: 0; - background: #fbfbfb; - border-bottom: 1px solid #ddd; } - -.carat { - height: 10px; - margin: 0 5px; } - -.navigation { - order: 2; } - @media (min-width: 768px) { - .navigation { - order: 1; - width: 25%; - max-width: 300px; - padding-bottom: 64px; - overflow: hidden; - word-wrap: normal; - background: #fbfbfb; - border-right: 1px solid #ddd; } } - -.nav-groups { - list-style-type: none; - padding-left: 0; } - -.nav-group-name { - border-bottom: 1px solid #ddd; - padding: 8px 0 8px 16px; } - -.nav-group-name-link { - color: #333; } - -.nav-group-tasks { - margin: 8px 0; - padding: 0 0 0 8px; } - -.nav-group-task { - font-size: 1em; - list-style-type: none; - white-space: nowrap; } - -.nav-group-task-link { - color: #808080; } - -.main-content { - order: 1; } - @media (min-width: 768px) { - .main-content { - order: 2; - flex: 1; - padding-bottom: 60px; } } - -.section { - padding: 0 32px; - border-bottom: 1px solid #ddd; } - -.section-content { - max-width: 834px; - margin: 0 auto; - padding: 16px 0; } - -.section-name { - color: #666; - display: block; } - -.declaration .highlight { - overflow-x: initial; - padding: 8px 0; - margin: 0; - background-color: transparent; - border: none; } - -.task-group-section { - border-top: 1px solid #ddd; } - -.task-group { - padding-top: 0px; } - -.task-name-container a[name]:before { - content: ""; - display: block; } - -.item-container { - padding: 0; } - -.item { - padding-top: 8px; - width: 100%; - list-style-type: none; } - .item a[name]:before { - content: ""; - display: block; } - .item .token, .item .direct-link { - padding-left: 3px; - margin-left: 0px; - font-size: 1rem; } - .item .declaration-note { - font-size: .85em; - color: #808080; - font-style: italic; } - -.pointer-container { - border-bottom: 1px solid #ddd; - left: -23px; - padding-bottom: 13px; - position: relative; - width: 110%; } - -.pointer { - left: 21px; - top: 7px; - display: block; - position: absolute; - width: 12px; - height: 12px; - border-left: 1px solid #ddd; - border-top: 1px solid #ddd; - background: #fff; - transform: rotate(45deg); } - -.height-container { - display: none; - position: relative; - width: 100%; - overflow: hidden; } - .height-container .section { - background: #fff; - border: 1px solid #ddd; - border-top-width: 0; - padding-top: 10px; - padding-bottom: 5px; - padding: 8px 16px; } - -.aside, .language { - padding: 6px 12px; - margin: 12px 0; - border-left: 5px solid #dddddd; - overflow-y: hidden; } - .aside .aside-title, .language .aside-title { - font-size: 9px; - letter-spacing: 2px; - text-transform: uppercase; - padding-bottom: 0; - margin: 0; - color: #aaa; - -webkit-user-select: none; } - .aside p:last-child, .language p:last-child { - margin-bottom: 0; } - -.language { - border-left: 5px solid #cde9f4; } - .language .aside-title { - color: #4183c4; } - -.aside-warning, .aside-deprecated, .aside-unavailable { - border-left: 5px solid #ff6666; } - .aside-warning .aside-title, .aside-deprecated .aside-title, .aside-unavailable .aside-title { - color: #ff0000; } - -.graybox { - border-collapse: collapse; - width: 100%; } - .graybox p { - margin: 0; - word-break: break-word; - min-width: 50px; } - .graybox td { - border: 1px solid #ddd; - padding: 5px 25px 5px 10px; - vertical-align: middle; } - .graybox tr td:first-of-type { - text-align: right; - padding: 7px; - vertical-align: top; - word-break: normal; - width: 40px; } - -.slightly-smaller { - font-size: 0.9em; } - -.footer { - padding: 8px 16px; - background: #444; - color: #ddd; - font-size: 0.8em; } - .footer p { - margin: 8px 0; } - .footer a { - color: #fff; } - -html.dash .header, html.dash .breadcrumbs, html.dash .navigation { - display: none; } - -html.dash .height-container { - display: block; } - -form[role=search] input { - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - line-height: 24px; - padding: 0 10px; - margin: 0; - border: none; - border-radius: 1em; } - .loading form[role=search] input { - background: white url(../img/spinner.gif) center right 4px no-repeat; } - -form[role=search] .tt-menu { - margin: 0; - min-width: 300px; - background: #fbfbfb; - color: #333; - border: 1px solid #ddd; } - -form[role=search] .tt-highlight { - font-weight: bold; } - -form[role=search] .tt-suggestion { - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - padding: 0 8px; } - form[role=search] .tt-suggestion span { - display: table-cell; - white-space: nowrap; } - form[role=search] .tt-suggestion .doc-parent-name { - width: 100%; - text-align: right; - font-weight: normal; - font-size: 0.9em; - padding-left: 16px; } - -form[role=search] .tt-suggestion:hover, -form[role=search] .tt-suggestion.tt-cursor { - cursor: pointer; - background-color: #4183c4; - color: #fff; } - -form[role=search] .tt-suggestion:hover .doc-parent-name, -form[role=search] .tt-suggestion.tt-cursor .doc-parent-name { - color: #fff; } diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Info.plist b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Info.plist deleted file mode 100644 index 2710d06..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Info.plist +++ /dev/null @@ -1,20 +0,0 @@ - - - - - CFBundleIdentifier - com.jazzy.alamofire - CFBundleName - Alamofire - DocSetPlatformFamily - alamofire - isDashDocset - - dashIndexFilePath - index.html - isJavaScriptEnabled - - DashDocSetFamily - dashtoc - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes.html deleted file mode 100644 index 8036fca..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes.html +++ /dev/null @@ -1,1503 +0,0 @@ - - - - Classes Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Classes

-

The following classes are available globally.

- -
-
- -
-
-
- -
-
-
    -
  • -
    - - - - MultipartFormData - -
    -
    -
    -
    -
    -
    -

    Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode -multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.

    - -

    For more information on multipart/form-data in general, please refer to the RFC-2388 and RFC-2045 specs as well -and the w3 form documentation.

    - - - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class MultipartFormData
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and -WiFi network interfaces.

    - -

    Reachability can be used to determine background information about why a network operation failed, or to retry -network requests when a connection is established. It should not be used to prevent a user from initiating a network -request, as it’s possible that an initial request may be required to establish reachability.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class NetworkReachabilityManager
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Request - -
    -
    -
    -
    -
    -
    -

    Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback -handling.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - JSONParameterEncoder - -
    -
    -
    -
    -
    -
    -

    A ParameterEncoder that encodes types as JSON body data.

    - -

    If no Content-Type header is already set on the provided URLRequests, it’s set to application/json.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class JSONParameterEncoder : ParameterEncoder
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -on the Destination set.

    - -

    If no Content-Type header is already set on the provided URLRequests, it will be set to -application/x-www-form-urlencoded; charset=utf-8.

    - -

    Encoding behavior can be customized by passing an instance of URLEncodedFormEncoder to the initializer.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class URLEncodedFormParameterEncoder : ParameterEncoder
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DataRequest - -
    -
    -
    -
    -
    -
    -

    Request subclass which handles in-memory Data download using URLSessionDataTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class DataRequest : Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DownloadRequest - -
    -
    -
    -
    -
    -
    -

    Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class DownloadRequest : Request
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - UploadRequest - -
    -
    -
    -
    -
    -
    -

    DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class UploadRequest : DataRequest
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
-
- -
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a -request returning nil or no data is considered an error. However, if the response is has a status code valid for -empty responses (204, 205), then an empty Data value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DataResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no -data is considered an error. However, if the response is has a status code valid for empty responses (204, 205), -then an empty String is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class StringResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning -nil or no data is considered an error. However, if the response is has a status code valid for empty responses -(204, 205), then an NSNull value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class JSONResponseSerializer : ResponseSerializer
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    A ResponseSerializer that decodes the response data as a generic value using any type that conforms to -DataDecoder. By default, this is an instance of JSONDecoder. Additionally, a request returning nil or no data -is considered an error. However, if the response is has a status code valid for empty responses (204, 205), then -the Empty.value value is returned.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DecodableResponseSerializer<T> : ResponseSerializer where T : Decodable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RetryPolicy - -
    -
    -
    -
    -
    -
    -

    A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -as well as certain types of networking errors.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class RetryPolicy : RequestInterceptor
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    A retry policy that automatically retries idempotent requests for network connection lost errors. For more -information about retrying network connection lost errors, please refer to Apple’s -technical document.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class ConnectionLostRetryPolicy : RetryPolicy
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
    -
  • -
    - - - - DefaultTrustEvaluator - -
    -
    -
    -
    -
    -
    -

    An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -host provided by the challenge. Applications are encouraged to always validate the host in production environments -to guarantee the validity of the server’s certificate chain.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DefaultTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -environments to guarantee the validity of the server’s certificate chain.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class RevocationTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -certificates match one of the server certificates. By validating both the certificate chain and host, certificate -pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class PinnedCertificatesTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -public keys match one of the server certificate public keys. By validating both the certificate chain and host, -public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class PublicKeysTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -evaluators consider it valid.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class CompositeTrustEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DisabledEvaluator - -
    -
    -
    -
    -
    -
    -

    Disables all evaluation which in turn will always consider any server trust as valid.

    - -

    THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class DisabledEvaluator : ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Session - -
    -
    -
    -
    -
    -
    -

    Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common -functionality for all Requests, including queuing, interception, trust management, redirect handling, and response -cache handling.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class Session
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - SessionDelegate - -
    -
    -
    -
    -
    -
    -

    Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open class SessionDelegate : NSObject
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLEncodedFormEncoder - -
    -
    -
    -
    -
    -
    -

    An object that encodes instances into URL-encoded query strings.

    - -

    There is no published specification for how to encode collection types. By default, the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

    - -

    BoolEncoding can be used to configure how Bool values are encoded. The default behavior is to encode -true as 1 and false as 0.

    - -

    DateEncoding can be used to configure how Date values are encoded. By default, the .deferredToDate -strategy is used, which formats dates from their structure.

    - -

    SpaceEncoding can be used to configure how spaces are encoded. Modern encodings use percent replacement (%20), -while older encodings may expect spaces to be replaced with +.

    - -

    This type is largely based on Vapor’s url-encoded-form project.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public final class URLEncodedFormEncoder
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Adapter.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Adapter.html deleted file mode 100644 index a813e98..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Adapter.html +++ /dev/null @@ -1,523 +0,0 @@ - - - - Adapter Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Adapter

-
-
-
open class Adapter : RequestInterceptor
- -
-
-

Closure-based RequestAdapter.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ adaptHandler: @escaping AdaptHandler)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - adaptHandler - - -
    -

    AdaptHandler closure to be executed when handling request adaptation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/AlamofireNotifications.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/AlamofireNotifications.html deleted file mode 100644 index eafae49..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/AlamofireNotifications.html +++ /dev/null @@ -1,659 +0,0 @@ - - - - AlamofireNotifications Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireNotifications

-
-
-
public final class AlamofireNotifications : EventMonitor
- -
-
-

EventMonitor that provides Alamofire’s notifications.

- -
-
- -
-
-
-
    -
  • -
    - - - - requestDidResume(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidResume(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidSuspend(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidSuspend(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidCancel(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidCancel(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidFinish(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestDidFinish(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didResumeTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didSuspendTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didCancelTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ClosureEventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ClosureEventMonitor.html deleted file mode 100644 index 90cea72..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ClosureEventMonitor.html +++ /dev/null @@ -1,2636 +0,0 @@ - - - - ClosureEventMonitor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ClosureEventMonitor

-
-
-
open class ClosureEventMonitor : EventMonitor
- -
-
-

EventMonitor that allows optional closures to be set to receive events.

- -
-
- -
-
-
- -
-
- - -
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeEventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeEventMonitor.html deleted file mode 100644 index 8d17ddb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeEventMonitor.html +++ /dev/null @@ -1,1572 +0,0 @@ - - - - CompositeEventMonitor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CompositeEventMonitor

-
-
-
public final class CompositeEventMonitor : EventMonitor
- -
-
-

An EventMonitor which can contain multiple EventMonitors and calls their methods on their queues.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeTrustEvaluator.html deleted file mode 100644 index a3bd6f0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/CompositeTrustEvaluator.html +++ /dev/null @@ -1,524 +0,0 @@ - - - - CompositeTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CompositeTrustEvaluator

-
-
-
public final class CompositeTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -evaluators consider it valid.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(evaluators:) - -
    -
    -
    -
    -
    -
    -

    Creates a CompositeTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(evaluators: [ServerTrustEvaluating])
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - evaluators - - -
    -

    The ServerTrustEvaluating values used to evaluate the server trust.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ConnectionLostRetryPolicy.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ConnectionLostRetryPolicy.html deleted file mode 100644 index 36dedcd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ConnectionLostRetryPolicy.html +++ /dev/null @@ -1,542 +0,0 @@ - - - - ConnectionLostRetryPolicy Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionLostRetryPolicy

-
-
-
open class ConnectionLostRetryPolicy : RetryPolicy
- -
-
-

A retry policy that automatically retries idempotent requests for network connection lost errors. For more -information about retrying network connection lost errors, please refer to Apple’s -technical document.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataRequest.html deleted file mode 100644 index 29487ce..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataRequest.html +++ /dev/null @@ -1,1240 +0,0 @@ - - - - DataRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataRequest

-
-
-
public class DataRequest : Request
- -
-
-

Request subclass which handles in-memory Data download using URLSessionDataTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - convertible - -
    -
    -
    -
    -
    -
    -

    URLRequestConvertible value used to create URLRequests for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let convertible: URLRequestConvertible
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    Data read from the server so far.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var data: Data? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(_:) - -
    -
    -
    -
    -
    -
    -

    Validates the request, using the specified closure.

    -
    -

    Note

    -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate(_ validation: @escaping Validation) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validation - - -
    -

    Validation closure used to validate the response.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
    -                                                                 responseSerializer: Serializer,
    -                                                                 completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default

    -
    -
    - - responseSerializer - - -
    -

    The response serializer responsible for serializing the request, response, and data.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseData(queue: DispatchQueue = .main,
    -                         completionHandler: @escaping (AFDataResponse<Data>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseString(queue: DispatchQueue = .main,
    -                           encoding: String.Encoding? = nil,
    -                           completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - encoding - - -
    -

    The string encoding. Defaults to nil, in which case the encoding will be determined from - the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseJSON(queue: DispatchQueue = .main,
    -                         options: JSONSerialization.ReadingOptions = .allowFragments,
    -                         completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - options - - -
    -

    The JSON serialization reading options. .allowFragments by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
    -                                            queue: DispatchQueue = .main,
    -                                            decoder: DataDecoder = JSONDecoder(),
    -                                            completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - type - - -
    -

    Decodable type to decode from response data.

    -
    -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - decoder - - -
    -

    DataDecoder to use to decode the response. JSONDecoder() by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Validation - -
    -
    -
    -
    -
    -
    -

    A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the -request was valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(statusCode:) - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sequence, S.Element == Int
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - range - - -
    -

    The range of acceptable status codes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates that the response has a content type in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - contentType - - -
    -

    The acceptable content types, which may specify wildcard types and/or subtypes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the default acceptable range of 200…299, and that the content -type matches any specified in the Accept HTTP header field.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataResponseSerializer.html deleted file mode 100644 index d3e9ea9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DataResponseSerializer.html +++ /dev/null @@ -1,629 +0,0 @@ - - - - DataResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponseSerializer

-
-
-
public final class DataResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a -request returning nil or no data is considered an error. However, if the response is has a status code valid for -empty responses (204, 205), then an empty Data value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
    -            emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DecodableResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DecodableResponseSerializer.html deleted file mode 100644 index cecd9d9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DecodableResponseSerializer.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - DecodableResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DecodableResponseSerializer

-
-
-
public final class DecodableResponseSerializer<T> : ResponseSerializer where T : Decodable
- -
-
-

A ResponseSerializer that decodes the response data as a generic value using any type that conforms to -DataDecoder. By default, this is an instance of JSONDecoder. Additionally, a request returning nil or no data -is considered an error. However, if the response is has a status code valid for empty responses (204, 205), then -the Empty.value value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - decoder - -
    -
    -
    -
    -
    -
    -

    The DataDecoder instance used to decode responses.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let decoder: DataDecoder
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the values provided.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
    -            decoder: DataDecoder = JSONDecoder(),
    -            emptyResponseCodes: Set<Int> = DecodableResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - decoder - - -
    -

    The DataDecoder. JSONDecoder() by default.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DefaultTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DefaultTrustEvaluator.html deleted file mode 100644 index 2384515..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DefaultTrustEvaluator.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - DefaultTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DefaultTrustEvaluator

-
-
-
public final class DefaultTrustEvaluator : ServerTrustEvaluating
- -
-
-

An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -host provided by the challenge. Applications are encouraged to always validate the host in production environments -to guarantee the validity of the server’s certificate chain.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(validateHost:) - -
    -
    -
    -
    -
    -
    -

    Creates a DefaultTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host. true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DisabledEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DisabledEvaluator.html deleted file mode 100644 index 66f02a1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DisabledEvaluator.html +++ /dev/null @@ -1,506 +0,0 @@ - - - - DisabledEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DisabledEvaluator

-
-
-
public final class DisabledEvaluator : ServerTrustEvaluating
- -
-
-

Disables all evaluation which in turn will always consider any server trust as valid.

- -

THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest.html deleted file mode 100644 index 667fd36..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest.html +++ /dev/null @@ -1,1585 +0,0 @@ - - - - DownloadRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadRequest

-
-
-
public class DownloadRequest : Request
- -
-
-

Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - Options - -
    -
    -
    -
    -
    -
    -

    A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination -URL.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Options : OptionSet
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - Destination - -
    -
    -
    -
    -
    -
    -

    A closure executed once a download request has successfully completed in order to determine where to move the -temporary file written to during the download process. The closure takes two arguments: the temporary file URL -and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and -the options defining how the file should be moved.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Destination = (_ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a download file destination closure which uses the default file manager to move the temporary file to a -file URL in the first available directory with the specified search path directory and search path domain mask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
    -                                               in domain: FileManager.SearchPathDomainMask = .userDomainMask,
    -                                               options: Options = []) -> Destination
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - directory - - -
    -

    The search path directory. .documentDirectory by default.

    -
    -
    - - domain - - -
    -

    The search path domain mask. .userDomainMask by default.

    -
    -
    - - options - - -
    -

    DownloadRequest.Options used when moving the downloaded file to its destination. None by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The Destination closure.

    -
    -
    -
    -
  • -
  • -
    - - - - Downloadable - -
    -
    -
    -
    -
    -
    -

    Type describing the source used to create the underlying URLSessionDownloadTask.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Downloadable
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - resumeData - -
    -
    -
    -
    -
    -
    -

    If the download is resumable and eventually cancelled, this value may be used to resume the download using the -download(resumingWith data:) API.

    -
    -

    Note

    - For more information about resumeData, see Apple’s documentation. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var resumeData: Data? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileURL - -
    -
    -
    -
    -
    -
    -

    If the download is successful, the URL where the file was downloaded.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var fileURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - downloadable - -
    -
    -
    -
    -
    -
    -

    Downloadable value used for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let downloadable: Downloadable
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a URLSessionTask from the provided resume data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - data - - -
    -

    Data used to resume the download.

    -
    -
    - - session - - -
    -

    URLSession used to create the URLSessionTask.

    -
    -
    -
    -
    -

    Return Value

    -

    The URLSessionTask created.

    -
    -
    -
    -
  • -
  • -
    - - - - cancel() - -
    -
    -
    -
    -
    -
    -

    Cancels the instance. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

    -
    -

    Note

    -

    This method will NOT produce resume data. If you wish to cancel and produce resume data, use - cancel(producingResumeData:) or cancel(byProducingResumeData:).

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public override func cancel() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Cancels the instance, optionally producing resume data. Once cancelled, a DownloadRequest can no longer be -resumed or suspended.

    -
    -

    Note

    -

    If producingResumeData is true, the resumeData property will be populated with any resume data, if - available.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Cancels the instance while producing resume data. Once cancelled, a DownloadRequest can no longer be resumed -or suspended.

    -
    -

    Note

    -

    The resume data passed to the completion handler will also be available on the instance’s resumeData - property.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - completionHandler - - -
    -

    The completion handler that is called when the download has been successfully - cancelled. It is not guaranteed to be called on a particular queue, so you may - want use an appropriate queue to perform your work.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - validate(_:) - -
    -
    -
    -
    -
    -
    -

    Validates the request, using the specified closure.

    -
    -

    Note

    -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate(_ validation: @escaping Validation) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - validation - - -
    -

    Validation closure to validate the response.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response(queue: DispatchQueue = .main,
    -                     completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func response<T: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
    -                                                            responseSerializer: T,
    -                                                            completionHandler: @escaping (AFDownloadResponse<T.SerializedObject>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - responseSerializer - - -
    -

    The response serializer responsible for serializing the request, response, and data - contained in the destination URL.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseData(queue: DispatchQueue = .main,
    -                         completionHandler: @escaping (AFDownloadResponse<Data>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - completionHandler - - -
    -

    The code to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

String

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseString(queue: DispatchQueue = .main,
    -                           encoding: String.Encoding? = nil,
    -                           completionHandler: @escaping (AFDownloadResponse<String>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - encoding - - -
    -

    The string encoding. Defaults to nil, in which case the encoding will be determined from - the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- - - -

JSON

-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Adds a handler to be called once the request has finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func responseJSON(queue: DispatchQueue = .main,
    -                         options: JSONSerialization.ReadingOptions = .allowFragments,
    -                         completionHandler: @escaping (AFDownloadResponse<Any>) -> Void)
    -    -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - queue - - -
    -

    The queue on which the completion handler is dispatched. .main by default.

    -
    -
    - - options - - -
    -

    The JSON serialization reading options. .allowFragments by default.

    -
    -
    - - completionHandler - - -
    -

    A closure to be executed once the request has finished.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Validation - -
    -
    -
    -
    -
    -
    -

    A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a -destination URL, and returns whether the request was valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse, _ fileURL: URL?) -> ValidationResult
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate(statusCode:) - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S>(statusCode acceptableStatusCodes: S) -> Self where S : Sequence, S.Element == Int
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - range - - -
    -

    The range of acceptable status codes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates that the response has a content type in the specified sequence.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - contentType - - -
    -

    The acceptable content types, which may specify wildcard types and/or subtypes.

    -
    -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Validates that the response has a status code in the default acceptable range of 200…299, and that the content -type matches any specified in the Accept HTTP header field.

    - -

    If validation fails, subsequent calls to response handlers will have an associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func validate() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The request.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Downloadable.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Downloadable.html deleted file mode 100644 index 7e50954..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Downloadable.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - Downloadable Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Downloadable

-
-
-
public enum Downloadable
- -
-
-

Type describing the source used to create the underlying URLSessionDownloadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - request(_:) - -
    -
    -
    -
    -
    -
    -

    Download should be started from the URLRequest produced by the associated URLRequestConvertible value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case request(URLRequestConvertible)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumeData(_:) - -
    -
    -
    -
    -
    -
    -

    Download should be started from the associated resume Data value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case resumeData(Data)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Options.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Options.html deleted file mode 100644 index 8acc68e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/DownloadRequest/Options.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - Options Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Options

-
-
-
public struct Options : OptionSet
- -
-
-

A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination -URL.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Specifies that intermediate directories for the destination URL should be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let createIntermediateDirectories: DownloadRequest.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - removePreviousFile - -
    -
    -
    -
    -
    -
    -

    Specifies that any previous file at the destination URL should be removed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let removePreviousFile: DownloadRequest.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    -

    Returns the raw bitmask value of the option and satisfies the RawRepresentable protocol.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: Int
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: Int)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Interceptor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Interceptor.html deleted file mode 100644 index 3f3364c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Interceptor.html +++ /dev/null @@ -1,734 +0,0 @@ - - - - Interceptor Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Interceptor

-
-
-
open class Interceptor : RequestInterceptor
- -
-
-

RequestInterceptor which can use multiple RequestAdapter and RequestRetrier values.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONParameterEncoder.html deleted file mode 100644 index b1845a4..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONParameterEncoder.html +++ /dev/null @@ -1,635 +0,0 @@ - - - - JSONParameterEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONParameterEncoder

-
-
-
open class JSONParameterEncoder : ParameterEncoder
- -
-
-

A ParameterEncoder that encodes types as JSON body data.

- -

If no Content-Type header is already set on the provided URLRequests, it’s set to application/json.

- -
-
- -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with default parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - prettyPrinted - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with JSONEncoder.outputFormatting set to .prettyPrinted.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var prettyPrinted: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sortedKeys - -
    -
    -
    -
    -
    -
    -

    Returns an encoder with JSONEncoder.outputFormatting set to .sortedKeys.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
    -public static var sortedKeys: JSONParameterEncoder { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoder - -
    -
    -
    -
    -
    -
    -

    JSONEncoder used to encode parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let encoder: JSONEncoder
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(encoder:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance with the provided JSONEncoder.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(encoder: JSONEncoder = JSONEncoder())
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - encoder - - -
    -

    The JSONEncoder. JSONEncoder() by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:into:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func encode<Parameters: Encodable>(_ parameters: Parameters?,
    -                                        into request: URLRequest) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONResponseSerializer.html deleted file mode 100644 index 9747d00..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/JSONResponseSerializer.html +++ /dev/null @@ -1,669 +0,0 @@ - - - - JSONResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONResponseSerializer

-
-
-
public final class JSONResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning -nil or no data is considered an error. However, if the response is has a status code valid for empty responses -(204, 205), then an NSNull value is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    JSONSerialization.ReadingOptions used when serializing a response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let options: JSONSerialization.ReadingOptions
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance with the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
    -            emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
    -            options: JSONSerialization.ReadingOptions = .allowFragments)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    - - options - - -
    -

    The options to use. .allowFragments by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartFormData.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartFormData.html deleted file mode 100644 index 6c9e81d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartFormData.html +++ /dev/null @@ -1,1205 +0,0 @@ - - - - MultipartFormData Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartFormData

-
-
-
open class MultipartFormData
- -
-
-

Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode -multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.

- -

For more information on multipart/form-data in general, please refer to the RFC-2388 and RFC-2045 specs as well -and the w3 form documentation.

- - - -
-
- -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Default memory threshold used when encoding MultipartFormData, in bytes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let encodingMemoryThreshold: UInt64
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - contentType - -
    -
    -
    -
    -
    -
    -

    The Content-Type header value containing the boundary used to generate the multipart/form-data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open lazy var contentType: String { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - contentLength - -
    -
    -
    -
    -
    -
    -

    The content length of all body parts used to generate the multipart/form-data not including the boundaries.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var contentLength: UInt64 { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boundary - -
    -
    -
    -
    -
    -
    -

    The boundary used to separate the body parts in the encoded form data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boundary: String
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(fileManager: FileManager = .default, boundary: String? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - fileManager - - -
    -

    FileManager to use for file operations, if needed.

    -
    -
    - - boundary - - -
    -

    Boundary String used to separate body parts.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the data and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - data - - -
    -

    Data to encoding into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the Data in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the Data in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the data in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - append(_:withName:) - -
    -
    -
    -
    -
    -
    -

    Creates a body part from the file and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{generated filename} (HTTP Header)
    • -
    • Content-Type: #{generated mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary
    • -
    - -

    The filename in the Content-Disposition HTTP header is generated from the last path component of the -fileURL. The Content-Type HTTP header MIME type is generated by mapping the fileURL extension to the -system associated MIME type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ fileURL: URL, withName name: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - fileURL - - -
    -

    URL of the file whose content will be encoded into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the file and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded file data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - fileURL - - -
    -

    URL of the file whose content will be encoded into the instance.

    -
    -
    - - name - - -
    -

    Name to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the file content in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the file content in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part from the stream and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
    • -
    • Content-Type: #{mimeType} (HTTP Header)
    • -
    • Encoded stream data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ stream: InputStream,
    -                   withLength length: UInt64,
    -                   name: String,
    -                   fileName: String,
    -                   mimeType: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - stream - - -
    -

    InputStream to encode into the instance.

    -
    -
    - - length - - -
    -

    Length, in bytes, of the stream.

    -
    -
    - - name - - -
    -

    Name to associate with the stream content in the Content-Disposition HTTP header.

    -
    -
    - - fileName - - -
    -

    Filename to associate with the stream content in the Content-Disposition HTTP header.

    -
    -
    - - mimeType - - -
    -

    MIME type to associate with the stream content in the Content-Type HTTP header.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a body part with the stream, length, and headers and appends it to the instance.

    - -

    The body part data will be encoded using the following format:

    - -
      -
    • HTTP headers
    • -
    • Encoded stream data
    • -
    • Multipart form boundary

    • -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - stream - - -
    -

    InputStream to encode into the instance.

    -
    -
    - - length - - -
    -

    Length, in bytes, of the stream.

    -
    -
    - - headers - - -
    -

    HTTPHeaders for the body part.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode() - -
    -
    -
    -
    -
    -
    -

    Encodes all appended body parts into a single Data value.

    -
    -

    Note

    -

    This method will load all the appended body parts into memory all at the same time. This method should - only be used when the encoded data will have a small memory footprint. For large data cases, please use - the writeEncodedData(to:)) method.

    - -
    -
    -

    Throws

    -

    An AFError if encoding encounters an error.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode() throws -> Data
    - -
    -
    -
    -

    Return Value

    -

    The encoded Data, if encoding is successful.

    -
    -
    -
    -
  • -
  • -
    - - - - writeEncodedData(to:) - -
    -
    -
    -
    -
    -
    -

    Writes all appended body parts to the given file URL.

    - -

    This process is facilitated by reading and writing with input and output streams, respectively. Thus, -this approach is very memory efficient and should be used for large body part data.

    -
    -

    Throws

    - An AFError if encoding encounters an error. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func writeEncodedData(to fileURL: URL) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - fileURL - - -
    -

    File URL to which to write the form data.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartUpload.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartUpload.html deleted file mode 100644 index 3af213d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/MultipartUpload.html +++ /dev/null @@ -1,525 +0,0 @@ - - - - MultipartUpload Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartUpload

-
-
-
open class MultipartUpload
- -
-
-

Undocumented

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Default memory threshold used when encoding MultipartFormData, in bytes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let encodingMemoryThreshold: UInt64
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - createUploadable() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func createUploadable() throws -> UploadRequest.Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager.html deleted file mode 100644 index 95813dd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager.html +++ /dev/null @@ -1,917 +0,0 @@ - - - - NetworkReachabilityManager Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

NetworkReachabilityManager

-
-
-
open class NetworkReachabilityManager
- -
-
-

The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and -WiFi network interfaces.

- -

Reachability can be used to determine background information about why a network operation failed, or to retry -network requests when a connection is established. It should not be used to prevent a user from initiating a network -request, as it’s possible that an initial request may be required to establish reachability.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Defines the various states of network reachability.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum NetworkReachabilityStatus
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - Listener - -
    -
    -
    -
    -
    -
    -

    A closure executed when the network reachability status changes. The closure takes a single argument: the -network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Listener = (NetworkReachabilityStatus) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Default NetworkReachabilityManager for the zero address and a listenerQueue of .main.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let `default`: NetworkReachabilityManager?
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isReachable - -
    -
    -
    -
    -
    -
    -

    Whether the network is currently reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachable: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isReachableOnCellular - -
    -
    -
    -
    -
    -
    -

    Whether the network is currently reachable over the cellular interface.

    -
    -

    Note

    - Using this property to decide whether to make a high or low bandwidth request is not recommended. - Instead, set the allowsCellularAccess on any URLRequests being issued. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachableOnCellular: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Whether the network is currently reachable over Ethernet or WiFi interface.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var isReachableOnEthernetOrWiFi: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - reachabilityQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue on which reachability will update.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let reachabilityQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - flags - -
    -
    -
    -
    -
    -
    -

    Flags of the current reachability type, if any.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var flags: SCNetworkReachabilityFlags? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - status - -
    -
    -
    -
    -
    -
    -

    The current network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open var status: NetworkReachabilityStatus { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(host:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance with the specified host.

    -
    -

    Note

    -

    The host value must not contain a scheme, just the hostname.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init?(host: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    Host used to evaluate network reachability. Must not include the scheme (e.g. https).

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an instance that monitors the address 0.0.0.0.

    - -

    Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing -status of the device, both IPv4 and IPv6.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init?()
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Starts listening for changes in network reachability status.

    -
    -

    Note

    -

    Stops and removes any existing listener.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -open func startListening(onQueue queue: DispatchQueue = .main,
    -                         onUpdatePerforming listener: @escaping Listener) -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    DispatchQueue on which to call the listener closure. .main by default.

    -
    -
    - - listener - - -
    -

    Listener closure called when reachability changes.

    -
    -
    -
    -
    -

    Return Value

    -

    true if listening was started successfully, false otherwise.

    -
    -
    -
    -
  • -
  • -
    - - - - stopListening() - -
    -
    -
    -
    -
    -
    -

    Stops listening for changes in network reachability status.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func stopListening()
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/ConnectionType.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/ConnectionType.html deleted file mode 100644 index 7c985da..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/ConnectionType.html +++ /dev/null @@ -1,490 +0,0 @@ - - - - ConnectionType Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionType

-
-
-
public enum ConnectionType
- -
-
-

Defines the various connection types detected by reachability flags.

- -
-
- -
-
-
-
    -
  • -
    - - - - ethernetOrWiFi - -
    -
    -
    -
    -
    -
    -

    The connection type is either over Ethernet or WiFi.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case ethernetOrWiFi
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - wwan - -
    -
    -
    -
    -
    -
    -

    The connection type is a WWAN connection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case wwan
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html deleted file mode 100644 index e266c59..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html +++ /dev/null @@ -1,560 +0,0 @@ - - - - NetworkReachabilityStatus Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

NetworkReachabilityStatus

-
-
-
public enum NetworkReachabilityStatus
- -
-
-

Defines the various states of network reachability.

- -
-
- -
-
-
-
    -
  • -
    - - - - unknown - -
    -
    -
    -
    -
    -
    -

    It is unknown whether the network is reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unknown
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - notReachable - -
    -
    -
    -
    -
    -
    -

    The network is not reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case notReachable
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - reachable(_:) - -
    -
    -
    -
    -
    -
    -

    The network is reachable on the associated ConnectionType.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case reachable(ConnectionType)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ConnectionType - -
    -
    -
    -
    -
    -
    -

    Defines the various connection types detected by reachability flags.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ConnectionType
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html deleted file mode 100644 index 60e2a93..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ConnectionType Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ConnectionType

-
-
-
public enum ConnectionType
- -
-
-

Defines the various connection types detected by reachability flags.

- -
-
- -
-
-
-
    -
  • -
    - - - - ethernetOrWiFi - -
    -
    -
    -
    -
    -
    -

    The connection type is either over Ethernet or WiFi.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case ethernetOrWiFi
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cellular - -
    -
    -
    -
    -
    -
    -

    The connection type is a cellular connection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cellular
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PinnedCertificatesTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PinnedCertificatesTrustEvaluator.html deleted file mode 100644 index 3b2ce6f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PinnedCertificatesTrustEvaluator.html +++ /dev/null @@ -1,572 +0,0 @@ - - - - PinnedCertificatesTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PinnedCertificatesTrustEvaluator

-
-
-
public final class PinnedCertificatesTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -certificates match one of the server certificates. By validating both the certificate chain and host, certificate -pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Creates a PinnedCertificatesTrustEvaluator.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
    -            acceptSelfSignedCertificates: Bool = false,
    -            performDefaultValidation: Bool = true,
    -            validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - certificates - - -
    -

    The certificates to use to evaluate the trust. All cer, crt, and der - certificates in Bundle.main by default.

    -
    -
    - - acceptSelfSignedCertificates - - -
    -

    Adds the provided certificates as anchors for the trust evaluation, allowing - self-signed certificates to pass. false by default. THIS SETTING SHOULD BE - FALSE IN PRODUCTION!

    -
    -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition - to performing the default evaluation, even if performDefaultValidation is - false. true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PublicKeysTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PublicKeysTrustEvaluator.html deleted file mode 100644 index a163875..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/PublicKeysTrustEvaluator.html +++ /dev/null @@ -1,563 +0,0 @@ - - - - PublicKeysTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PublicKeysTrustEvaluator

-
-
-
public final class PublicKeysTrustEvaluator : ServerTrustEvaluating
- -
-
-

Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -public keys match one of the server certificate public keys. By validating both the certificate chain and host, -public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -Applications are encouraged to always validate the host and require a valid certificate chain in production -environments.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Creates a PublicKeysTrustEvaluator.

    -
    -

    Note

    -

    Default and host validation will fail when using this evaluator with self-signed certificates. Use - PinnedCertificatesTrustEvaluator if you need to use self-signed certificates.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(keys: [SecKey] = Bundle.main.af.publicKeys,
    -            performDefaultValidation: Bool = true,
    -            validateHost: Bool = true)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - keys - - -
    -

    The SecKeys to use to validate public keys. Defaults to the public keys of all - certificates included in the main bundle.

    -
    -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition to - performing the default evaluation, even if performDefaultValidation is false. - true by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request.html deleted file mode 100644 index 06988a3..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request.html +++ /dev/null @@ -1,2516 +0,0 @@ - - - - Request Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Request

-
-
-
public class Request
- -
-
-

Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback -handling.

- -
-
- -
-
-
- -
-
- -
    -
  • -
    - - - - id - -
    -
    -
    -
    -
    -
    -

    UUID providing a unique identifier for the Request, used in the Hashable and Equatable conformances.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let id: UUID
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - underlyingQueue - -
    -
    -
    -
    -
    -
    -

    The serial queue for all internal async actions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let underlyingQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationQueue - -
    -
    -
    -
    -
    -
    -

    The queue used for all serialization actions. By default it’s a serial queue that targets underlyingQueue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - eventMonitor - -
    -
    -
    -
    -
    -
    -

    EventMonitor used for event callbacks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let eventMonitor: EventMonitor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - interceptor - -
    -
    -
    -
    -
    -
    -

    The Request‘s interceptor.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let interceptor: RequestInterceptor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delegate - -
    -
    -
    -
    -
    -
    -

    The Request‘s delegate.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public private(set) weak var delegate: RequestDelegate?
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - state - -
    -
    -
    -
    -
    -
    -

    State of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var state: State { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isInitialized - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .initialized.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isInitialized: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isResumed - -
    -
    -
    -
    -
    -
    -

    Returns whether state is.resumed`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResumed: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSuspended - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .suspended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSuspended: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isCancelled - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .cancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCancelled: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isFinished - -
    -
    -
    -
    -
    -
    -

    Returns whether state is .finished.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isFinished: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ProgressHandler - -
    -
    -
    -
    -
    -
    -

    Closure type executed when monitoring the upload or download progress of a request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias ProgressHandler = (Progress) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - uploadProgress - -
    -
    -
    -
    -
    -
    -

    Progress of the upload of the body of the executed URLRequest. Reset to 0 if the Request is retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let uploadProgress: Progress
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - downloadProgress - -
    -
    -
    -
    -
    -
    -

    Progress of the download of any response data. Reset to 0 if the Request is retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let downloadProgress: Progress
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- - -
-
- -
    -
  • -
    - - - - credential - -
    -
    -
    -
    -
    -
    -

    URLCredential used for authentication challenges. Created by calling one of the authenticate methods.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public private(set) var credential: URLCredential? { get set }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - requests - -
    -
    -
    -
    -
    -
    -

    All URLRequests created on behalf of the Request, including original and adapted requests.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var requests: [URLRequest] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstRequest - -
    -
    -
    -
    -
    -
    -

    First URLRequest created on behalf of the Request. May not be the first one actually executed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastRequest - -
    -
    -
    -
    -
    -
    -

    Last URLRequest created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    Current URLRequest created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var request: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - performedRequests - -
    -
    -
    -
    -
    -
    -

    URLRequests from all of the URLSessionTasks executed on behalf of the Request. May be different from -requests due to URLSession manipulation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var performedRequests: [URLRequest] { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    HTTPURLResponse received from the server, if any. If the Request was retried, this is the response of the -last URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var response: HTTPURLResponse? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Tasks

-
-
-
    -
  • -
    - - - - tasks - -
    -
    -
    -
    -
    -
    -

    All URLSessionTasks created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var tasks: [URLSessionTask] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstTask - -
    -
    -
    -
    -
    -
    -

    First URLSessionTask created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstTask: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastTask - -
    -
    -
    -
    -
    -
    -

    Last URLSessionTask crated on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastTask: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - task - -
    -
    -
    -
    -
    -
    -

    Current URLSessionTask created on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var task: URLSessionTask? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - allMetrics - -
    -
    -
    -
    -
    -
    -

    All URLSessionTaskMetrics gathered on behalf of the Request. Should correspond to the tasks created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var allMetrics: [URLSessionTaskMetrics] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - firstMetrics - -
    -
    -
    -
    -
    -
    -

    First URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var firstMetrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lastMetrics - -
    -
    -
    -
    -
    -
    -

    Last URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var lastMetrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    Current URLSessionTaskMetrics gathered on behalf of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var metrics: URLSessionTaskMetrics? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - retryCount - -
    -
    -
    -
    -
    -
    -

    Number of times the Request has been retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var retryCount: Int { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Error

-
-
-
    -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Error returned from Alamofire internally, from the network request directly, or any validators executed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public fileprivate(set) var error: AFError? { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

State

-
-
-
    -
  • -
    - - - - cancel() - -
    -
    -
    -
    -
    -
    -

    Cancels the instance. Once cancelled, a Request can no longer be resumed or suspended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cancel() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - suspend() - -
    -
    -
    -
    -
    -
    -

    Suspends the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func suspend() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - resume() - -
    -
    -
    -
    -
    -
    -

    Resumes the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func resume() -> Self
    - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Associates a credential using the provided values with the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - username - - -
    -

    The username.

    -
    -
    - - password - - -
    -

    The password.

    -
    -
    - - persistence - - -
    -

    The URLCredential.Persistence for the created URLCredential. .forSession by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • -
    - - - - authenticate(with:) - -
    -
    -
    -
    -
    -
    -

    Associates the provided credential with the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func authenticate(with credential: URLCredential) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - credential - - -
    -

    The URLCredential.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.

    -
    -

    Note

    -

    Only the last closure provided is used.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The DispatchQueue to execute the closure on. .main by default.

    -
    -
    - - closure - - -
    -

    The closure to be executed periodically as data is read from the server.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.

    -
    -

    Note

    -

    Only the last closure provided is used.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    The DispatchQueue to execute the closure on. .main by default.

    -
    -
    - - closure - - -
    -

    The closure to be executed periodically as data is sent to the server.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - redirect(using:) - -
    -
    -
    -
    -
    -
    -

    Sets the redirect handler for the instance which will be used if a redirect response is encountered.

    -
    -

    Note

    -

    Attempting to set the redirect handler more than once is a logic error and will crash.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func redirect(using handler: RedirectHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - -
    -

    The RedirectHandler.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - cacheResponse(using:) - -
    -
    -
    -
    -
    -
    -

    Sets the cached response handler for the Request which will be used when attempting to cache a response.

    -
    -

    Note

    -

    Attempting to set the cache handler more than once is a logic error and will crash.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cacheResponse(using handler: CachedResponseHandler) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - - -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a handler to be called when the cURL description of the request is available.

    -
    -

    Note

    -

    When waiting for a Request‘s URLRequest to be created, only the last handler will be called.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - handler - - -
    -

    Closure to be called when the cURL description is available.

    -
    -
    -
    -
    -

    Return Value

    -

    The instance.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - didResumeNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is resumed. The Notification contains the resumed Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didResumeNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a Request is suspended. The Notification contains the suspended Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didSuspendNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didCancelNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is cancelled. The Notification contains the cancelled Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCancelNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didFinishNotification - -
    -
    -
    -
    -
    -
    -

    Posted when a Request is finished. The Notification contains the completed Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didFinishNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is resumed. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didResumeTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is suspended. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didSuspendTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is cancelled. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCancelTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Posted when a URLSessionTask is completed. The Notification contains the Request associated with the URLSessionTask.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let didCompleteTaskNotification: Notification.Name
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ==(_:_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func == (lhs: Request, rhs: Request) -> Bool
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - hash(into:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func hash(into hasher: inout Hasher)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    A textual representation of this instance, including the HTTPMethod and URL if the URLRequest has been -created, as well as the response status code, if a response has been received.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - cURLDescription() - -
    -
    -
    -
    -
    -
    -

    cURL representation of the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cURLDescription() -> String
    - -
    -
    -
    -

    Return Value

    -

    The cURL equivalent of the instance.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - ValidationResult - -
    -
    -
    -
    -
    -
    -

    Used to represent whether a validation succeeded or failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias ValidationResult = Result<Void, Error>
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request/State.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request/State.html deleted file mode 100644 index 4c19fef..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Request/State.html +++ /dev/null @@ -1,592 +0,0 @@ - - - - State Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

State

-
-
-
public enum State
- -
-
-

State of the Request, with managed transitions between states set when calling resume(), suspend(), or -cancel() on the Request.

- -
-
- -
-
-
-
    -
  • -
    - - - - initialized - -
    -
    -
    -
    -
    -
    -

    Initial state of the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case initialized
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumed - -
    -
    -
    -
    -
    -
    -

    State set when resume() is called. Any tasks created for the Request will have resume() called on -them in this state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case resumed
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - suspended - -
    -
    -
    -
    -
    -
    -

    State set when suspend() is called. Any tasks created for the Request will have suspend() called on -them in this state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case suspended
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cancelled - -
    -
    -
    -
    -
    -
    -

    State set when cancel() is called. Any tasks created for the Request will have cancel() called on -them. Unlike resumed or suspended, once in the cancelled state, the Request can no longer transition -to any other state.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cancelled
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - finished - -
    -
    -
    -
    -
    -
    -

    State set when all response serialization completion closures have been cleared on the Request and -enqueued on their respective queues.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case finished
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Retrier.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Retrier.html deleted file mode 100644 index fb14705..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Retrier.html +++ /dev/null @@ -1,526 +0,0 @@ - - - - Retrier Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Retrier

-
-
-
open class Retrier : RequestInterceptor
- -
-
-

Closure-based RequestRetrier.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ retryHandler: @escaping RetryHandler)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - retryHandler - - -
    -

    RetryHandler closure to be executed when handling request retry.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func retry(_ request: Request,
    -                for session: Session,
    -                dueTo error: Error,
    -                completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RetryPolicy.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RetryPolicy.html deleted file mode 100644 index 7515cb8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RetryPolicy.html +++ /dev/null @@ -1,921 +0,0 @@ - - - - RetryPolicy Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RetryPolicy

-
-
-
open class RetryPolicy : RequestInterceptor
- -
-
-

A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -as well as certain types of networking errors.

- -
-
- -
-
-
-
    -
  • -
    - - - - defaultRetryLimit - -
    -
    -
    -
    -
    -
    -

    The default retry limit for retry policies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryLimit: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default exponential backoff base for retry policies (must be a minimum of 2).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultExponentialBackoffBase: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default exponential backoff scale for retry policies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultExponentialBackoffScale: Double
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default HTTP methods to retry. -See RFC 2616 - Section 9.1.2 for more information.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableHTTPMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default HTTP status codes to retry. -See RFC 2616 - Section 10 for more information.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableHTTPStatusCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The default URL error codes to retry.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultRetryableURLErrorCodes: Set<URLError.Code>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryLimit - -
    -
    -
    -
    -
    -
    -

    The total number of times the request is allowed to be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryLimit: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The base of the exponential backoff policy (should always be greater than or equal to 2).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let exponentialBackoffBase: UInt
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The scale of the exponential backoff.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let exponentialBackoffScale: Double
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryableHTTPMethods - -
    -
    -
    -
    -
    -
    -

    The HTTP methods that are allowed to be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableHTTPMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The HTTP status codes that are automatically retried by the policy.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableHTTPStatusCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The URL error codes that are automatically retried by the policy.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let retryableURLErrorCodes: Set<URLError.Code>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an ExponentialBackoffRetryPolicy from the specified parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
    -            exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
    -            exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
    -            retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
    -            retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
    -            retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - retryLimit - - -
    -

    The total number of times the request is allowed to be retried. 2 by default.

    -
    -
    - - exponentialBackoffBase - - -
    -

    The base of the exponential backoff policy. 2 by default.

    -
    -
    - - exponentialBackoffScale - - -
    -

    The scale of the exponential backoff. 0.5 by default.

    -
    -
    - - retryableHTTPMethods - - -
    -

    The HTTP methods that are allowed to be retried. - RetryPolicy.defaultRetryableHTTPMethods by default.

    -
    -
    - - retryableHTTPStatusCodes - - -
    -

    The HTTP status codes that are automatically retried by the policy. - RetryPolicy.defaultRetryableHTTPStatusCodes by default.

    -
    -
    - - retryableURLErrorCodes - - -
    -

    The URL error codes that are automatically retried by the policy. - RetryPolicy.defaultRetryableURLErrorCodes by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func retry(_ request: Request,
    -                for session: Session,
    -                dueTo error: Error,
    -                completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator.html deleted file mode 100644 index af7f782..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator.html +++ /dev/null @@ -1,590 +0,0 @@ - - - - RevocationTrustEvaluator Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RevocationTrustEvaluator

-
-
-
public final class RevocationTrustEvaluator : ServerTrustEvaluating
- -
-
-

An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -environments to guarantee the validity of the server’s certificate chain.

- -
-
- -
-
-
-
    -
  • -
    - - - - Options - -
    -
    -
    -
    -
    -
    -

    Represents the options to be use when evaluating the status of a certificate. -Only Revocation Policy Constants are valid, and can be found in Apple’s documentation.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Options : OptionSet
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a RevocationTrustEvaluator.

    -
    -

    Note

    -

    Default and host validation will fail when using this evaluator with self-signed certificates. Use - PinnedCertificatesTrustEvaluator if you need to use self-signed certificates.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - performDefaultValidation - - -
    -

    Determines whether default validation should be performed in addition to - evaluating the pinned certificates. true by default.

    -
    -
    - - validateHost - - -
    -

    Determines whether or not the evaluator should validate the host, in addition - to performing the default evaluation, even if performDefaultValidation is - false. true by default.

    -
    -
    - - options - - -
    -

    The Options to use to check the revocation status of the certificate. .any - by default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator/Options.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator/Options.html deleted file mode 100644 index 9dec048..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/RevocationTrustEvaluator/Options.html +++ /dev/null @@ -1,689 +0,0 @@ - - - - Options Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Options

-
-
-
public struct Options : OptionSet
- -
-
-

Represents the options to be use when evaluating the status of a certificate. -Only Revocation Policy Constants are valid, and can be found in Apple’s documentation.

- -
-
- -
-
-
-
    -
  • -
    - - - - crl - -
    -
    -
    -
    -
    -
    -

    Perform revocation checking using the CRL (Certification Revocation List) method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let crl: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - networkAccessDisabled - -
    -
    -
    -
    -
    -
    -

    Consult only locally cached replies; do not use network access.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let networkAccessDisabled: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ocsp - -
    -
    -
    -
    -
    -
    -

    Perform revocation checking using OCSP (Online Certificate Status Protocol).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let ocsp: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preferCRL - -
    -
    -
    -
    -
    -
    -

    Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let preferCRL: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a -best attempt basis, where failure to reach the server is not considered fatal.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let requirePositiveResponse: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - any - -
    -
    -
    -
    -
    -
    -

    Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the -certificate and the value of preferCRL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let any: RevocationTrustEvaluator.Options
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    -

    The raw value of the option.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: CFOptionFlags
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    -

    Creates an Options value with the given CFOptionFlags.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: CFOptionFlags)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - rawValue - - -
    -

    The CFOptionFlags value to initialize with.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ServerTrustManager.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ServerTrustManager.html deleted file mode 100644 index e3db39b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/ServerTrustManager.html +++ /dev/null @@ -1,628 +0,0 @@ - - - - ServerTrustManager Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustManager

-
-
-
open class ServerTrustManager
- -
-
-

Responsible for managing the mapping of ServerTrustEvaluating values to given hosts.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether all hosts for this ServerTrustManager must be evaluated. true by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let allHostsMustBeEvaluated: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - evaluators - -
    -
    -
    -
    -
    -
    -

    The dictionary of policies mapped to a particular host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let evaluators: [String : ServerTrustEvaluating]
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Initializes the ServerTrustManager instance with the given evaluators.

    - -

    Since different servers and web services can have different leaf certificates, intermediate and even root -certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This -allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key -pinning for host3 and disabling evaluation for host4.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String : ServerTrustEvaluating])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - allHostsMustBeEvaluated - - -
    -

    The value determining whether all hosts for this instance must be evaluated. true - by default.

    -
    -
    - - evaluators - - -
    -

    A dictionary of evaluators mapped to hosts.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns the ServerTrustEvaluating value for the given host, if one is set.

    - -

    By default, this method will return the policy that perfectly matches the given host. Subclasses could override -this method and implement more complex mapping implementations such as wildcards.

    -
    -

    Throws

    -

    AFError.serverTrustEvaluationFailed if allHostsMustBeEvaluated is true and no matching - evaluators are found.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The host to use when searching for a matching policy.

    -
    -
    -
    -
    -

    Return Value

    -

    The ServerTrustEvaluating value for the given host if found, nil otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Session.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Session.html deleted file mode 100644 index 4604000..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/Session.html +++ /dev/null @@ -1,3365 +0,0 @@ - - - - Session Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Session

-
-
-
open class Session
- -
-
-

Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common -functionality for all Requests, including queuing, interception, trust management, redirect handling, and response -cache handling.

- -
-
- -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Shared singleton instance used by all AF.request APIs. Cannot be modified.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let `default`: Session
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - session - -
    -
    -
    -
    -
    -
    -

    Underlying URLSession used to create URLSessionTasks for this instance, and for which this instance’s -delegate handles URLSessionDelegate callbacks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let session: URLSession
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delegate - -
    -
    -
    -
    -
    -
    -

    Instance’s SessionDelegate, which handles the URLSessionDelegate methods and Request interaction.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let delegate: SessionDelegate
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rootQueue - -
    -
    -
    -
    -
    -
    -

    Root DispatchQueue for all internal callbacks and state update. MUST be a serial queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rootQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Value determining whether this instance automatically calls resume() on all created Requests.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let startRequestsImmediately: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue on which URLRequests are created asynchronously. By default this queue uses rootQueue as its -target, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile -and test before introducing an additional queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let requestQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationQueue - -
    -
    -
    -
    -
    -
    -

    DispatchQueue passed to all Requests on which they perform their response serialization. By default this -queue uses rootQueue as its target but a separate queue can be used if response serialization is determined -to be a bottleneck. Always profile and test before introducing an additional queue.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationQueue: DispatchQueue
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - interceptor - -
    -
    -
    -
    -
    -
    -

    RequestInterceptor used for all Request created by the instance. RequestInterceptors can also be set on a -per-Request basis, in which case the Request‘s interceptor takes precedence over this value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let interceptor: RequestInterceptor?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serverTrustManager - -
    -
    -
    -
    -
    -
    -

    ServerTrustManager instance used to evaluate all trust challenges and provide certificate and key pinning.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serverTrustManager: ServerTrustManager?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - redirectHandler - -
    -
    -
    -
    -
    -
    -

    RedirectHandler instance used to provide customization for request redirection.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let redirectHandler: RedirectHandler?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    CachedResponseHandler instance used to provide customization of cached response handling.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let cachedResponseHandler: CachedResponseHandler?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - eventMonitor - -
    -
    -
    -
    -
    -
    -

    CompositeEventMonitor used to compose Alamofire’s defaultEventMonitors and any passed EventMonitors.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let eventMonitor: CompositeEventMonitor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEventMonitors - -
    -
    -
    -
    -
    -
    -

    EventMonitors included in all instances. [AlamofireNotifications()] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let defaultEventMonitors: [EventMonitor]
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a Session from a URLSession and other parameters.

    -
    -

    Note

    -

    When passing a URLSession, you must create the URLSession with a specific delegateQueue value and - pass the delegateQueue‘s underlyingQueue as the rootQueue parameter of this initializer.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(session: URLSession,
    -            delegate: SessionDelegate,
    -            rootQueue: DispatchQueue,
    -            startRequestsImmediately: Bool = true,
    -            requestQueue: DispatchQueue? = nil,
    -            serializationQueue: DispatchQueue? = nil,
    -            interceptor: RequestInterceptor? = nil,
    -            serverTrustManager: ServerTrustManager? = nil,
    -            redirectHandler: RedirectHandler? = nil,
    -            cachedResponseHandler: CachedResponseHandler? = nil,
    -            eventMonitors: [EventMonitor] = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - session - - -
    -

    Underlying URLSession for this instance.

    -
    -
    - - delegate - - -
    -

    SessionDelegate that handles session‘s delegate callbacks as well as Request - interaction.

    -
    -
    - - rootQueue - - -
    -

    Root DispatchQueue for all internal callbacks and state updates. MUST be a - serial queue.

    -
    -
    - - startRequestsImmediately - - -
    -

    Determines whether this instance will automatically start all Requests. true - by default. If set to false, all Requests created must have .resume() called. - on them for them to start.

    -
    -
    - - requestQueue - - -
    -

    DispatchQueue on which to perform URLRequest creation. By default this queue - will use the rootQueue as its target. A separate queue can be used if it’s - determined request creation is a bottleneck, but that should only be done after - careful testing and profiling. nil by default.

    -
    -
    - - serializationQueue - - -
    -

    DispatchQueue on which to perform all response serialization. By default this - queue will use the rootQueue as its target. A separate queue can be used if - it’s determined response serialization is a bottleneck, but that should only be - done after careful testing and profiling. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor to be used for all Requests created by this instance. nil - by default.

    -
    -
    - - serverTrustManager - - -
    -

    ServerTrustManager to be used for all trust evaluations by this instance. nil - by default.

    -
    -
    - - redirectHandler - - -
    -

    RedirectHandler to be used by all Requests created by this instance. nil by - default.

    -
    -
    - - cachedResponseHandler - - -
    -

    CachedResponseHandler to be used by all Requests created by this instance. - nil by default.

    -
    -
    - - eventMonitors - - -
    -

    Additional EventMonitors used by the instance. Alamofire always adds a - AlamofireNotifications EventMonitor to the array passed here. [] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a Session from a URLSessionConfiguration.

    -
    -

    Note

    -

    This initializer lets Alamofire handle the creation of the underlying URLSession and its - delegateQueue, and is the recommended initializer for most uses.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
    -                        delegate: SessionDelegate = SessionDelegate(),
    -                        rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
    -                        startRequestsImmediately: Bool = true,
    -                        requestQueue: DispatchQueue? = nil,
    -                        serializationQueue: DispatchQueue? = nil,
    -                        interceptor: RequestInterceptor? = nil,
    -                        serverTrustManager: ServerTrustManager? = nil,
    -                        redirectHandler: RedirectHandler? = nil,
    -                        cachedResponseHandler: CachedResponseHandler? = nil,
    -                        eventMonitors: [EventMonitor] = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - configuration - - -
    -

    URLSessionConfiguration to be used to create the underlying URLSession. Changes - to this value after being passed to this initializer will have no effect. - URLSessionConfiguration.af.default by default.

    -
    -
    - - delegate - - -
    -

    SessionDelegate that handles session‘s delegate callbacks as well as Request - interaction. SessionDelegate() by default.

    -
    -
    - - rootQueue - - -
    -

    Root DispatchQueue for all internal callbacks and state updates. MUST be a - serial queue. DispatchQueue(label: "org.alamofire.session.rootQueue") by default.

    -
    -
    - - startRequestsImmediately - - -
    -

    Determines whether this instance will automatically start all Requests. true - by default. If set to false, all Requests created must have .resume() called. - on them for them to start.

    -
    -
    - - requestQueue - - -
    -

    DispatchQueue on which to perform URLRequest creation. By default this queue - will use the rootQueue as its target. A separate queue can be used if it’s - determined request creation is a bottleneck, but that should only be done after - careful testing and profiling. nil by default.

    -
    -
    - - serializationQueue - - -
    -

    DispatchQueue on which to perform all response serialization. By default this - queue will use the rootQueue as its target. A separate queue can be used if - it’s determined response serialization is a bottleneck, but that should only be - done after careful testing and profiling. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor to be used for all Requests created by this instance. nil - by default.

    -
    -
    - - serverTrustManager - - -
    -

    ServerTrustManager to be used for all trust evaluations by this instance. nil - by default.

    -
    -
    - - redirectHandler - - -
    -

    RedirectHandler to be used by all Requests created by this instance. nil by - default.

    -
    -
    - - cachedResponseHandler - - -
    -

    CachedResponseHandler to be used by all Requests created by this instance. - nil by default.

    -
    -
    - - eventMonitors - - -
    -

    Additional EventMonitors used by the instance. Alamofire always adds a - AlamofireNotifications EventMonitor to the array passed here. [] by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Cancel all active Requests, optionally calling a completion handler when complete.

    -
    -

    Note

    -

    This is an asynchronous operation and does not block the creation of future Requests. Cancelled - Requests may not cancel immediately due internal work, and may not cancel at all if they are close to - completion when cancelled.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - queue - - -
    -

    DispatchQueue on which the completion handler is run. .main by default.

    -
    -
    - - completion - - -
    -

    Closure to be called when all Requests have been cancelled.

    -
    -
    -
    -
    -
    -
  • -
-
-
- - -
-
- - -
-
-
- - - -

Data

-
-
- -
-
-
- - - -

File

-
-
- -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the multipart form data built using a closure and sent using the provided -URLRequest components and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                 to url: URLConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 method: HTTPMethod = .post,
    -                 headers: HTTPHeaders? = nil,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - convertible - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible -value, and a RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                 with request: URLRequestConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components -and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: MultipartFormData,
    -                 to url: URLConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 method: HTTPMethod = .post,
    -                 headers: HTTPHeaders? = nil,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - url - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible -value and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func upload(multipartFormData: MultipartFormData,
    -                 with request: URLRequestConvertible,
    -                 usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                 interceptor: RequestInterceptor? = nil,
    -                 fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager instance to be used by the returned UploadRequest. .default instance by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - sessionConfiguration - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var sessionConfiguration: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - startImmediately - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var startImmediately: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup(after:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func cleanup(after request: Request)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/SessionDelegate.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/SessionDelegate.html deleted file mode 100644 index 28b2285..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/SessionDelegate.html +++ /dev/null @@ -1,916 +0,0 @@ - - - - SessionDelegate Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SessionDelegate

-
-
-
open class SessionDelegate : NSObject
- -
-
-

Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

- -
-
- -
-
-
-
    -
  • -
    - - - - init(fileManager:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from the given FileManager.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(fileManager: FileManager = .default)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - fileManager - - -
    -

    FileManager to use for underlying file management, such as moving downloaded files. - .default by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     didReceive challenge: URLAuthenticationChallenge,
    -                     completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     didSendBodyData bytesSent: Int64,
    -                     totalBytesSent: Int64,
    -                     totalBytesExpectedToSend: Int64)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     task: URLSessionTask,
    -                     willPerformHTTPRedirection response: HTTPURLResponse,
    -                     newRequest request: URLRequest,
    -                     completionHandler: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    open func urlSession(_ session: URLSession,
    -                     dataTask: URLSessionDataTask,
    -                     willCacheResponse proposedResponse: CachedURLResponse,
    -                     completionHandler: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/StringResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/StringResponseSerializer.html deleted file mode 100644 index a4a4658..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/StringResponseSerializer.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - StringResponseSerializer Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

StringResponseSerializer

-
-
-
public final class StringResponseSerializer : ResponseSerializer
- -
-
-

A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no -data is considered an error. However, if the response is has a status code valid for empty responses (204, 205), -then an empty String is returned.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataPreprocessor: DataPreprocessor
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoding - -
    -
    -
    -
    -
    -
    -

    Optional string encoding used to validate the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let encoding: String.Encoding?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyResponseCodes: Set<Int>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let emptyRequestMethods: Set<HTTPMethod>
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance with the provided values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
    -            encoding: String.Encoding? = nil,
    -            emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
    -            emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - dataPreprocessor - - -
    -

    DataPreprocessor used to prepare the received Data for serialization.

    -
    -
    - - encoding - - -
    -

    A string encoding. Defaults to nil, in which case the encoding will be determined - from the server response, falling back to the default HTTP character set, ISO-8859-1.

    -
    -
    - - emptyResponseCodes - - -
    -

    The HTTP response codes for which empty responses are allowed. [204, 205] by default.

    -
    -
    - - emptyRequestMethods - - -
    -

    The HTTP request methods for which empty responses are allowed. [.head] by default.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder.html deleted file mode 100644 index a7103f1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder.html +++ /dev/null @@ -1,1138 +0,0 @@ - - - - URLEncodedFormEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncodedFormEncoder

-
-
-
public final class URLEncodedFormEncoder
- -
-
-

An object that encodes instances into URL-encoded query strings.

- -

There is no published specification for how to encode collection types. By default, the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

- -

BoolEncoding can be used to configure how Bool values are encoded. The default behavior is to encode -true as 1 and false as 0.

- -

DateEncoding can be used to configure how Date values are encoded. By default, the .deferredToDate -strategy is used, which formats dates from their structure.

- -

SpaceEncoding can be used to configure how spaces are encoded. Modern encodings use percent replacement (%20), -while older encodings may expect spaces to be replaced with +.

- -

This type is largely based on Vapor’s url-encoded-form project.

- -
-
- -
-
-
-
    -
  • -
    - - - - ArrayEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Array values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - BoolEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Bool values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum BoolEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DataEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Data values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum DataEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DateEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for Date values.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum DateEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - KeyEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for keys.

    - -

    This type is derived from JSONEncoder‘s KeyEncodingStrategy -and XMLEncoders KeyEncodingStrategy.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum KeyEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - SpaceEncoding - -
    -
    -
    -
    -
    -
    -

    Encoding to use for spaces.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum SpaceEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - Error - -
    -
    -
    -
    -
    - -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Error : Swift.Error
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Whether or not to sort the encoded key value pairs.

    -
    -

    Note

    - This setting ensures a consistent ordering for all encodings of the same parameters. When set to false, - encoded Dictionary values may have a different encoded order each time they’re encoded due to - Dictionary‘s random storage order, but Encodable types will maintain their encoded order. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let alphabetizeKeyValuePairs: Bool
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - arrayEncoding - -
    -
    -
    -
    -
    -
    -

    The ArrayEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let arrayEncoding: ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boolEncoding - -
    -
    -
    -
    -
    -
    -

    The BoolEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boolEncoding: BoolEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - dataEncoding - -
    -
    -
    -
    -
    -
    -

    THe DataEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dataEncoding: DataEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - dateEncoding - -
    -
    -
    -
    -
    -
    -

    The DateEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let dateEncoding: DateEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - keyEncoding - -
    -
    -
    -
    -
    -
    -

    The KeyEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let keyEncoding: KeyEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - spaceEncoding - -
    -
    -
    -
    -
    -
    -

    The SpaceEncoding to use.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let spaceEncoding: SpaceEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - allowedCharacters - -
    -
    -
    -
    -
    -
    -

    The CharacterSet of allowed (non-escaped) characters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var allowedCharacters: CharacterSet
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an instance from the supplied parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(alphabetizeKeyValuePairs: Bool = true,
    -            arrayEncoding: ArrayEncoding = .brackets,
    -            boolEncoding: BoolEncoding = .numeric,
    -            dataEncoding: DataEncoding = .base64,
    -            dateEncoding: DateEncoding = .deferredToDate,
    -            keyEncoding: KeyEncoding = .useDefaultKeys,
    -            spaceEncoding: SpaceEncoding = .percentEscaped,
    -            allowedCharacters: CharacterSet = .afURLQueryAllowed)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - alphabetizeKeyValuePairs - - -
    -

    Whether or not to sort the encoded key value pairs. true by default.

    -
    -
    - - arrayEncoding - - -
    -

    The ArrayEncoding to use. .brackets by default.

    -
    -
    - - boolEncoding - - -
    -

    The BoolEncoding to use. .numeric by default.

    -
    -
    - - dataEncoding - - -
    -

    The DataEncoding to use. .base64 by default.

    -
    -
    - - dateEncoding - - -
    -

    The DateEncoding to use. .deferredToDate by default.

    -
    -
    - - keyEncoding - - -
    -

    The KeyEncoding to use. .useDefaultKeys by default.

    -
    -
    - - spaceEncoding - - -
    -

    The SpaceEncoding to use. .percentEscaped by default.

    -
    -
    - - allowedCharacters - - -
    -

    The CharacterSet of allowed (non-escaped) characters. .afURLQueryAllowed by - default.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes the value as a URL form encoded String.

    -
    -

    Throws

    -

    An Error or EncodingError instance if encoding fails.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ value: Encodable) throws -> String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Encodable value.`

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded String.

    -
    -
    -
    -
  • -
  • -
    - - - - encode(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes the value as Data. This is performed by first creating an encoded String and then returning the -.utf8 data.

    -
    -

    Throws

    -

    An Error or EncodingError instance if encoding fails.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ value: Encodable) throws -> Data
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Encodable value.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded Data.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/ArrayEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/ArrayEncoding.html deleted file mode 100644 index d663d6a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/ArrayEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ArrayEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ArrayEncoding

-
-
-
public enum ArrayEncoding
- -
-
-

Encoding to use for Array values.

- -
-
- -
-
-
-
    -
  • -
    - - - - brackets - -
    -
    -
    -
    -
    -
    -

    An empty set of square brackets ([]) are appended to the key for every value. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case brackets
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noBrackets - -
    -
    -
    -
    -
    -
    -

    No brackets are appended to the key and the key is encoded as is.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noBrackets
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/BoolEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/BoolEncoding.html deleted file mode 100644 index ec3b7e2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/BoolEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - BoolEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

BoolEncoding

-
-
-
public enum BoolEncoding
- -
-
-

Encoding to use for Bool values.

- -
-
- -
-
-
-
    -
  • -
    - - - - numeric - -
    -
    -
    -
    -
    -
    -

    Encodes true as 1, false as 0.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case numeric
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - literal - -
    -
    -
    -
    -
    -
    -

    Encodes true as true, false as false. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case literal
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DataEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DataEncoding.html deleted file mode 100644 index 0000525..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DataEncoding.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - DataEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataEncoding

-
-
-
public enum DataEncoding
- -
-
-

Encoding to use for Data values.

- -
-
- -
-
-
-
    -
  • -
    - - - - deferredToData - -
    -
    -
    -
    -
    -
    -

    Defers encoding to the Data type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case deferredToData
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - base64 - -
    -
    -
    -
    -
    -
    -

    Encodes Data as a Base64-encoded string. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case base64
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    Encode the Data as a custom value encoded by the given closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((Data) throws -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DateEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DateEncoding.html deleted file mode 100644 index 6853d4e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/DateEncoding.html +++ /dev/null @@ -1,613 +0,0 @@ - - - - DateEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DateEncoding

-
-
-
public enum DateEncoding
- -
-
-

Encoding to use for Date values.

- -
-
- -
-
-
-
    -
  • -
    - - - - deferredToDate - -
    -
    -
    -
    -
    -
    -

    Defers encoding to the Date type. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case deferredToDate
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - secondsSince1970 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates as seconds since midnight UTC on January 1, 1970.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case secondsSince1970
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - millisecondsSince1970 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates as milliseconds since midnight UTC on January 1, 1970.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case millisecondsSince1970
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - iso8601 - -
    -
    -
    -
    -
    -
    -

    Encodes Dates according to the ISO8601 and RFC3339 standards.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case iso8601
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - formatted(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes Dates using the given DateFormatter.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case formatted(DateFormatter)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    Encodes Dates using the given closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((Date) throws -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/Error.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/Error.html deleted file mode 100644 index 5e24530..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/Error.html +++ /dev/null @@ -1,478 +0,0 @@ - - - - Error Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Error

-
-
-
public enum Error : Swift.Error
- -
-
-

URLEncodedFormEncoder error.

- -
-
- -
-
-
-
    -
  • -
    - - - - invalidRootObject(_:) - -
    -
    -
    -
    -
    -
    -

    An invalid root object was created by the encoder. Only keyed values are valid.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case invalidRootObject(String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/KeyEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/KeyEncoding.html deleted file mode 100644 index ce9a1d1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/KeyEncoding.html +++ /dev/null @@ -1,670 +0,0 @@ - - - - KeyEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

KeyEncoding

-
-
-
public enum KeyEncoding
- -
-
-

Encoding to use for keys.

- -

This type is derived from JSONEncoder‘s KeyEncodingStrategy -and XMLEncoders KeyEncodingStrategy.

- -
-
- -
-
-
-
    -
  • -
    - - - - useDefaultKeys - -
    -
    -
    -
    -
    -
    -

    Use the keys specified by each type. This is the default encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case useDefaultKeys
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - convertToSnakeCase - -
    -
    -
    -
    -
    -
    -

    Convert from camelCaseKeys to snake_case_keys before writing a key.

    - -

    Capital characters are determined by testing membership in -CharacterSet.uppercaseLetters and CharacterSet.lowercaseLetters -(Unicode General Categories Lu and Lt). -The conversion to lower case uses Locale.system, also known as -the ICU root locale. This means the result is consistent -regardless of the current user’s locale and language preferences.

    - -

    Converting from camel case to snake case:

    - -
      -
    1. Splits words at the boundary of lower-case to upper-case
    2. -
    3. Inserts _ between words
    4. -
    5. Lowercases the entire string
    6. -
    7. Preserves starting and ending _.
    8. -
    - -

    For example, oneTwoThree becomes one_two_three. _oneTwoThree_ becomes _one_two_three_.

    -
    -

    Note

    - Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case convertToSnakeCase
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - convertToKebabCase - -
    -
    -
    -
    -
    -
    -

    Same as convertToSnakeCase, but using - instead of _. -For example oneTwoThree becomes one-two-three.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case convertToKebabCase
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - capitalized - -
    -
    -
    -
    -
    -
    -

    Capitalize the first letter only. -For example oneTwoThree becomes OneTwoThree.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case capitalized
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - uppercased - -
    -
    -
    -
    -
    -
    -

    Uppercase all letters. -For example oneTwoThree becomes ONETWOTHREE.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case uppercased
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - lowercased - -
    -
    -
    -
    -
    -
    -

    Lowercase all letters. -For example oneTwoThree becomes onetwothree.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case lowercased
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - custom(_:) - -
    -
    -
    -
    -
    -
    -

    A custom encoding using the provided closure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case custom((String) -> String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/SpaceEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/SpaceEncoding.html deleted file mode 100644 index 8361bbb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormEncoder/SpaceEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - SpaceEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SpaceEncoding

-
-
-
public enum SpaceEncoding
- -
-
-

Encoding to use for spaces.

- -
-
- -
-
-
-
    -
  • -
    - - - - percentEscaped - -
    -
    -
    -
    -
    -
    -

    Encodes spaces according to normal percent escaping rules (%20).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case percentEscaped
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - plusReplaced - -
    -
    -
    -
    -
    -
    -

    Encodes spaces as +,

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case plusReplaced
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder.html deleted file mode 100644 index 572435e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder.html +++ /dev/null @@ -1,651 +0,0 @@ - - - - URLEncodedFormParameterEncoder Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncodedFormParameterEncoder

-
-
-
open class URLEncodedFormParameterEncoder : ParameterEncoder
- -
-
-

A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -on the Destination set.

- -

If no Content-Type header is already set on the provided URLRequests, it will be set to -application/x-www-form-urlencoded; charset=utf-8.

- -

Encoding behavior can be customized by passing an instance of URLEncodedFormEncoder to the initializer.

- -
-
- -
-
-
- -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder/Destination.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder/Destination.html deleted file mode 100644 index 1c26e9f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/URLEncodedFormParameterEncoder/Destination.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - Destination Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Destination

-
-
-
public enum Destination
- -
-
-

Defines where the URL-encoded string should be set for each URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - methodDependent - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to any existing query string for .get, .head, and .delete request. -Sets it to the httpBody for all other methods.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case methodDependent
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to any existing query string from the URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case queryString
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Applies the encoded query string to the httpBody of the URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpBody
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest.html deleted file mode 100644 index 8a6ea06..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest.html +++ /dev/null @@ -1,609 +0,0 @@ - - - - UploadRequest Class Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

UploadRequest

-
-
-
public class UploadRequest : DataRequest
- -
-
-

DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

- -
-
- -
-
-
-
    -
  • -
    - - - - Uploadable - -
    -
    -
    -
    -
    -
    -

    Type describing the origin of the upload, whether Data, file, or stream.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - upload - -
    -
    -
    -
    -
    -
    -

    The UploadableConvertible value used to produce the Uploadable value for this instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let upload: UploadableConvertible
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileManager - -
    -
    -
    -
    -
    -
    -

    FileManager used to perform cleanup tasks, including the removal of multipart form encoded payloads written -to disk.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let fileManager: FileManager
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - uploadable - -
    -
    -
    -
    -
    -
    -

    Uploadable value used by the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var uploadable: UploadRequest.Uploadable?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public override func cleanup()
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest/Uploadable.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest/Uploadable.html deleted file mode 100644 index 99fe7e7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Classes/UploadRequest/Uploadable.html +++ /dev/null @@ -1,570 +0,0 @@ - - - - Uploadable Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Uploadable

-
-
-
public enum Uploadable
- -
-
-

Type describing the origin of the upload, whether Data, file, or stream.

- -
-
- -
-
-
-
    -
  • -
    - - - - data(_:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided Data value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case data(Data)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - file(_:shouldRemove:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided file URL, as well as a Bool determining whether the source file should be -automatically removed once uploaded.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case file(URL, shouldRemove: Bool)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - stream(_:) - -
    -
    -
    -
    -
    -
    -

    Upload from the provided InputStream.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case stream(InputStream)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - createUploadable() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func createUploadable() throws -> UploadRequest.Uploadable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums.html deleted file mode 100644 index f007ef2..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - Enumerations Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Enumerations

-

The following enumerations are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AFError - -
    -
    -
    -
    -
    -
    -

    AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with -their own associated reasons.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum AFError : Error
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - AF - -
    -
    -
    -
    -
    -
    -

    Global namespace containing API for the default Session instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum AF
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RetryResult - -
    -
    -
    -
    -
    -
    -

    Outcome of determination whether retry is necessary.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum RetryResult
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AF.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AF.html deleted file mode 100644 index 019be1b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AF.html +++ /dev/null @@ -1,2419 +0,0 @@ - - - - AF Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AF

-
-
-
public enum AF
- -
-
-

Global namespace containing API for the default Session instance.

- -
-
- -
-
-
- - -
-
- - -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates a DownloadRequest using the Session.default from the resumeData produced from a previous -DownloadRequest cancellation to retrieve the contents of the original request and save them to the destination.

    -
    -

    Note

    -

    If destination is not specified, the download will be moved to a temporary location determined by - Alamofire.

    - -
    -
    -

    Note

    -

    On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), -resumeData is broken on background URL session configurations. There’s an underlying bug in the resumeData -generation logic where the data is written incorrectly and will always fail to resume the download. For more -information about the bug and possible workarounds, please refer to the this Stack Overflow post.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func download(resumingWith resumeData: Data,
    -                            interceptor: RequestInterceptor? = nil,
    -                            to destination: DownloadRequest.Destination? = nil) -> DownloadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - resumeData - - -
    -

    The resume Data. This is an opaque blob produced by URLSessionDownloadTask when a task is - cancelled. See Apple’s documentation - for more information.

    -
    -
    - - interceptor - - -
    -

    The RequestInterceptor, nil by default.

    -
    -
    - - destination - - -
    -

    The DownloadRequest.Destination closure used to determine the destination of the downloaded - file. nil by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created DownloadRequest.

    -
    -
    -
    -
  • -
-
-
-
- - - -

Data

-
-
- -
-
-
- - - -

File

-
-
- -
-
- - -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the multipart form data built using a closure and sent using the provided -URLRequest components and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                          to url: URLConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          method: HTTPMethod = .post,
    -                          headers: HTTPHeaders? = nil,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - convertible - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible -value, and a RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
    -                          with request: URLRequestConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData building closure.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components -and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: MultipartFormData,
    -                          to url: URLConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          method: HTTPMethod = .post,
    -                          headers: HTTPHeaders? = nil,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - url - - -
    -

    URLConvertible value to be used as the URLRequest‘s URL.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - method - - -
    -

    HTTPMethod for the URLRequest. .post by default.

    -
    -
    - - headers - - -
    -

    HTTPHeaders value to be added to the URLRequest. nil by default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager to be used if the form data exceeds the memory threshold and is - written to disk before being uploaded. .default instance by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible -value and RequestInterceptor.

    - -

    It is important to understand the memory implications of uploading MultipartFormData. If the cumulative -payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -used for larger payloads such as video content.

    - -

    The encodingMemoryThreshold parameter allows Alamofire to automatically determine whether to encode in-memory -or stream from disk. If the content length of the MultipartFormData is below the encodingMemoryThreshold, -encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -technique was used.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func upload(multipartFormData: MultipartFormData,
    -                          with request: URLRequestConvertible,
    -                          usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
    -                          interceptor: RequestInterceptor? = nil,
    -                          fileManager: FileManager = .default) -> UploadRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - -
    - - multipartFormData - - -
    -

    MultipartFormData instance to upload.

    -
    -
    - - request - - -
    -

    URLRequestConvertible value to be used to create the URLRequest.

    -
    -
    - - encodingMemoryThreshold - - -
    -

    Byte threshold used to determine whether the form data is encoded into memory or - onto disk before being uploaded. MultipartFormData.encodingMemoryThreshold by - default.

    -
    -
    - - interceptor - - -
    -

    RequestInterceptor value to be used by the returned DataRequest. nil by default.

    -
    -
    - - fileManager - - -
    -

    FileManager instance to be used by the returned UploadRequest. .default instance by - default.

    -
    -
    -
    -
    -

    Return Value

    -

    The created UploadRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError.html deleted file mode 100644 index 760dcdd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError.html +++ /dev/null @@ -1,1855 +0,0 @@ - - - - AFError Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AFError

-
-
-
public enum AFError : Error
- -
-
-

AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with -their own associated reasons.

- -
-
- -
-
-
- -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .sessionDeinitialized.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionDeinitializedError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .sessionInvalidated.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionInvalidatedError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .explicitlyCancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isExplicitlyCancelledError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isInvalidURLError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is .invalidURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isInvalidURLError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .parameterEncodingFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isParameterEncodingError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .parameterEncoderFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isParameterEncoderError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .multipartEncodingFailed. When true, the url and underlyingError -properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isMultipartEncodingError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .requestAdaptationFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isRequestAdaptationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .responseValidationFailed. When true, the acceptableContentTypes, -responseContentType, responseCode, and underlyingError properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResponseValidationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .responseSerializationFailed. When true, the failedStringEncoding and -underlyingError properties will contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isResponseSerializationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is .serverTrustEvaluationFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isServerTrustEvaluationError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isRequestRetryError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is requestRetryFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isRequestRetryError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is createUploadableFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCreateUploadableError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isCreateURLRequestError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns whether the instance is downloadedFileMoveFailed. When true, the destination and underlyingError properties will -contain the associated values.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isDownloadedFileMoveError: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSessionTaskError - -
    -
    -
    -
    -
    -
    -

    Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will -contain the associated value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSessionTaskError: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlConvertible - -
    -
    -
    -
    -
    -
    -

    The URLConvertible associated with the error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var urlConvertible: URLConvertible? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - url - -
    -
    -
    -
    -
    -
    -

    The URL associated with the error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var url: URL? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - underlyingError - -
    -
    -
    -
    -
    -
    -

    The underlying Error responsible for generating the failure associated with .sessionInvalidated, -.parameterEncodingFailed, .parameterEncoderFailed, .multipartEncodingFailed, .requestAdaptationFailed, -.responseSerializationFailed, .requestRetryFailed errors.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var underlyingError: Error? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The acceptable Content-Types of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var acceptableContentTypes: [String]? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - responseContentType - -
    -
    -
    -
    -
    -
    -

    The response Content-Type of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var responseContentType: String? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - responseCode - -
    -
    -
    -
    -
    -
    -

    The response code of a .responseValidationFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var responseCode: Int? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - failedStringEncoding - -
    -
    -
    -
    -
    -
    -

    The String.Encoding associated with a failed .stringResponse() call.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var failedStringEncoding: String.Encoding? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sourceURL - -
    -
    -
    -
    -
    -
    -

    The source URL of a .downloadedFileMoveFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var sourceURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - destinationURL - -
    -
    -
    -
    -
    -
    -

    The destination URL of a .downloadedFileMoveFailed error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var destinationURL: URL? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - errorDescription - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var errorDescription: String? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/MultipartEncodingFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/MultipartEncodingFailureReason.html deleted file mode 100644 index 1a4fa3a..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/MultipartEncodingFailureReason.html +++ /dev/null @@ -1,802 +0,0 @@ - - - - MultipartEncodingFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

MultipartEncodingFailureReason

-
-
-
public enum MultipartEncodingFailureReason
- -
-
-

The underlying reason the .multipartEncodingFailed error occurred.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The fileURL provided for reading an encodable body part isn’t a file URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartURLInvalid(url: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The filename of the fileURL provided has either an empty lastPathComponent or `pathExtension.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFilenameInvalid(in: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file at the fileURL provided was not reachable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileNotReachable(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Attempting to check the reachability of the fileURL provided threw an error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file at the fileURL provided is actually a directory.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileIsDirectory(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The size of the file at the fileURL provided was not returned by the system.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileSizeNotAvailable(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to find the size of the file at the fileURL provided threw an error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An InputStream could not be created for the provided fileURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyPartInputStreamCreationFailed(for: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    An OutputStream could not be created when attempting to write the encoded data to disk.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamCreationFailed(for: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The encoded body data could not be written to disk because a file already exists at the provided fileURL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamFileAlreadyExists(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The fileURL provided for writing the encoded body data to disk is not a file URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamURLInvalid(url: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to write the encoded body data to disk failed with an underlying error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case outputStreamWriteFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The attempt to read an encoded body part InputStream failed with underlying system error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputStreamReadFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason.html deleted file mode 100644 index c14953f..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason.html +++ /dev/null @@ -1,533 +0,0 @@ - - - - ParameterEncoderFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoderFailureReason

-
-
-
public enum ParameterEncoderFailureReason
- -
-
-

The underlying reason the .parameterEncoderFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - RequiredComponent - -
    -
    -
    -
    -
    -
    -

    Possible missing components.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum RequiredComponent
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A RequiredComponent was missing during encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingRequiredComponent(RequiredComponent)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - encoderFailed(error:) - -
    -
    -
    -
    -
    -
    -

    The underlying encoder failed with the associated error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case encoderFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html deleted file mode 100644 index 864fc1d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - RequiredComponent Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequiredComponent

-
-
-
public enum RequiredComponent
- -
-
-

Possible missing components.

- -
-
- -
-
-
-
    -
  • -
    - - - - url - -
    -
    -
    -
    -
    -
    -

    The URL was missing or unable to be extracted from the passed URLRequest or during encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case url
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpMethod(rawValue:) - -
    -
    -
    -
    -
    -
    -

    The HTTPMethod could not be extracted from the passed URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpMethod(rawValue: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncodingFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncodingFailureReason.html deleted file mode 100644 index 3995a8e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ParameterEncodingFailureReason.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - ParameterEncodingFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncodingFailureReason

-
-
-
public enum ParameterEncodingFailureReason
- -
-
-

The underlying reason the .parameterEncodingFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - missingURL - -
    -
    -
    -
    -
    -
    -

    The URLRequest did not have a URL to encode.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingURL
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    JSON serialization failed with an underlying system error during the encoding process.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case jsonEncodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom parameter encoding failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customEncodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseSerializationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseSerializationFailureReason.html deleted file mode 100644 index 7740740..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseSerializationFailureReason.html +++ /dev/null @@ -1,667 +0,0 @@ - - - - ResponseSerializationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseSerializationFailureReason

-
-
-
public enum ResponseSerializationFailureReason
- -
-
-

The underlying reason the response serialization error occurred.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    The server response contained no data or the data was zero length.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputDataNilOrZeroLength
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - inputFileNil - -
    -
    -
    -
    -
    -
    -

    The file containing the server response did not exist.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputFileNil
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The file containing the server response could not be read from the associated URL.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case inputFileReadFailed(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    String serialization failed using the provided String.Encoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case stringSerializationFailed(encoding: String.Encoding)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    JSON serialization failed with an underlying system error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case jsonSerializationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A DataDecoder failed to decode the response due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case decodingFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    A custom response serializer failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customSerializationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Generic serialization failed for an empty response that wasn’t type Empty but instead the associated type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case invalidEmptyResponse(type: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseValidationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseValidationFailureReason.html deleted file mode 100644 index d537ea6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ResponseValidationFailureReason.html +++ /dev/null @@ -1,614 +0,0 @@ - - - - ResponseValidationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseValidationFailureReason

-
-
-
public enum ResponseValidationFailureReason
- -
-
-

The underlying reason the .responseValidationFailed error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataFileNil - -
    -
    -
    -
    -
    -
    -

    The data file containing the server response did not exist.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case dataFileNil
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The data file containing the server response at the associated URL could not be read.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case dataFileReadFailed(at: URL)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response did not contain a Content-Type and the acceptableContentTypes provided did not contain a -wildcard type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case missingContentType(acceptableContentTypes: [String])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response Content-Type did not match any type in the provided acceptableContentTypes.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The response status code was not acceptable.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case unacceptableStatusCode(code: Int)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom response validation failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customValidationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason.html deleted file mode 100644 index 22f7b83..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason.html +++ /dev/null @@ -1,830 +0,0 @@ - - - - ServerTrustFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustFailureReason

-
-
-
public enum ServerTrustFailureReason
- -
-
-

Underlying reason a server trust evaluation error occurred.

- -
-
- -
-
-
-
    -
  • -
    - - - - Output - -
    -
    -
    -
    -
    -
    -

    The output of a server trust evaluation.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Output
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    No ServerTrustEvaluator was found for the associated host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noRequiredEvaluator(host: String)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noCertificatesFound - -
    -
    -
    -
    -
    -
    -

    No certificates were found with which to perform the trust evaluation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noCertificatesFound
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noPublicKeysFound - -
    -
    -
    -
    -
    -
    -

    No public keys were found with which to perform the trust evaluation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noPublicKeysFound
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, application of the associated SecPolicy failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, setting the associated anchor certificates failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    During evaluation, creation of the revocation policy failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case revocationPolicyCreationFailed
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    SecTrust evaluation failed with the associated Error, if one was produced.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case trustEvaluationFailed(error: Error?)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Default evaluation failed with the associated Output.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case defaultEvaluationFailed(output: Output)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Host validation failed with the associated Output.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case hostValidationFailed(output: Output)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Revocation check failed with the associated Output and options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Certificate pinning failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Public key pinning failed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Custom server trust evaluation failed due to the associated Error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case customEvaluationFailed(error: Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason/Output.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason/Output.html deleted file mode 100644 index da099f5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/ServerTrustFailureReason/Output.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - Output Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Output

-
-
-
public struct Output
- -
-
-

The output of a server trust evaluation.

- -
-
- -
-
-
-
    -
  • -
    - - - - host - -
    -
    -
    -
    -
    -
    -

    The host for which the evaluation was performed.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let host: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trust - -
    -
    -
    -
    -
    -
    -

    The SecTrust value which was evaluated.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let trust: SecTrust
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - status - -
    -
    -
    -
    -
    -
    -

    The OSStatus of evaluation operation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let status: OSStatus
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of the evaluation operation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: SecTrustResultType
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/URLRequestValidationFailureReason.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/URLRequestValidationFailureReason.html deleted file mode 100644 index 1fb0129..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/AFError/URLRequestValidationFailureReason.html +++ /dev/null @@ -1,478 +0,0 @@ - - - - URLRequestValidationFailureReason Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequestValidationFailureReason

-
-
-
public enum URLRequestValidationFailureReason
- -
-
-

The underlying reason the .urlRequestValidationFailed

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    URLRequest with GET method had body data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case bodyDataInGETRequest(Data)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/HTTPMethod.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/HTTPMethod.html deleted file mode 100644 index dbdfd33..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/HTTPMethod.html +++ /dev/null @@ -1,681 +0,0 @@ - - - - HTTPMethod Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPMethod

-
-
-
public enum HTTPMethod : String
- -
-
-

HTTP method definitions.

- -

See https://tools.ietf.org/html/rfc7231#section-4.3

- -
-
- -
-
-
-
    -
  • -
    - - - - connect - -
    -
    -
    -
    -
    -
    -

    CONNECT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case connect = "CONNECT"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delete - -
    -
    -
    -
    -
    -
    -

    DELETE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case delete = "DELETE"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - get - -
    -
    -
    -
    -
    -
    -

    GET method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case get = "GET"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - head - -
    -
    -
    -
    -
    -
    -

    HEAD method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case head = "HEAD"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    OPTIONS method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case options = "OPTIONS"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - patch - -
    -
    -
    -
    -
    -
    -

    PATCH method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case patch = "PATCH"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - post - -
    -
    -
    -
    -
    -
    -

    POST method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case post = "POST"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - put - -
    -
    -
    -
    -
    -
    -

    PUT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case put = "PUT"
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trace - -
    -
    -
    -
    -
    -
    -

    TRACE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case trace = "TRACE"
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/Result.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/Result.html deleted file mode 100644 index 3c425f6..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/Result.html +++ /dev/null @@ -1,1242 +0,0 @@ - - - - Result Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Result

-
-
-
public enum Result<Value>
- -
-
-

Used to represent whether a request was successful or encountered an error.

- -
    -
  • success: The request and all post processing operations were successful resulting in the serialization of the - provided associated value.

  • -
  • failure: The request encountered an error resulting in a failure. The associated values are the original data - provided by the server as well as the error that caused the failure.

  • -
- -
-
- -
-
-
-
    -
  • -
    - - - - success(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case success(Value)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - failure(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case failure(Error)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns true if the result is a success, false otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - isFailure - -
    -
    -
    -
    -
    -
    -

    Returns true if the result is a failure, false otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var isFailure: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value if the result is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Value? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Error? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes whether the result was a -success or failure in addition to the value or error.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(value:) - -
    -
    -
    -
    -
    -
    -

    Creates a Result instance from the result of a closure.

    - -

    A failure result is created when the closure throws, and a success result is created when the closure -succeeds without throwing an error.

    -
    func someString() throws -> String { ... }
    -
    -let result = Result(value: {
    -    return try someString()
    -})
    -
    -// The type of result is Result<String>
    -
    - -

    The trailing closure syntax is also supported:

    -
    let result = Result { try someString() }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(value: () throws -> Value)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The closure to execute and create the result for.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - unwrap() - -
    -
    -
    -
    -
    -
    -

    Returns the success value, or throws the failure error.

    -
    let possibleString: Result<String> = .success("success")
    -try print(possibleString.unwrap())
    -// Prints "success"
    -
    -let noString: Result<String> = .failure(error)
    -try print(noString.unwrap())
    -// Throws error
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func unwrap() throws -> Value
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: Result<Data> = .success(Data())
    -let possibleInt = possibleData.map { $0.count }
    -try print(possibleInt.unwrap())
    -// Prints "0"
    -
    -let noData: Result<Data> = .failure(error)
    -let noInt = noData.map { $0.count }
    -try print(noInt.unwrap())
    -// Throws error
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<T>(_ transform: (Value) -> T) -> Result<T>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the Result instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result containing the result of the given closure. If this instance is a failure, returns the - same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - flatMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the flatMap method with a closure that may throw an error. For example:

    -
    let possibleData: Result<Data> = .success(Data(...))
    -let possibleObject = possibleData.flatMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result containing the result of the given closure. If this instance is a failure, returns the - same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: Result<Data> = .failure(someError)
    -let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<T>(_ transform: (Error) -> T) -> Result where T : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result instance containing the result of the transform. If this instance is a success, returns - the same instance.

    -
    -
    -
    -
  • -
  • -
    - - - - flatMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the flatMapError function with a closure that may throw an error. For example:

    -
    let possibleData: Result<Data> = .success(Data(...))
    -let possibleObject = possibleData.flatMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func flatMapError<T>(_ transform: (Error) throws -> T) -> Result where T : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A Result instance containing the result of the transform. If this instance is a success, returns - the same instance.

    -
    -
    -
    -
  • -
  • -
    - - - - withValue(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success, passing the unwrapped value as a parameter.

    - -

    Use the withValue function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A closure that takes the success value of this instance.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - withError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure, passing the unwrapped error as a parameter.

    - -

    Use the withError function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func withError(_ closure: (Error) throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A closure that takes the success value of this instance.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - ifSuccess(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a success.

    - -

    Use the ifSuccess function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A Void closure.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
  • -
    - - - - ifFailure(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the Result is a failure.

    - -

    Use the ifFailure function to evaluate the passed closure without modifying the Result instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @discardableResult
    -public func ifFailure(_ closure: () throws -> Void) rethrows -> Result
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - closure - - -
    -

    A Void closure.

    -
    -
    -
    -
    -

    Return Value

    -

    This Result instance, unmodified.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/RetryResult.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/RetryResult.html deleted file mode 100644 index 76ef180..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Enums/RetryResult.html +++ /dev/null @@ -1,559 +0,0 @@ - - - - RetryResult Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RetryResult

-
-
-
public enum RetryResult
- -
-
-

Outcome of determination whether retry is necessary.

- -
-
- -
-
-
-
    -
  • -
    - - - - retry - -
    -
    -
    -
    -
    -
    -

    Retry should be attempted immediately.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case retry
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retryWithDelay(_:) - -
    -
    -
    -
    -
    -
    -

    Retry should be attempted after the associated TimeInterval.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case retryWithDelay(TimeInterval)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotRetry - -
    -
    -
    -
    -
    -
    -

    Do not retry.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotRetry
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Do not retry due to the associated AFError.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotRetryWithError(Error)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions.html deleted file mode 100644 index 9bae0aa..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions.html +++ /dev/null @@ -1,751 +0,0 @@ - - - - Extensions Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Extensions

-

The following extensions are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - Error - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension Error
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - URLRequest - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension URLRequest
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - HTTPURLResponse - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension HTTPURLResponse
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public extension URLSessionConfiguration
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Notification - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    extension Notification
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- -
-
-
    -
  • -
    - - - - CharacterSet - -
    -
    -
    -
    -
    -
    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public extension CharacterSet
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Array.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Array.html deleted file mode 100644 index 10f8663..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Array.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - Array Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Array

-
-
-
@frozen
-public extension Array where Element == ServerTrustEvaluating
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given SecTrust value for the given host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - trust - - -
    -

    The SecTrust value to evaluate.

    -
    -
    - - host - - -
    -

    The host for which to evaluate the SecTrust value.

    -
    -
    -
    -
    -

    Return Value

    -

    Whether or not the evaluator considers the SecTrust value valid for host.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Bundle.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Bundle.html deleted file mode 100644 index 210c154..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Bundle.html +++ /dev/null @@ -1,494 +0,0 @@ - - - - Bundle Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Bundle

-
-
-
class Bundle : NSObject
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Returns all valid cer, crt, and der certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    Returns all public keys for the valid certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/CharacterSet.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/CharacterSet.html deleted file mode 100644 index 2144003..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/CharacterSet.html +++ /dev/null @@ -1,488 +0,0 @@ - - - - CharacterSet Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CharacterSet

-
-
-
public extension CharacterSet
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - afURLQueryAllowed - -
    -
    -
    -
    -
    -
    -

    Creates a CharacterSet from RFC 3986 allowed characters.

    - -

    RFC 3986 states that the following characters are reserved characters.

    - -
      -
    • General Delimiters: :, #, [, ], @, ?, /
    • -
    • Sub-Delimiters: !, $, &, , (, ), *, +, ,, ;, =
    • -
    - -

    In RFC 3986 - Section 3.4, it states that the ? and / characters should not be escaped to allow -query strings to include a URL. Therefore, all reserved characters with the exception of ? and / -should be percent-escaped in the query string.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let afURLQueryAllowed: CharacterSet
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Error.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Error.html deleted file mode 100644 index f006796..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Error.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - Error Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Error

-
-
-
extension Error
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asAFError - -
    -
    -
    -
    -
    -
    -

    Returns the instance cast as an AFError.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var asAFError: AFError? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns the instance cast as an AFError. If casting fails, a fatalError with the specified message is thrown.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/HTTPURLResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/HTTPURLResponse.html deleted file mode 100644 index 9fffd9e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/HTTPURLResponse.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - HTTPURLResponse Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPURLResponse

-
-
-
extension HTTPURLResponse
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns allHeaderFields as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var headers: HTTPHeaders { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Notification.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Notification.html deleted file mode 100644 index 2fa2506..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/Notification.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - Notification Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Notification

-
-
-
extension Notification
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The Request contained by the instance’s userInfo, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var request: Request? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/SecTrust.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/SecTrust.html deleted file mode 100644 index 0ecff22..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/SecTrust.html +++ /dev/null @@ -1,683 +0,0 @@ - - - - SecTrust Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SecTrust

-
-
-
class SecTrust : _CFObject
- -
-
- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - apply(policy:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func apply(policy: SecPolicy) throws -> SecTrust
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func setAnchorCertificates(_ certificates: [SecCertificate]) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    The public keys contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificateData - -
    -
    -
    -
    -
    -
    -

    The Data values for all certificates contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificateData: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performDefaultEvaluation(forHost host: String) throws
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validateHost(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validateHost(_ host: String) throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/String.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/String.html deleted file mode 100644 index 8579500..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/String.html +++ /dev/null @@ -1,487 +0,0 @@ - - - - String Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

String

-
-
-
@frozen
-extension String: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL if self can be used to initialize a URL instance, otherwise throws.

    -
    -

    Throws

    - An AFError.invalidURL instance. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL initialized with self.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URL.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URL.html deleted file mode 100644 index 7fb02ee..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URL.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - URL Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URL

-
-
-
extension URL: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLComponents.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLComponents.html deleted file mode 100644 index 852bc77..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLComponents.html +++ /dev/null @@ -1,486 +0,0 @@ - - - - URLComponents Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLComponents

-
-
-
extension URLComponents: URLConvertible
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL if the self‘s url is not nil, otherwise throws.

    -
    -

    Throws

    - An AFError.invalidURL instance. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL from the url property.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLRequest.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLRequest.html deleted file mode 100644 index b8cec70..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLRequest.html +++ /dev/null @@ -1,645 +0,0 @@ - - - - URLRequest Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequest

-
-
-
extension URLRequest
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns allHTTPHeaderFields as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var headers: HTTPHeaders { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    -

    Returns self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - method - -
    -
    -
    -
    -
    -
    -

    Returns the httpMethod as Alamofire’s HTTPMethod type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var method: HTTPMethod? { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - validate() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func validate() throws
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLSessionConfiguration.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLSessionConfiguration.html deleted file mode 100644 index 64abc67..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Extensions/URLSessionConfiguration.html +++ /dev/null @@ -1,477 +0,0 @@ - - - - URLSessionConfiguration Extension Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLSessionConfiguration

-
-
-
public extension URLSessionConfiguration
- -
-
- -
-
- -
-
-
-
    -
  • -
    - - - - headers - -
    -
    -
    -
    -
    -
    -

    Returns httpAdditionalHeaders as HTTPHeaders.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var headers: HTTPHeaders { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Functions.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Functions.html deleted file mode 100644 index 9debbb7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Functions.html +++ /dev/null @@ -1,494 +0,0 @@ - - - - Functions Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (77% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Functions

-

The following functions are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - ==(_:_:) - -
    -
    -
    -
    -
    -
    -

    Returns whether the two network reachability status values are equal.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func ==(
    -    lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
    -    rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
    -    -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - lhs - - -
    -

    The left-hand side value to compare.

    -
    -
    - - rhs - - -
    -

    The right-hand side value to compare.

    -
    -
    -
    -
    -

    Return Value

    -

    true if the two values are equal, false otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols.html deleted file mode 100644 index 64e6f3b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols.html +++ /dev/null @@ -1,1134 +0,0 @@ - - - - Protocols Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Protocols

-

The following protocols are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AlamofireExtended - -
    -
    -
    -
    -
    -
    -

    Protocol describing the af extension points for Alamofire extended types.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol AlamofireExtended
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - CachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    A type that handles whether the data task should store the HTTP response in the cache.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol CachedResponseHandler
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - EventMonitor - -
    -
    -
    -
    -
    -
    -

    Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -URLSession delegate protocols as well as various events from the lifetime of Request and its subclasses.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol EventMonitor
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ParameterEncoder - -
    -
    -
    -
    -
    -
    -

    A type that can encode any Encodable type into a URLRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ParameterEncoder
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ParameterEncoding - -
    -
    -
    -
    -
    -
    -

    A type used to define how a set of parameters are applied to a URLRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RedirectHandler - -
    -
    -
    -
    -
    -
    -

    A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RedirectHandler
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - RequestDelegate - -
    -
    -
    -
    -
    -
    -

    Protocol abstraction for Request‘s communication back to the SessionDelegate.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestDelegate : AnyObject
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
    -
  • -
    - - - - RequestAdapter - -
    -
    -
    -
    -
    -
    -

    A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestAdapter
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - RequestRetrier - -
    -
    -
    -
    -
    -
    -

    A type that determines whether a request should be retried after being executed by the specified session manager -and encountering an error.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol RequestRetrier
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    The type to which all data response serializers must conform in order to serialize a response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    The type to which all download response serializers must conform in order to serialize a response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DownloadResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ResponseSerializer - -
    -
    -
    -
    -
    -
    -

    A serializer that can handle both data and download responses.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ResponseSerializer : DataResponseSerializerProtocol, DownloadResponseSerializerProtocol
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - DataPreprocessor - -
    -
    -
    -
    -
    -
    -

    Type used to preprocess Data before it handled by a serializer.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataPreprocessor
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - EmptyResponse - -
    -
    -
    -
    -
    -
    -

    Protocol representing an empty response. Use T.emptyValue() to get an instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol EmptyResponse
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - DataDecoder - -
    -
    -
    -
    -
    -
    -

    Any type which can decode Data into a Decodable type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol DataDecoder
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ServerTrustEvaluating - -
    -
    -
    -
    -
    -
    -

    A protocol describing the API used to evaluate server trusts.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol ServerTrustEvaluating
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLConvertible - -
    -
    -
    -
    -
    -
    -

    Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct -URLRequests.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol URLConvertible
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLRequestConvertible - -
    -
    -
    -
    -
    -
    -

    Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public protocol URLRequestConvertible
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/AlamofireExtended.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/AlamofireExtended.html deleted file mode 100644 index eaa2cca..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/AlamofireExtended.html +++ /dev/null @@ -1,541 +0,0 @@ - - - - AlamofireExtended Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireExtended

-
-
-
public protocol AlamofireExtended
- -
-
-

Protocol describing the af extension points for Alamofire extended types.

- -
-
- -
-
-
-
    -
  • -
    - - - - ExtendedType - -
    -
    -
    -
    -
    -
    -

    Type being extended.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype ExtendedType
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - af - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Static Alamofire extension point.

    - -
    -

    Default Implementation

    -
    -

    Static Alamofire extension point.

    -

    Instance Alamofire extension point.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static var af: AlamofireExtension<ExtendedType>.Type { get set }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - af - -
    -
    -
    -
    -
    -
    -

    Instance Alamofire extension point.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var af: AlamofireExtension<ExtendedType> { get set }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/CachedResponseHandler.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/CachedResponseHandler.html deleted file mode 100644 index 5c797ea..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/CachedResponseHandler.html +++ /dev/null @@ -1,529 +0,0 @@ - - - - CachedResponseHandler Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

CachedResponseHandler

-
-
-
public protocol CachedResponseHandler
- -
-
-

A type that handles whether the data task should store the HTTP response in the cache.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether the HTTP response should be stored in the cache.

    - -

    The completion closure should be passed one of three possible options:

    - -
      -
    1. The cached response provided by the server (this is the most common use case).
    2. -
    3. A modified version of the cached response (you may want to modify it in some way before caching).
    4. -
    5. A nil value to prevent the cached response from being stored in the cache.
    6. -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func dataTask(_ task: URLSessionDataTask, willCacheResponse response: CachedURLResponse, completion: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - task - - -
    -

    The data task whose request resulted in the cached response.

    -
    -
    - - response - - -
    -

    The cached response to potentially store in the cache.

    -
    -
    - - completion - - -
    -

    The closure to execute containing cached response, a modified response, or nil.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataDecoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataDecoder.html deleted file mode 100644 index b419233..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataDecoder.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - DataDecoder Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataDecoder

-
-
-
public protocol DataDecoder
- -
-
-

Any type which can decode Data into a Decodable type.

- -
-
- -
-
-
-
    -
  • -
    - - - - decode(_:from:) - -
    -
    -
    -
    -
    -
    -

    Decode Data into the provided type.

    -
    -

    Throws

    -

    Any error that occurs during decode.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func decode<D>(_ type: D.Type, from data: Data) throws -> D where D : Decodable
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - type - - -
    -

    The Type to be decoded.

    -
    -
    - - data - - -
    -

    The Data to be decoded.

    -
    -
    -
    -
    -

    Return Value

    -

    The decoded value of type D.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataPreprocessor.html deleted file mode 100644 index eaad83d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataPreprocessor.html +++ /dev/null @@ -1,497 +0,0 @@ - - - - DataPreprocessor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataPreprocessor

-
-
-
public protocol DataPreprocessor
- -
-
-

Type used to preprocess Data before it handled by a serializer.

- -
-
- -
-
-
-
    -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    -

    Process Data before it’s handled by a serializer.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - data - - -
    -

    The raw Data to process.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataResponseSerializerProtocol.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataResponseSerializerProtocol.html deleted file mode 100644 index e985d88..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DataResponseSerializerProtocol.html +++ /dev/null @@ -1,569 +0,0 @@ - - - - DataResponseSerializerProtocol Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponseSerializerProtocol

-
-
-
public protocol DataResponseSerializerProtocol
- -
-
-

The type to which all data response serializers must conform in order to serialize a response.

- -
-
- -
-
-
-
    -
  • -
    - - - - SerializedObject - -
    -
    -
    -
    -
    -
    -

    The type of serialized object to be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype SerializedObject
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Serialize the response Data into the provided type..

    -
    -

    Throws

    -

    Any Error produced during serialization.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest which was used to perform the request, if any.

    -
    -
    - - response - - -
    -

    HTTPURLResponse received from the server, if any.

    -
    -
    - - data - - -
    -

    Data returned from the server, if any.

    -
    -
    - - error - - -
    -

    Error produced by Alamofire or the underlying URLSession during the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The SerializedObject.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DownloadResponseSerializerProtocol.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DownloadResponseSerializerProtocol.html deleted file mode 100644 index 3ad7dd3..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/DownloadResponseSerializerProtocol.html +++ /dev/null @@ -1,576 +0,0 @@ - - - - DownloadResponseSerializerProtocol Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadResponseSerializerProtocol

-
-
-
public protocol DownloadResponseSerializerProtocol
- -
-
-

The type to which all download response serializers must conform in order to serialize a response.

- -
-
- -
-
-
-
    -
  • -
    - - - - SerializedObject - -
    -
    -
    -
    -
    -
    -

    The type of serialized object to be created.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    associatedtype SerializedObject
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializeDownload(request:response:fileURL:error:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Serialize the downloaded response Data from disk into the provided type..

    -
    -

    Throws

    -

    Any Error produced during serialization.

    - -
    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest which was used to perform the request, if any.

    -
    -
    - - response - - -
    -

    HTTPURLResponse received from the server, if any.

    -
    -
    - - fileURL - - -
    -

    File URL to which the response data was downloaded.

    -
    -
    - - error - - -
    -

    Error produced by Alamofire or the underlying URLSession during the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The SerializedObject.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EmptyResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EmptyResponse.html deleted file mode 100644 index b7876f0..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EmptyResponse.html +++ /dev/null @@ -1,482 +0,0 @@ - - - - EmptyResponse Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

EmptyResponse

-
-
-
public protocol EmptyResponse
- -
-
-

Protocol representing an empty response. Use T.emptyValue() to get an instance.

- -
-
- -
-
-
-
    -
  • -
    - - - - emptyValue() - -
    -
    -
    -
    -
    -
    -

    Empty value for the conforming type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func emptyValue() -> Self
    - -
    -
    -
    -

    Return Value

    -

    Value of Self to use for empty values.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EventMonitor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EventMonitor.html deleted file mode 100644 index e871a0b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/EventMonitor.html +++ /dev/null @@ -1,1957 +0,0 @@ - - - - EventMonitor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

EventMonitor

-
-
-
public protocol EventMonitor
- -
-
-

Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -URLSession delegate protocols as well as various events from the lifetime of Request and its subclasses.

- -
-
- -
-
-
-
    -
  • -
    - - - - queue - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    The DispatchQueue onto which Alamofire’s root CompositeEventMonitor will dispatch events. .main by default.

    - -
    -

    Default Implementation

    -
    -

    The default queue on which CompositeEventMonitors will call the EventMonitor methods. .main by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var queue: DispatchQueue { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:didBecomeInvalidWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDelegate‘s urlSession(_:didBecomeInvalidWithError:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:task:didReceive:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didReceive:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:taskNeedsNewBodyStream:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:needNewBodyStream:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:willPerformHTTPRedirection:newRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:didFinishCollecting:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didFinishCollecting:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:task:didCompleteWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:task:didCompleteWithError:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:taskIsWaitingForConnectivity:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionTaskDelegate‘s urlSession(_:taskIsWaitingForConnectivity:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
    -func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:dataTask:didReceive:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:didReceive:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:dataTask:willCacheResponse:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:willCacheResponse:completionHandler:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - urlSession(_:downloadTask:didFinishDownloadingTo:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didFinishDownloadingTo:) method.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - request(_:didCreateInitialURLRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a URLRequest is first created for a Request. If a RequestAdapter is active, the -URLRequest will be adapted before being issued.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToCreateURLRequestWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when the attempt to create a URLRequest from a Request‘s original URLRequestConvertible value fails.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didAdaptInitialRequest:to:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a RequestAdapter adapts the Request‘s initial URLRequest.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToAdaptURLRequest:withError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a RequestAdapter fails to adapt the Request‘s initial URLRequest.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCreateURLRequest:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a final URLRequest is created for a Request.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCreateTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a URLSessionTask subclass instance is created for a Request.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCreateTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didGatherMetrics:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a URLSessionTaskMetrics value.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailTask:earlyWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request fails due to an error created by Alamofire. e.g. When certificate pinning fails.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCompleteTask:with:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s task completes, possibly with an error. A Request may receive this event -multiple times if it is retried.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestIsRetrying(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request is about to be retried.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestIsRetrying(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidFinish(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request finishes and response serializers are being called.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidFinish(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidResume(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a resume call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidResume(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didResumeTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is resumed.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didResumeTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidSuspend(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a suspend call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidSuspend(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didSuspendTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is suspended.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didSuspendTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestDidCancel(_:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request receives a cancel call.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func requestDidCancel(_ request: Request)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didCancelTask:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when a Request‘s associated URLSessionTask is cancelled.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: Request, didCancelTask task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
- -
    -
  • -
    - - - - request(_:didCreateUploadable:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest creates its Uploadable value, indicating the type of upload it represents.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didFailToCreateUploadableWithError:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest failed to create its Uploadable value due to an error.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(_:didProvideInputStream:) - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    Event called when an UploadRequest provides the InputStream from its Uploadable value. This only occurs if -the InputStream does not wrap a Data value or file URL.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoder.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoder.html deleted file mode 100644 index bc140d7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoder.html +++ /dev/null @@ -1,519 +0,0 @@ - - - - ParameterEncoder Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoder

-
-
-
public protocol ParameterEncoder
- -
-
-

A type that can encode any Encodable type into a URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - encode(_:into:) - -
    -
    -
    -
    -
    -
    -

    Encode the provided Encodable parameters into request.

    -
    -

    Throws

    -

    An Error when encoding fails. For Alamofire provided encoders, this will be an instance of - AFError.parameterEncoderFailed with an associated ParameterEncoderFailureReason.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func encode<Parameters>(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest where Parameters : Encodable
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - parameters - - -
    -

    The Encodable parameter value.

    -
    -
    - - request - - -
    -

    The URLRequest into which to encode the parameters.

    -
    -
    -
    -
    -

    Return Value

    -

    A URLRequest with the result of the encoding.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoding.html deleted file mode 100644 index 4a4e7ff..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ParameterEncoding.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - ParameterEncoding Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ParameterEncoding

-
-
-
public protocol ParameterEncoding
- -
-
-

A type used to define how a set of parameters are applied to a URLRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    -

    Creates a URLRequest by encoding parameters and applying them on the passed request.

    -
    -

    Throws

    -

    Any Error produced during parameter encoding.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - urlRequest - - -
    -

    URLRequestConvertible value onto which parameters will be encoded.

    -
    -
    - - parameters - - -
    -

    Parameters to encode onto the request.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded URLRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RedirectHandler.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RedirectHandler.html deleted file mode 100644 index b0b1594..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RedirectHandler.html +++ /dev/null @@ -1,541 +0,0 @@ - - - - RedirectHandler Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RedirectHandler

-
-
-
public protocol RedirectHandler
- -
-
-

A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines how the HTTP redirect response should be redirected to the new request.

    - -

    The completion closure should be passed one of three possible options:

    - -
      -
    1. The new request specified by the redirect (this is the most common use case).
    2. -
    3. A modified version of the new request (you may want to route it somewhere else).
    4. -
    5. A nil value to deny the redirect request and return the body of the redirect response.
    6. -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func task(_ task: URLSessionTask, willBeRedirectedTo request: URLRequest, for response: HTTPURLResponse, completion: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - task - - -
    -

    The task whose request resulted in a redirect.

    -
    -
    - - request - - -
    -

    The URL request object to the new location specified by the redirect response.

    -
    -
    - - response - - -
    -

    The response containing the server’s response to the original request.

    -
    -
    - - completion - - -
    -

    The closure to execute containing the new request, a modified request, or nil.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestAdapter.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestAdapter.html deleted file mode 100644 index 78891bb..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestAdapter.html +++ /dev/null @@ -1,521 +0,0 @@ - - - - RequestAdapter Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestAdapter

-
-
-
public protocol RequestAdapter
- -
-
-

A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Inspects and adapts the specified URLRequest in some manner and calls the completion handler with the Result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - urlRequest - - -
    -

    The URLRequest to adapt.

    -
    -
    - - session - - -
    -

    The Session that will execute the URLRequest.

    -
    -
    - - completion - - -
    -

    The completion handler that must be called when adaptation is complete.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestDelegate.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestDelegate.html deleted file mode 100644 index f98fa8d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestDelegate.html +++ /dev/null @@ -1,679 +0,0 @@ - - - - RequestDelegate Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestDelegate

-
-
-
public protocol RequestDelegate : AnyObject
- -
-
-

Protocol abstraction for Request‘s communication back to the SessionDelegate.

- -
-
- -
-
-
-
    -
  • -
    - - - - sessionConfiguration - -
    -
    -
    -
    -
    -
    -

    URLSessionConfiguration used to create the underlying URLSessionTasks.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var sessionConfiguration: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - startImmediately - -
    -
    -
    -
    -
    -
    -

    Determines whether the Request should automatically call resume() when adding the first response handler.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var startImmediately: Bool { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cleanup(after:) - -
    -
    -
    -
    -
    -
    -

    Notifies the delegate the Request has reached a point where it needs cleanup.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func cleanup(after request: Request)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - request - - -
    -

    The Request to cleanup after.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Asynchronously ask the delegate whether a Request will be retried.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - request - - -
    -

    Request which failed.

    -
    -
    - - error - - -
    -

    Error which produced the failure.

    -
    -
    - - completion - - -
    -

    Closure taking the RetryResult for evaluation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Asynchronously retry the Request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - request - - -
    -

    Request which will be retried.

    -
    -
    - - timeDelay - - -
    -

    TimeInterval after which the retry will be triggered.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestInterceptor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestInterceptor.html deleted file mode 100644 index 1cf9116..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestInterceptor.html +++ /dev/null @@ -1,512 +0,0 @@ - - - - RequestInterceptor Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestInterceptor

-
-
-
public protocol RequestInterceptor : RequestAdapter, RequestRetrier
- -
-
-

Type that provides both RequestAdapter and RequestRetrier functionality.

- -
-
- -
-
-
-
    -
  • -
    - - - - adapt(_:for:completion:) - - - Extension method - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - retry(_:for:dueTo:completion:) - - - Extension method - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func retry(_ request: Request,
    -                  for session: Session,
    -                  dueTo error: Error,
    -                  completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestRetrier.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestRetrier.html deleted file mode 100644 index 70a7a5d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/RequestRetrier.html +++ /dev/null @@ -1,538 +0,0 @@ - - - - RequestRetrier Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

RequestRetrier

-
-
-
public protocol RequestRetrier
- -
-
-

A type that determines whether a request should be retried after being executed by the specified session manager -and encountering an error.

- -
-
- -
-
-
-
    -
  • - -
    -
    -
    -
    -
    -

    Determines whether the Request should be retried by calling the completion closure.

    - -

    This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs -to be retried. The one requirement is that the completion closure is called to ensure the request is properly -cleaned up after.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    Request that failed due to the provided Error.

    -
    -
    - - session - - -
    -

    Session that produced the Request.

    -
    -
    - - error - - -
    -

    Error encountered while executing the Request.

    -
    -
    - - completion - - -
    -

    Completion closure to be executed when a retry decision has been determined.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ResponseSerializer.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ResponseSerializer.html deleted file mode 100644 index ab8e5c1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ResponseSerializer.html +++ /dev/null @@ -1,825 +0,0 @@ - - - - ResponseSerializer Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseSerializer

-
-
-
public protocol ResponseSerializer : DataResponseSerializerProtocol, DownloadResponseSerializerProtocol
- -
-
-

A serializer that can handle both data and download responses.

- -
-
- -
-
-
-
    -
  • -
    - - - - dataPreprocessor - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    DataPreprocessor used to prepare incoming Data for serialization.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var dataPreprocessor: DataPreprocessor { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyRequestMethods - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    HTTPMethods for which empty response bodies are considered appropriate.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var emptyRequestMethods: Set<HTTPMethod> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseCodes - - - Default implementation - -
    -
    -
    -
    -
    -
    -

    HTTP response codes for which empty response bodies are considered appropriate.

    - -
    -

    Default Implementation

    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var emptyResponseCodes: Set<Int> { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - defaultDataPreprocessor - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Default DataPreprocessor. PassthroughPreprocessor by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultDataPreprocessor: DataPreprocessor { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEmptyRequestMethods - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Default HTTPMethods for which empty response bodies are considered appropriate. [.head] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultEmptyRequestMethods: Set<HTTPMethod> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultEmptyResponseCodes - - - Extension method - -
    -
    -
    -
    -
    -
    -

    HTTP response codes for which empty response bodies are considered appropriate. [204, 205] by default.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var defaultEmptyResponseCodes: Set<Int> { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - requestAllowsEmptyResponseData(_:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether the request allows empty response bodies, if request exists.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - request - - -
    -

    URLRequest to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    Bool representing the outcome of the evaluation, or nil if request was nil.

    -
    -
    -
    -
  • -
  • -
    - - - - responseAllowsEmptyResponseData(_:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether the response allows empty response bodies, if response exists`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - response - - -
    -

    HTTPURLResponse to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    Bool representing the outcome of the evaluation, or nil if response was nil.

    -
    -
    -
    -
  • -
  • -
    - - - - emptyResponseAllowed(forRequest:response:) - - - Extension method - -
    -
    -
    -
    -
    -
    -

    Determines whether request and response allow empty response bodies.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - request - - -
    -

    URLRequest to evaluate.

    -
    -
    - - response - - -
    -

    HTTPURLResponse to evaluate.

    -
    -
    -
    -
    -

    Return Value

    -

    true if request or response allow empty bodies, false otherwise.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ServerTrustEvaluating.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ServerTrustEvaluating.html deleted file mode 100644 index e432683..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/ServerTrustEvaluating.html +++ /dev/null @@ -1,513 +0,0 @@ - - - - ServerTrustEvaluating Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ServerTrustEvaluating

-
-
-
public protocol ServerTrustEvaluating
- -
-
-

A protocol describing the API used to evaluate server trusts.

- -
-
- -
-
-
-
    -
  • -
    - - - - evaluate(_:forHost:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given SecTrust value for the given host.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func evaluate(_ trust: SecTrust, forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - trust - - -
    -

    The SecTrust value to evaluate.

    -
    -
    - - host - - -
    -

    The host for which to evaluate the SecTrust value.

    -
    -
    -
    -
    -

    Return Value

    -

    A Bool indicating whether the evaluator considers the SecTrust value valid for host.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/SessionStateProvider.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/SessionStateProvider.html deleted file mode 100644 index 695f181..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/SessionStateProvider.html +++ /dev/null @@ -1,630 +0,0 @@ - - - - SessionStateProvider Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (75% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

SessionStateProvider

-
-
-
public protocol SessionStateProvider : AnyObject
- -
-
-

Undocumented

- -
-
- -
-
-
-
    -
  • -
    - - - - serverTrustManager - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var serverTrustManager: ServerTrustManager? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - redirectHandler - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var redirectHandler: RedirectHandler? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cachedResponseHandler - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var cachedResponseHandler: CachedResponseHandler? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - request(for:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func request(for task: URLSessionTask) -> Request?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - didCompleteTask(_:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func didCompleteTask(_ task: URLSessionTask)
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - credential(for:in:) - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func cancelRequestsForSessionInvalidation(with error: Error?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLConvertible.html deleted file mode 100644 index 74f2fc1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLConvertible.html +++ /dev/null @@ -1,488 +0,0 @@ - - - - URLConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLConvertible

-
-
-
public protocol URLConvertible
- -
-
-

Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct -URLRequests.

- -
-
- -
-
-
-
    -
  • -
    - - - - asURL() - -
    -
    -
    -
    -
    -
    -

    Returns a URL from the conforming instance or throws.

    -
    -

    Throws

    - Any error thrown while creating the URL. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func asURL() throws -> URL
    - -
    -
    -
    -

    Return Value

    -

    The URL created from the instance.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLRequestConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLRequestConvertible.html deleted file mode 100644 index ef46800..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/URLRequestConvertible.html +++ /dev/null @@ -1,521 +0,0 @@ - - - - URLRequestConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLRequestConvertible

-
-
-
public protocol URLRequestConvertible
- -
-
-

Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

- -
-
- -
-
-
-
    -
  • -
    - - - - asURLRequest() - -
    -
    -
    -
    -
    -
    -

    Returns a URLRequest or throws if an Error was encountered.

    -
    -

    Throws

    - Any error thrown while constructing the URLRequest. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func asURLRequest() throws -> URLRequest
    - -
    -
    -
    -

    Return Value

    -

    A URLRequest.

    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - urlRequest - - - Extension method - -
    -
    -
    -
    -
    -
    -

    The URLRequest returned by discarding any Error encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var urlRequest: URLRequest? { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/UploadableConvertible.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/UploadableConvertible.html deleted file mode 100644 index 000b5ad..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Protocols/UploadableConvertible.html +++ /dev/null @@ -1,487 +0,0 @@ - - - - UploadableConvertible Protocol Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- - -
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs.html deleted file mode 100644 index aaeea16..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs.html +++ /dev/null @@ -1,892 +0,0 @@ - - - - Structures Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Structures

-

The following structures are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - AlamofireExtension - -
    -
    -
    -
    -
    -
    -

    Type that acts as a generic extension point for all AlamofireExtended types.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct AlamofireExtension<ExtendedType>
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - ResponseCacher - -
    -
    -
    -
    -
    -
    -

    ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached -response.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct ResponseCacher
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - HTTPHeaders - -
    -
    -
    -
    -
    -
    -

    An order-preserving and case-insensitive representation of HTTP headers.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPHeaders
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - HTTPHeader - -
    -
    -
    -
    -
    -
    -

    A representation of a single HTTP header’s name / value pair.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPHeader : Hashable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - HTTPMethod - -
    -
    -
    -
    -
    -
    -

    Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so -HTTPMethod.get != HTTPMethod(rawValue: "get").

    - -

    See https://tools.ietf.org/html/rfc7231#section-4.3

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct HTTPMethod : RawRepresentable, Equatable, Hashable
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - URLEncoding - -
    -
    -
    -
    -
    -
    -

    Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -the HTTP body depends on the destination of the encoding.

    - -

    The Content-Type HTTP header field of an encoded request with HTTP body is set to -application/x-www-form-urlencoded; charset=utf-8.

    - -

    There is no published specification for how to encode collection types. By default the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

    - -

    BoolEncoding can be used to configure how boolean values are encoded. The default behavior is to encode -true as 1 and false as 0.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct URLEncoding : ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - JSONEncoding - -
    -
    -
    -
    -
    -
    -

    Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the -request. The Content-Type HTTP header field of an encoded request is set to application/json.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct JSONEncoding : ParameterEncoding
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - Redirector - -
    -
    -
    -
    -
    -
    -

    Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Redirector
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - DataResponse - -
    -
    -
    -
    -
    -
    -

    Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct DataResponse<Success, Failure> where Failure : Error
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - DownloadResponse - -
    -
    -
    -
    -
    -
    -

    Used to store all data associated with a serialized response of a download request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct DownloadResponse<Success, Failure> where Failure : Error
    - -
    -
    -
    -
    -
  • -
-
-
- - -
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - Empty - -
    -
    -
    -
    -
    -
    -

    Type representing an empty response. Use Empty.value to get the static instance.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public struct Empty : Decodable
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/AlamofireExtension.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/AlamofireExtension.html deleted file mode 100644 index 6e636af..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/AlamofireExtension.html +++ /dev/null @@ -1,1427 +0,0 @@ - - - - AlamofireExtension Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

AlamofireExtension

-
-
-
public struct AlamofireExtension<ExtendedType>
- -
-
-

Type that acts as a generic extension point for all AlamofireExtended types.

- -
-
- -
-
-
- -
    -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    Returns all valid cer, crt, and der certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    Returns all public keys for the valid certificates in the bundle.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns all pathnames for the resources identified by the provided file extensions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func paths(forResourcesOfTypes types: [String]) -> [String]
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - types - - -
    -

    The filename extensions locate.

    -
    -
    -
    -
    -

    Return Value

    -

    All pathnames for the given filename extensions.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Evaluates self after applying the SecPolicy value provided.

    -
    -

    Throws

    -

    Any Error from applying the SecPolicy or from evaluation.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS 12, OSX 10.14, tvOS 12, watchOS 5, *)
    -func evaluate(afterApplying policy: SecPolicy) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - policy - - -
    -

    The SecPolicy to apply to self before evaluation.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Attempts to validate self using the SecPolicy provided and transforming any error produced using the closure passed.

    -
    -

    Throws

    - Any Error from applying the policy, or the result of errorProducer if validation fails. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:﹚")
    -@available(OSX, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:﹚")
    -@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:﹚")
    -@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:﹚")
    -func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - policy - - -
    -

    The SecPolicy used to evaluate self.

    -
    -
    - - errorProducer - - -
    -

    The closure used transform the failed OSStatus and SecTrustResultType.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - apply(policy:) - -
    -
    -
    -
    -
    -
    -

    Applies a SecPolicy to self, throwing if it fails.

    -
    -

    Throws

    -

    An AFError.serverTrustEvaluationFailed instance with a .policyApplicationFailed reason.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func apply(policy: SecPolicy) throws -> SecTrust
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - policy - - -
    -

    The SecPolicy.

    -
    -
    -
    -
    -

    Return Value

    -

    self, with the policy applied.

    -
    -
    -
    -
  • -
  • -
    - - - - evaluate() - -
    -
    -
    -
    -
    -
    -

    Evaluate self, throwing an Error if evaluation fails.

    -
    -

    Throws

    - AFError.serverTrustEvaluationFailed with reason .trustValidationFailed and associated error from - the underlying evaluation. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS 12, OSX 10.14, tvOS 12, watchOS 5, *)
    -func evaluate() throws
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validate self, passing any failure values through errorProducer.

    -
    -

    Throws

    - The Error produced by the errorProducer closure. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(﹚")
    -@available(OSX, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(﹚")
    -@available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(﹚")
    -@available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(﹚")
    -func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - errorProducer - - -
    -

    The closure used to transform the failed OSStatus and SecTrustResultType into an - Error.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Sets a custom certificate chain on self, allowing full validation of a self-signed certificate and its chain.

    -
    -

    Throws

    - Any error produced when applying the new certificate chain. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func setAnchorCertificates(_ certificates: [SecCertificate]) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - certificates - - -
    -

    The SecCertificates to add to the chain.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    The public keys contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificates - -
    -
    -
    -
    -
    -
    -

    The SecCertificates contained i self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificates: [SecCertificate] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - certificateData - -
    -
    -
    -
    -
    -
    -

    The Data values for all certificates contained in self.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var certificateData: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates self after applying SecPolicy.af.default. This evaluation does not validate the hostname.

    -
    -

    Throws

    - An AFError.serverTrustEvaluationFailed instance with a .defaultEvaluationFailed reason. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performDefaultValidation(forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The hostname, used only in the error output if validation fails.

    -
    -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Validates self after applying SecPolicy.af.hostname(host), which performs the default validation as well as -hostname validation.

    -
    -

    Throws

    - An AFError.serverTrustEvaluationFailed instance with a .defaultEvaluationFailed reason. - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    func performValidation(forHost host: String) throws
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - host - - -
    -

    The hostname to use in the validation.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy instance which will validate server certificates but not require a host name match.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let `default`: SecPolicy
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - hostname(_:) - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy instance which will validate server certificates and much match the provided hostname.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func hostname(_ hostname: String) -> SecPolicy
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - hostname - - -
    -

    The hostname to validate against.

    -
    -
    -
    -
    -

    Return Value

    -

    The SecPolicy.

    -
    -
    -
    -
  • -
  • -
    - - - - revocation(options:) - -
    -
    -
    -
    -
    -
    -

    Creates a SecPolicy which checks the revocation of certificates.

    -
    -

    Throws

    -

    An AFError.serverTrustEvaluationFailed error with reason .revocationPolicyCreationFailed - if the policy cannot be created.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - options - - -
    -

    The RevocationTrustEvaluator.Options for evaluation.

    -
    -
    -
    -
    -

    Return Value

    -

    The SecPolicy.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    All Data values for the contained SecCertificates.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var data: [Data] { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - publicKeys - -
    -
    -
    -
    -
    -
    -

    All public SecKey values for the contained SecCertificates.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKeys: [SecKey] { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - publicKey - -
    -
    -
    -
    -
    -
    -

    The public key for self, if it can be extracted.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var publicKey: SecKey? { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns whether self is errSecSuccess.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - isSuccess - -
    -
    -
    -
    -
    -
    -

    Returns whether self is.unspecifiedor.proceed`.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    var isSuccess: Bool { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Alamofire’s default configuration. Same as URLSessionConfiguration.default but adds Alamofire default -Accept-Language, Accept-Encoding, and User-Agent headers.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: URLSessionConfiguration { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DataResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DataResponse.html deleted file mode 100644 index 36cdb48..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DataResponse.html +++ /dev/null @@ -1,1071 +0,0 @@ - - - - DataResponse Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DataResponse

-
-
-
public struct DataResponse<Success, Failure> where Failure : Error
- -
-
-

Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The URL request sent to the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let request: URLRequest?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    The server’s response to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let response: HTTPURLResponse?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - data - -
    -
    -
    -
    -
    -
    -

    The data returned by the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let data: Data?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    The final metrics of the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let metrics: URLSessionTaskMetrics?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationDuration - -
    -
    -
    -
    -
    -
    -

    The time taken to serialize the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationDuration: TimeInterval
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: Result<Success, Failure>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value of the result if it is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Success? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result if it is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Failure? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a DataResponse instance with the specified parameters derived from the response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(request: URLRequest?,
    -            response: HTTPURLResponse?,
    -            data: Data?,
    -            metrics: URLSessionTaskMetrics?,
    -            serializationDuration: TimeInterval,
    -            result: Result<Success, Failure>)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    The URLRequest sent to the server.

    -
    -
    - - response - - -
    -

    The HTTPURLResponse from the server.

    -
    -
    - - data - - -
    -

    The Data returned by the server.

    -
    -
    - - metrics - - -
    -

    The URLSessionTaskMetrics of the DataRequest or UploadRequest.

    -
    -
    - - serializationDuration - - -
    -

    The duration taken by serialization.

    -
    -
    - - result - - -
    -

    The Result of response serialization.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes the URL request, the URL -response, the server data, the duration of the network and serialization actions, and the response serialization -result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the result of this DataResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleInt = possibleData.map { $0.count }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse whose result wraps the value returned by the given closure. If this instance’s - result is a failure, returns a response wrapping the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DataResponse is a success, passing the unwrapped result -value as a parameter.

    - -

    Use the tryMap method with a closure that may throw an error. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleObject = possibleData.tryMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A success or failure DataResponse depending on the result of the given closure. If this instance’s - result is a failure, returns the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let withMyError = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the tryMapError function with a closure that may throw an error. For example:

    -
    let possibleData: DataResponse<Data> = ...
    -let possibleObject = possibleData.tryMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMapError<NewFailure>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DataResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DownloadResponse.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DownloadResponse.html deleted file mode 100644 index 4a59706..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/DownloadResponse.html +++ /dev/null @@ -1,1123 +0,0 @@ - - - - DownloadResponse Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

DownloadResponse

-
-
-
public struct DownloadResponse<Success, Failure> where Failure : Error
- -
-
-

Used to store all data associated with a serialized response of a download request.

- -
-
- -
-
-
-
    -
  • -
    - - - - request - -
    -
    -
    -
    -
    -
    -

    The URL request sent to the server.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let request: URLRequest?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - response - -
    -
    -
    -
    -
    -
    -

    The server’s response to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let response: HTTPURLResponse?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - fileURL - -
    -
    -
    -
    -
    -
    -

    The final destination URL of the data returned from the server after it is moved.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let fileURL: URL?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - resumeData - -
    -
    -
    -
    -
    -
    -

    The resume data generated if the request was cancelled.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let resumeData: Data?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - metrics - -
    -
    -
    -
    -
    -
    -

    The final metrics of the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let metrics: URLSessionTaskMetrics?
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - serializationDuration - -
    -
    -
    -
    -
    -
    -

    The time taken to serialize the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let serializationDuration: TimeInterval
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - result - -
    -
    -
    -
    -
    -
    -

    The result of response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let result: Result<Success, Failure>
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Returns the associated value of the result if it is a success, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var value: Success? { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - error - -
    -
    -
    -
    -
    -
    -

    Returns the associated error value if the result if it is a failure, nil otherwise.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var error: Failure? { get }
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a DownloadResponse instance with the specified parameters derived from response serialization.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(request: URLRequest?,
    -            response: HTTPURLResponse?,
    -            fileURL: URL?,
    -            resumeData: Data?,
    -            metrics: URLSessionTaskMetrics?,
    -            serializationDuration: TimeInterval,
    -            result: Result<Success, Failure>)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - request - - -
    -

    The URLRequest sent to the server.

    -
    -
    - - response - - -
    -

    The HTTPURLResponse from the server.

    -
    -
    - - temporaryURL - - -
    -

    The temporary destination URL of the data returned from the server.

    -
    -
    - - destinationURL - - -
    -

    The final destination URL of the data returned from the server, if it was moved.

    -
    -
    - - resumeData - - -
    -

    The resume Data generated if the request was cancelled.

    -
    -
    - - metrics - - -
    -

    The URLSessionTaskMetrics of the DownloadRequest.

    -
    -
    - - serializationDuration - - -
    -

    The duration taken by serialization.

    -
    -
    - - result - - -
    -

    The Result of response serialization.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    -

    The textual representation used when written to an output stream, which includes whether the result was a -success or failure.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - debugDescription - -
    -
    -
    -
    -
    -
    -

    The debug textual representation used when written to an output stream, which includes the URL request, the URL -response, the temporary and destination URLs, the resume data, the durations of the network and serialization -actions, and the response serialization result.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var debugDescription: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - map(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the map method with a closure that does not throw. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleInt = possibleData.map { $0.count }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse whose result wraps the value returned by the given closure. If this instance’s - result is a failure, returns a response wrapping the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMap(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped -result value as a parameter.

    - -

    Use the tryMap method with a closure that may throw an error. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleObject = possibleData.tryMap {
    -    try JSONSerialization.jsonObject(with: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error>
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the success value of the instance’s result.

    -
    -
    -
    -
    -

    Return Value

    -

    A success or failure DownloadResponse depending on the result of the given closure. If this -instance’s result is a failure, returns the same failure.

    -
    -
    -
    -
  • -
  • -
    - - - - mapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the mapError function with a closure that does not throw. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let withMyError = possibleData.mapError { MyError.error($0) }
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
  • -
    - - - - tryMapError(_:) - -
    -
    -
    -
    -
    -
    -

    Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

    - -

    Use the tryMapError function with a closure that may throw an error. For example:

    -
    let possibleData: DownloadResponse<Data> = ...
    -let possibleObject = possibleData.tryMapError {
    -    try someFailableFunction(taking: $0)
    -}
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func tryMapError<NewFailure>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> where NewFailure : Error
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - transform - - -
    -

    A throwing closure that takes the error of the instance.

    -
    -
    -
    -
    -

    Return Value

    -

    A DownloadResponse instance containing the result of the transform.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Empty.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Empty.html deleted file mode 100644 index f1643f7..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Empty.html +++ /dev/null @@ -1,515 +0,0 @@ - - - - Empty Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Empty

-
-
-
public struct Empty : Decodable
- -
-
-

Type representing an empty response. Use Empty.value to get the static instance.

- -
-
- -
-
-
-
    -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Static Empty instance used for all Empty responses.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let value: Empty
    - -
    -
    -
    -
    -
  • -
-
-
-
- - - -

Empty

-
-
-
    -
  • -
    - - - - emptyValue() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func emptyValue() -> Empty
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/GoogleXSSIPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/GoogleXSSIPreprocessor.html deleted file mode 100644 index 9ee4520..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/GoogleXSSIPreprocessor.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - GoogleXSSIPreprocessor Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

GoogleXSSIPreprocessor

-
-
-
public struct GoogleXSSIPreprocessor : DataPreprocessor
- -
-
-

DataPreprocessor that trims Google’s typical )]}',\n XSSI JSON header.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeader.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeader.html deleted file mode 100644 index d27ba71..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeader.html +++ /dev/null @@ -1,1238 +0,0 @@ - - - - HTTPHeader Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPHeader

-
-
-
public struct HTTPHeader : Hashable
- -
-
-

A representation of a single HTTP header’s name / value pair.

- -
-
- -
-
-
-
    -
  • -
    - - - - name - -
    -
    -
    -
    -
    -
    -

    Name of the header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let name: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - value - -
    -
    -
    -
    -
    -
    -

    Value of the header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let value: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(name:value:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from the given name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The name of the header.

    -
    -
    - - value - - -
    -

    The value of the header.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - accept(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func accept(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptCharset(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Charset header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptCharset(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Charset value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptLanguage(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Language header.

    - -

    Alamofire offers a default Accept-Language header that accumulates and encodes the system’s preferred languages. -Use HTTPHeader.defaultAcceptLanguage.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptLanguage(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Language value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - acceptEncoding(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Accept-Encoding header.

    - -

    Alamofire offers a default accept encoding value that provides the most common values. Use -HTTPHeader.defaultAcceptEncoding.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func acceptEncoding(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Accept-Encoding value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Basic Authorization header using the username and password provided.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(username: String, password: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - username - - -
    -

    The username of the header.

    -
    -
    - - password - - -
    -

    The password of the header.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Bearer Authorization header using the bearerToken provided

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(bearerToken: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - bearerToken - - -
    -

    The bearer token.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - authorization(_:) - -
    -
    -
    -
    -
    -
    -

    Returns an Authorization header.

    - -

    Alamofire provides built-in methods to produce Authorization headers. For a Basic Authorization header use -HTTPHeader.authorization(username:password:). For a Bearer Authorization header, use -HTTPHeader.authorization(bearerToken:).

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func authorization(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Authorization value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Returns a Content-Disposition header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func contentDisposition(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Content-Disposition value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - contentType(_:) - -
    -
    -
    -
    -
    -
    -

    Returns a Content-Type header.

    - -

    All Alamofire ParameterEncodings and ParameterEncoders set the Content-Type of the request, so it may not be necessary to manually -set this value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func contentType(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The Content-Type value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
  • -
    - - - - userAgent(_:) - -
    -
    -
    -
    -
    -
    -

    Returns a User-Agent header.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static func userAgent(_ value: String) -> HTTPHeader
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - value - - -
    -

    The User-Agent value.

    -
    -
    -
    -
    -

    Return Value

    -

    The header.

    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - defaultAcceptEncoding - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default Accept-Encoding header, appropriate for the encodings supported by particular OS -versions.

    - -

    See the Accept-Encoding HTTP header documentation .

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultAcceptEncoding: HTTPHeader
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultAcceptLanguage - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default Accept-Language header, generated by querying Locale for the user’s -preferredLanguages.

    - -

    See the Accept-Language HTTP header documentation.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultAcceptLanguage: HTTPHeader
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - defaultUserAgent - -
    -
    -
    -
    -
    -
    -

    Returns Alamofire’s default User-Agent header.

    - -

    See the User-Agent header documentation.

    - -

    Example: iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let defaultUserAgent: HTTPHeader
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeaders.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeaders.html deleted file mode 100644 index a54387b..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPHeaders.html +++ /dev/null @@ -1,1238 +0,0 @@ - - - - HTTPHeaders Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPHeaders

-
-
-
public struct HTTPHeaders
- -
-
-

An order-preserving and case-insensitive representation of HTTP headers.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Creates an empty instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from an array of HTTPHeaders. Duplicate case-insensitive names are collapsed into the last -name and value encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ headers: [HTTPHeader])
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(_:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance from a [String: String]. Duplicate case-insensitive names are collapsed into the last name -and value encountered.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(_ dictionary: [String : String])
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - add(name:value:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func add(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The HTTPHeader name.

    -
    -
    - - value - - -
    -

    The `HTTPHeader value.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - add(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends the provided HTTPHeader into the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func add(_ header: HTTPHeader)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - header - - -
    -

    The HTTPHeader to update or append.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - update(name:value:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func update(name: String, value: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - name - - -
    -

    The HTTPHeader name.

    -
    -
    - - value - - -
    -

    The `HTTPHeader value.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - update(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively updates or appends the provided HTTPHeader into the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func update(_ header: HTTPHeader)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - header - - -
    -

    The HTTPHeader to update or append.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - remove(name:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively removes an HTTPHeader, if it exists, from the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func remove(name: String)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the HTTPHeader to remove.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - sort() - -
    -
    -
    -
    -
    -
    -

    Sort the current instance by header name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public mutating func sort()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - sorted() - -
    -
    -
    -
    -
    -
    -

    Returns an instance sorted by header name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func sorted() -> HTTPHeaders
    - -
    -
    -
    -

    Return Value

    -

    A copy of the current instance sorted by name.

    -
    -
    -
    -
  • -
  • -
    - - - - value(for:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively find a header’s value by name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func value(for name: String) -> String?
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the header to search for, case-insensitively.

    -
    -
    -
    -
    -

    Return Value

    -

    The value of header, if it exists.

    -
    -
    -
    -
  • -
  • -
    - - - - subscript(_:) - -
    -
    -
    -
    -
    -
    -

    Case-insensitively access the header with the given name.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public subscript(name: String) -> String? { get set }
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - name - - -
    -

    The name of the header.

    -
    -
    -
    -
    -
    -
  • -
  • -
    - - - - dictionary - -
    -
    -
    -
    -
    -
    -

    The dictionary representation of all headers.

    - -

    This representation does not preserve the current order of the instance.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var dictionary: [String : String] { get }
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(dictionaryLiteral elements: (String, String)...)
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - makeIterator() - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func makeIterator() -> IndexingIterator<[HTTPHeader]>
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - startIndex - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var startIndex: Int { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - endIndex - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var endIndex: Int { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - subscript(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public subscript(position: Int) -> HTTPHeader { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - index(after:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func index(after i: Int) -> Int
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - description - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public var description: String { get }
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    The default set of HTTPHeaders used by Alamofire. Includes Accept-Encoding, Accept-Language, and -User-Agent.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    static let `default`: HTTPHeaders
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPMethod.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPMethod.html deleted file mode 100644 index 512f9be..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/HTTPMethod.html +++ /dev/null @@ -1,749 +0,0 @@ - - - - HTTPMethod Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

HTTPMethod

-
-
-
public struct HTTPMethod : RawRepresentable, Equatable, Hashable
- -
-
-

Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so -HTTPMethod.get != HTTPMethod(rawValue: "get").

- -

See https://tools.ietf.org/html/rfc7231#section-4.3

- -
-
- -
-
-
-
    -
  • -
    - - - - connect - -
    -
    -
    -
    -
    -
    -

    CONNECT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let connect: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - delete - -
    -
    -
    -
    -
    -
    -

    DELETE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let delete: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - get - -
    -
    -
    -
    -
    -
    -

    GET method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let get: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - head - -
    -
    -
    -
    -
    -
    -

    HEAD method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let head: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    OPTIONS method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let options: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - patch - -
    -
    -
    -
    -
    -
    -

    PATCH method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let patch: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - post - -
    -
    -
    -
    -
    -
    -

    POST method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let post: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - put - -
    -
    -
    -
    -
    -
    -

    PUT method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let put: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - trace - -
    -
    -
    -
    -
    -
    -

    TRACE method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let trace: HTTPMethod
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - rawValue - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let rawValue: String
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(rawValue:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(rawValue: String)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/JSONEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/JSONEncoding.html deleted file mode 100644 index 98a6069..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/JSONEncoding.html +++ /dev/null @@ -1,701 +0,0 @@ - - - - JSONEncoding Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

JSONEncoding

-
-
-
public struct JSONEncoding : ParameterEncoding
- -
-
-

Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the -request. The Content-Type HTTP header field of an encoded request is set to application/json.

- -
-
- -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns a JSONEncoding instance with default writing options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: JSONEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - prettyPrinted - -
    -
    -
    -
    -
    -
    -

    Returns a JSONEncoding instance with .prettyPrinted writing options.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var prettyPrinted: JSONEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - options - -
    -
    -
    -
    -
    -
    -

    The options for writing the parameters as JSON data.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let options: JSONSerialization.WritingOptions
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - init(options:) - -
    -
    -
    -
    -
    -
    -

    Creates an instance using the specified WritingOptions.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(options: JSONSerialization.WritingOptions = [])
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - options - - -
    -

    JSONSerialization.WritingOptions to use.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Encodes any JSON compatible object into a URLRequest.

    -
    -

    Throws

    -

    Any Error produced during encoding.

    - -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - urlRequest - - -
    -

    URLRequestConvertible value into which the object will be encoded.

    -
    -
    - - jsonObject - - -
    -

    Any value (must be JSON compatibleto be encoded into theURLRequest.nil` by default.

    -
    -
    -
    -
    -

    Return Value

    -

    The encoded URLRequest.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/PassthroughPreprocessor.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/PassthroughPreprocessor.html deleted file mode 100644 index fc44f37..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/PassthroughPreprocessor.html +++ /dev/null @@ -1,504 +0,0 @@ - - - - PassthroughPreprocessor Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

PassthroughPreprocessor

-
-
-
public struct PassthroughPreprocessor : DataPreprocessor
- -
-
-

DataPreprocessor that returns passed Data without any transform.

- -
-
- -
-
-
-
    -
  • -
    - - - - init() - -
    -
    -
    -
    -
    -
    -

    Undocumented

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init()
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - preprocess(_:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func preprocess(_ data: Data) throws -> Data
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector.html deleted file mode 100644 index 0704e9c..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector.html +++ /dev/null @@ -1,639 +0,0 @@ - - - - Redirector Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Redirector

-
-
-
public struct Redirector
- -
-
-

Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

- -
-
- -
-
-
-
    -
  • -
    - - - - Behavior - -
    -
    -
    -
    -
    -
    -

    Defines the behavior of the Redirector type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - follow - -
    -
    -
    -
    -
    -
    -

    Returns a Redirector with a .follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let follow: Redirector
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotFollow - -
    -
    -
    -
    -
    -
    -

    Returns a Redirector with a .doNotFollow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let doNotFollow: Redirector
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - behavior - -
    -
    -
    -
    -
    -
    -

    The Behavior of the Redirector.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let behavior: Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(behavior:) - -
    -
    -
    -
    -
    -
    -

    Creates a Redirector instance from the Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(behavior: Behavior)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - behavior - - -
    -

    The Behavior.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func task(_ task: URLSessionTask,
    -                 willBeRedirectedTo request: URLRequest,
    -                 for response: HTTPURLResponse,
    -                 completion: @escaping (URLRequest?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector/Behavior.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector/Behavior.html deleted file mode 100644 index 9e1f452..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/Redirector/Behavior.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - Behavior Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Behavior

-
-
-
public enum Behavior
- -
-
-

Defines the behavior of the Redirector type.

- -
-
- -
-
-
-
    -
  • -
    - - - - follow - -
    -
    -
    -
    -
    -
    -

    Follow the redirect as defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case follow
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotFollow - -
    -
    -
    -
    -
    -
    -

    Do not follow the redirect defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotFollow
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - modify(_:) - -
    -
    -
    -
    -
    -
    -

    Modify the redirect request defined in the response.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher.html deleted file mode 100644 index a7f7a11..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher.html +++ /dev/null @@ -1,639 +0,0 @@ - - - - ResponseCacher Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ResponseCacher

-
-
-
public struct ResponseCacher
- -
-
-

ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached -response.

- -
-
- -
-
-
-
    -
  • -
    - - - - Behavior - -
    -
    -
    -
    -
    -
    -

    Defines the behavior of the ResponseCacher type.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - cache - -
    -
    -
    -
    -
    -
    -

    Returns a ResponseCacher with a follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let cache: ResponseCacher
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotCache - -
    -
    -
    -
    -
    -
    -

    Returns a ResponseCacher with a do not follow Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static let doNotCache: ResponseCacher
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - behavior - -
    -
    -
    -
    -
    -
    -

    The Behavior of the ResponseCacher.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let behavior: Behavior
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - init(behavior:) - -
    -
    -
    -
    -
    -
    -

    Creates a ResponseCacher instance from the Behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(behavior: Behavior)
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - behavior - - -
    -

    The Behavior.

    -
    -
    -
    -
    -
    -
  • -
-
-
-
    -
  • - -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func dataTask(_ task: URLSessionDataTask,
    -                     willCacheResponse response: CachedURLResponse,
    -                     completion: @escaping (CachedURLResponse?) -> Void)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher/Behavior.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher/Behavior.html deleted file mode 100644 index 66d2691..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/ResponseCacher/Behavior.html +++ /dev/null @@ -1,532 +0,0 @@ - - - - Behavior Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Behavior

-
-
-
public enum Behavior
- -
-
-

Defines the behavior of the ResponseCacher type.

- -
-
- -
-
-
-
    -
  • -
    - - - - cache - -
    -
    -
    -
    -
    -
    -

    Stores the cached response in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case cache
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - doNotCache - -
    -
    -
    -
    -
    -
    -

    Prevents the cached response from being stored in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case doNotCache
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - modify(_:) - -
    -
    -
    -
    -
    -
    -

    Modifies the cached response before storing it in the cache.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding.html deleted file mode 100644 index b7b0ee5..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding.html +++ /dev/null @@ -1,962 +0,0 @@ - - - - URLEncoding Structure Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

URLEncoding

-
-
-
public struct URLEncoding : ParameterEncoding
- -
-
-

Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -the HTTP body depends on the destination of the encoding.

- -

The Content-Type HTTP header field of an encoded request with HTTP body is set to -application/x-www-form-urlencoded; charset=utf-8.

- -

There is no published specification for how to encode collection types. By default the convention of appending -[] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for -nested dictionary values (foo[bar]=baz) is used. Optionally, ArrayEncoding can be used to omit the -square brackets appended to array keys.

- -

BoolEncoding can be used to configure how boolean values are encoded. The default behavior is to encode -true as 1 and false as 0.

- -
-
- -
-
-
- -
    -
  • -
    - - - - Destination - -
    -
    -
    -
    -
    -
    -

    Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the -resulting URL request.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum Destination
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - ArrayEncoding - -
    -
    -
    -
    -
    -
    -

    Configures how Array parameters are encoded.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - BoolEncoding - -
    -
    -
    -
    -
    -
    -

    Configures how Bool parameters are encoded.

    - - See more -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public enum BoolEncoding
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - default - -
    -
    -
    -
    -
    -
    -

    Returns a default URLEncoding instance with a .methodDependent destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var `default`: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Returns a URLEncoding instance with a .queryString destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var queryString: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Returns a URLEncoding instance with an .httpBody destination.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public static var httpBody: URLEncoding { get }
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - destination - -
    -
    -
    -
    -
    -
    -

    The destination defining where the encoded query string is to be applied to the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let destination: Destination
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - arrayEncoding - -
    -
    -
    -
    -
    -
    -

    The encoding to use for Array parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let arrayEncoding: ArrayEncoding
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - boolEncoding - -
    -
    -
    -
    -
    -
    -

    The encoding to use for Bool parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public let boolEncoding: BoolEncoding
    - -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • - -
    -
    -
    -
    -
    -

    Creates an instance using the specified parameters.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public init(destination: Destination = .methodDependent,
    -            arrayEncoding: ArrayEncoding = .brackets,
    -            boolEncoding: BoolEncoding = .numeric)
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - - - - - -
    - - destination - - -
    -

    Destination defining where the encoded query string will be applied. .methodDependent by - default.

    -
    -
    - - arrayEncoding - - -
    -

    ArrayEncoding to use. .brackets by default.

    -
    -
    - - boolEncoding - - -
    -

    BoolEncoding to use. .numeric by default.

    -
    -
    -
    -
    -
    -
  • -
-
-
- -
    -
  • -
    - - - - encode(_:with:) - -
    -
    -
    -
    -
    -
    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
    - -
    -
    -
    -
    -
  • -
  • - -
    -
    -
    -
    -
    -

    Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func queryComponents(fromKey key: String, value: Any) -> [(String, String)]
    - -
    -
    -
    -

    Parameters

    - - - - - - - - - - - -
    - - key - - -
    -

    Key of the query component.

    -
    -
    - - value - - -
    -

    Value of the query component.

    -
    -
    -
    -
    -

    Return Value

    -

    The percent-escaped, URL encoded query string components.

    -
    -
    -
    -
  • -
  • -
    - - - - escape(_:) - -
    -
    -
    -
    -
    -
    -

    Creates a percent-escaped string following RFC 3986 for a query string key or value.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public func escape(_ string: String) -> String
    - -
    -
    -
    -

    Parameters

    - - - - - - - -
    - - string - - -
    -

    String to be percent-escaped.

    -
    -
    -
    -
    -

    Return Value

    -

    The percent-escaped String.

    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/ArrayEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/ArrayEncoding.html deleted file mode 100644 index e56c1d4..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/ArrayEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - ArrayEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

ArrayEncoding

-
-
-
public enum ArrayEncoding
- -
-
-

Configures how Array parameters are encoded.

- -
-
- -
-
-
-
    -
  • -
    - - - - brackets - -
    -
    -
    -
    -
    -
    -

    An empty set of square brackets is appended to the key for every value. This is the default behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case brackets
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - noBrackets - -
    -
    -
    -
    -
    -
    -

    No brackets are appended. The key is encoded as is.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case noBrackets
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/BoolEncoding.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/BoolEncoding.html deleted file mode 100644 index 135d90e..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/BoolEncoding.html +++ /dev/null @@ -1,505 +0,0 @@ - - - - BoolEncoding Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

BoolEncoding

-
-
-
public enum BoolEncoding
- -
-
-

Configures how Bool parameters are encoded.

- -
-
- -
-
-
-
    -
  • -
    - - - - numeric - -
    -
    -
    -
    -
    -
    -

    Encode true as 1 and false as 0. This is the default behavior.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case numeric
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - literal - -
    -
    -
    -
    -
    -
    -

    Encode true and false as string literals.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case literal
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/Destination.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/Destination.html deleted file mode 100644 index 6511875..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Structs/URLEncoding/Destination.html +++ /dev/null @@ -1,534 +0,0 @@ - - - - Destination Enumeration Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Destination

-
-
-
public enum Destination
- -
-
-

Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the -resulting URL request.

- -
-
- -
-
-
-
    -
  • -
    - - - - methodDependent - -
    -
    -
    -
    -
    -
    -

    Applies encoded query string result to existing query string for GET, HEAD and DELETE requests and -sets as the HTTP body for requests with any other HTTP method.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case methodDependent
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - queryString - -
    -
    -
    -
    -
    -
    -

    Sets or appends encoded query string result to existing query string.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case queryString
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - httpBody - -
    -
    -
    -
    -
    -
    -

    Sets encoded query string result as the HTTP body of the URL request.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    case httpBody
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Typealiases.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Typealiases.html deleted file mode 100644 index 2b6f748..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/Typealiases.html +++ /dev/null @@ -1,619 +0,0 @@ - - - - Type Aliases Reference - - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
-

Type Aliases

-

The following type aliases are available globally.

- -
-
- -
-
-
-
    -
  • -
    - - - - Parameters - -
    -
    -
    -
    -
    -
    -

    A dictionary of parameters to apply to a URLRequest.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias Parameters = [String : Any]
    - -
    -
    -
    -
    -
  • -
-
-
-
    -
  • -
    - - - - AdaptHandler - -
    -
    -
    -
    -
    -
    -

    RequestAdapter closure definition.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result<URLRequest, Error>) -> Void) -> Void
    - -
    -
    -
    -
    -
  • -
  • -
    - - - - RetryHandler - -
    -
    -
    -
    -
    -
    -

    RequestRetrier closure definition.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
    - -
    -
    -
    -
    -
  • -
-
-
- -
-
-
    -
  • -
    - - - - AFResult - -
    -
    -
    -
    -
    -
    -

    Default type of Result returned by Alamofire, with an AFError Failure type.

    - -
    -
    -

    Declaration

    -
    -

    Swift

    -
    public typealias AFResult<Success> = Result<Success, AFError>
    - -
    -
    -
    -
    -
  • -
-
-
-
- -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/badge.svg b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/badge.svg deleted file mode 100644 index f47d948..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/badge.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - documentation - - - documentation - - - 98% - - - 98% - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/highlight.css b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/highlight.css deleted file mode 100644 index d0db0e1..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/highlight.css +++ /dev/null @@ -1,200 +0,0 @@ -/* Credit to https://gist.github.com/wataru420/2048287 */ -.highlight { - /* Comment */ - /* Error */ - /* Keyword */ - /* Operator */ - /* Comment.Multiline */ - /* Comment.Preproc */ - /* Comment.Single */ - /* Comment.Special */ - /* Generic.Deleted */ - /* Generic.Deleted.Specific */ - /* Generic.Emph */ - /* Generic.Error */ - /* Generic.Heading */ - /* Generic.Inserted */ - /* Generic.Inserted.Specific */ - /* Generic.Output */ - /* Generic.Prompt */ - /* Generic.Strong */ - /* Generic.Subheading */ - /* Generic.Traceback */ - /* Keyword.Constant */ - /* Keyword.Declaration */ - /* Keyword.Pseudo */ - /* Keyword.Reserved */ - /* Keyword.Type */ - /* Literal.Number */ - /* Literal.String */ - /* Name.Attribute */ - /* Name.Builtin */ - /* Name.Class */ - /* Name.Constant */ - /* Name.Entity */ - /* Name.Exception */ - /* Name.Function */ - /* Name.Namespace */ - /* Name.Tag */ - /* Name.Variable */ - /* Operator.Word */ - /* Text.Whitespace */ - /* Literal.Number.Float */ - /* Literal.Number.Hex */ - /* Literal.Number.Integer */ - /* Literal.Number.Oct */ - /* Literal.String.Backtick */ - /* Literal.String.Char */ - /* Literal.String.Doc */ - /* Literal.String.Double */ - /* Literal.String.Escape */ - /* Literal.String.Heredoc */ - /* Literal.String.Interpol */ - /* Literal.String.Other */ - /* Literal.String.Regex */ - /* Literal.String.Single */ - /* Literal.String.Symbol */ - /* Name.Builtin.Pseudo */ - /* Name.Variable.Class */ - /* Name.Variable.Global */ - /* Name.Variable.Instance */ - /* Literal.Number.Integer.Long */ } - .highlight .c { - color: #999988; - font-style: italic; } - .highlight .err { - color: #a61717; - background-color: #e3d2d2; } - .highlight .k { - color: #000000; - font-weight: bold; } - .highlight .o { - color: #000000; - font-weight: bold; } - .highlight .cm { - color: #999988; - font-style: italic; } - .highlight .cp { - color: #999999; - font-weight: bold; } - .highlight .c1 { - color: #999988; - font-style: italic; } - .highlight .cs { - color: #999999; - font-weight: bold; - font-style: italic; } - .highlight .gd { - color: #000000; - background-color: #ffdddd; } - .highlight .gd .x { - color: #000000; - background-color: #ffaaaa; } - .highlight .ge { - color: #000000; - font-style: italic; } - .highlight .gr { - color: #aa0000; } - .highlight .gh { - color: #999999; } - .highlight .gi { - color: #000000; - background-color: #ddffdd; } - .highlight .gi .x { - color: #000000; - background-color: #aaffaa; } - .highlight .go { - color: #888888; } - .highlight .gp { - color: #555555; } - .highlight .gs { - font-weight: bold; } - .highlight .gu { - color: #aaaaaa; } - .highlight .gt { - color: #aa0000; } - .highlight .kc { - color: #000000; - font-weight: bold; } - .highlight .kd { - color: #000000; - font-weight: bold; } - .highlight .kp { - color: #000000; - font-weight: bold; } - .highlight .kr { - color: #000000; - font-weight: bold; } - .highlight .kt { - color: #445588; } - .highlight .m { - color: #009999; } - .highlight .s { - color: #d14; } - .highlight .na { - color: #008080; } - .highlight .nb { - color: #0086B3; } - .highlight .nc { - color: #445588; - font-weight: bold; } - .highlight .no { - color: #008080; } - .highlight .ni { - color: #800080; } - .highlight .ne { - color: #990000; - font-weight: bold; } - .highlight .nf { - color: #990000; } - .highlight .nn { - color: #555555; } - .highlight .nt { - color: #000080; } - .highlight .nv { - color: #008080; } - .highlight .ow { - color: #000000; - font-weight: bold; } - .highlight .w { - color: #bbbbbb; } - .highlight .mf { - color: #009999; } - .highlight .mh { - color: #009999; } - .highlight .mi { - color: #009999; } - .highlight .mo { - color: #009999; } - .highlight .sb { - color: #d14; } - .highlight .sc { - color: #d14; } - .highlight .sd { - color: #d14; } - .highlight .s2 { - color: #d14; } - .highlight .se { - color: #d14; } - .highlight .sh { - color: #d14; } - .highlight .si { - color: #d14; } - .highlight .sx { - color: #d14; } - .highlight .sr { - color: #009926; } - .highlight .s1 { - color: #d14; } - .highlight .ss { - color: #990073; } - .highlight .bp { - color: #999999; } - .highlight .vc { - color: #008080; } - .highlight .vg { - color: #008080; } - .highlight .vi { - color: #008080; } - .highlight .il { - color: #009999; } diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/jazzy.css b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/jazzy.css deleted file mode 100644 index 833be0d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/css/jazzy.css +++ /dev/null @@ -1,378 +0,0 @@ -*, *:before, *:after { - box-sizing: inherit; } - -body { - margin: 0; - background: #fff; - color: #333; - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - letter-spacing: .2px; - -webkit-font-smoothing: antialiased; - box-sizing: border-box; } - -h1 { - font-size: 2rem; - font-weight: 700; - margin: 1.275em 0 0.6em; } - -h2 { - font-size: 1.75rem; - font-weight: 700; - margin: 1.275em 0 0.3em; } - -h3 { - font-size: 1.5rem; - font-weight: 700; - margin: 1em 0 0.3em; } - -h4 { - font-size: 1.25rem; - font-weight: 700; - margin: 1.275em 0 0.85em; } - -h5 { - font-size: 1rem; - font-weight: 700; - margin: 1.275em 0 0.85em; } - -h6 { - font-size: 1rem; - font-weight: 700; - margin: 1.275em 0 0.85em; - color: #777; } - -p { - margin: 0 0 1em; } - -ul, ol { - padding: 0 0 0 2em; - margin: 0 0 0.85em; } - -blockquote { - margin: 0 0 0.85em; - padding: 0 15px; - color: #858585; - border-left: 4px solid #e5e5e5; } - -img { - max-width: 100%; } - -a { - color: #4183c4; - text-decoration: none; } - a:hover, a:focus { - outline: 0; - text-decoration: underline; } - a.discouraged { - text-decoration: line-through; } - a.discouraged:hover, a.discouraged:focus { - text-decoration: underline line-through; } - -table { - background: #fff; - width: 100%; - border-collapse: collapse; - border-spacing: 0; - overflow: auto; - margin: 0 0 0.85em; } - -tr:nth-child(2n) { - background-color: #fbfbfb; } - -th, td { - padding: 6px 13px; - border: 1px solid #ddd; } - -pre { - margin: 0 0 1.275em; - padding: .85em 1em; - overflow: auto; - background: #f7f7f7; - font-size: .85em; - font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; } - -code { - font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; } - -p > code, li > code { - background: #f7f7f7; - padding: .2em; } - p > code:before, p > code:after, li > code:before, li > code:after { - letter-spacing: -.2em; - content: "\00a0"; } - -pre code { - padding: 0; - white-space: pre; } - -.content-wrapper { - display: flex; - flex-direction: column; } - @media (min-width: 768px) { - .content-wrapper { - flex-direction: row; } } - -.header { - display: flex; - padding: 8px; - font-size: 0.875em; - background: #444; - color: #999; } - -.header-col { - margin: 0; - padding: 0 8px; } - -.header-col--primary { - flex: 1; } - -.header-link { - color: #fff; } - -.header-icon { - padding-right: 6px; - vertical-align: -4px; - height: 16px; } - -.breadcrumbs { - font-size: 0.875em; - padding: 8px 16px; - margin: 0; - background: #fbfbfb; - border-bottom: 1px solid #ddd; } - -.carat { - height: 10px; - margin: 0 5px; } - -.navigation { - order: 2; } - @media (min-width: 768px) { - .navigation { - order: 1; - width: 25%; - max-width: 300px; - padding-bottom: 64px; - overflow: hidden; - word-wrap: normal; - background: #fbfbfb; - border-right: 1px solid #ddd; } } - -.nav-groups { - list-style-type: none; - padding-left: 0; } - -.nav-group-name { - border-bottom: 1px solid #ddd; - padding: 8px 0 8px 16px; } - -.nav-group-name-link { - color: #333; } - -.nav-group-tasks { - margin: 8px 0; - padding: 0 0 0 8px; } - -.nav-group-task { - font-size: 1em; - list-style-type: none; - white-space: nowrap; } - -.nav-group-task-link { - color: #808080; } - -.main-content { - order: 1; } - @media (min-width: 768px) { - .main-content { - order: 2; - flex: 1; - padding-bottom: 60px; } } - -.section { - padding: 0 32px; - border-bottom: 1px solid #ddd; } - -.section-content { - max-width: 834px; - margin: 0 auto; - padding: 16px 0; } - -.section-name { - color: #666; - display: block; } - -.declaration .highlight { - overflow-x: initial; - padding: 8px 0; - margin: 0; - background-color: transparent; - border: none; } - -.task-group-section { - border-top: 1px solid #ddd; } - -.task-group { - padding-top: 0px; } - -.task-name-container a[name]:before { - content: ""; - display: block; } - -.item-container { - padding: 0; } - -.item { - padding-top: 8px; - width: 100%; - list-style-type: none; } - .item a[name]:before { - content: ""; - display: block; } - .item .token, .item .direct-link { - padding-left: 3px; - margin-left: 0px; - font-size: 1rem; } - .item .declaration-note { - font-size: .85em; - color: #808080; - font-style: italic; } - -.pointer-container { - border-bottom: 1px solid #ddd; - left: -23px; - padding-bottom: 13px; - position: relative; - width: 110%; } - -.pointer { - left: 21px; - top: 7px; - display: block; - position: absolute; - width: 12px; - height: 12px; - border-left: 1px solid #ddd; - border-top: 1px solid #ddd; - background: #fff; - transform: rotate(45deg); } - -.height-container { - display: none; - position: relative; - width: 100%; - overflow: hidden; } - .height-container .section { - background: #fff; - border: 1px solid #ddd; - border-top-width: 0; - padding-top: 10px; - padding-bottom: 5px; - padding: 8px 16px; } - -.aside, .language { - padding: 6px 12px; - margin: 12px 0; - border-left: 5px solid #dddddd; - overflow-y: hidden; } - .aside .aside-title, .language .aside-title { - font-size: 9px; - letter-spacing: 2px; - text-transform: uppercase; - padding-bottom: 0; - margin: 0; - color: #aaa; - -webkit-user-select: none; } - .aside p:last-child, .language p:last-child { - margin-bottom: 0; } - -.language { - border-left: 5px solid #cde9f4; } - .language .aside-title { - color: #4183c4; } - -.aside-warning, .aside-deprecated, .aside-unavailable { - border-left: 5px solid #ff6666; } - .aside-warning .aside-title, .aside-deprecated .aside-title, .aside-unavailable .aside-title { - color: #ff0000; } - -.graybox { - border-collapse: collapse; - width: 100%; } - .graybox p { - margin: 0; - word-break: break-word; - min-width: 50px; } - .graybox td { - border: 1px solid #ddd; - padding: 5px 25px 5px 10px; - vertical-align: middle; } - .graybox tr td:first-of-type { - text-align: right; - padding: 7px; - vertical-align: top; - word-break: normal; - width: 40px; } - -.slightly-smaller { - font-size: 0.9em; } - -.footer { - padding: 8px 16px; - background: #444; - color: #ddd; - font-size: 0.8em; } - .footer p { - margin: 8px 0; } - .footer a { - color: #fff; } - -html.dash .header, html.dash .breadcrumbs, html.dash .navigation { - display: none; } - -html.dash .height-container { - display: block; } - -form[role=search] input { - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - line-height: 24px; - padding: 0 10px; - margin: 0; - border: none; - border-radius: 1em; } - .loading form[role=search] input { - background: white url(../img/spinner.gif) center right 4px no-repeat; } - -form[role=search] .tt-menu { - margin: 0; - min-width: 300px; - background: #fbfbfb; - color: #333; - border: 1px solid #ddd; } - -form[role=search] .tt-highlight { - font-weight: bold; } - -form[role=search] .tt-suggestion { - font: 16px/1.7 "Helvetica Neue", Helvetica, Arial, sans-serif; - padding: 0 8px; } - form[role=search] .tt-suggestion span { - display: table-cell; - white-space: nowrap; } - form[role=search] .tt-suggestion .doc-parent-name { - width: 100%; - text-align: right; - font-weight: normal; - font-size: 0.9em; - padding-left: 16px; } - -form[role=search] .tt-suggestion:hover, -form[role=search] .tt-suggestion.tt-cursor { - cursor: pointer; - background-color: #4183c4; - color: #fff; } - -form[role=search] .tt-suggestion:hover .doc-parent-name, -form[role=search] .tt-suggestion.tt-cursor .doc-parent-name { - color: #fff; } diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/carat.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/carat.png deleted file mode 100755 index 29d2f7f..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/carat.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/dash.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/dash.png deleted file mode 100755 index 6f694c7..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/dash.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/gh.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/gh.png deleted file mode 100755 index 628da97..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/gh.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/spinner.gif b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/spinner.gif deleted file mode 100644 index e3038d0..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/img/spinner.gif and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/index.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/index.html deleted file mode 100644 index 24cfd10..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/index.html +++ /dev/null @@ -1,650 +0,0 @@ - - - - Alamofire Reference - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
- -

Alamofire: Elegant Networking in Swift

- -

Build Status -CocoaPods Compatible -Carthage Compatible -Platform -Twitter -Gitter -Open Source Helpers

- -

Alamofire is an HTTP networking library written in Swift.

- -

⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️ This documentation is out of date during the Alamofire 5 beta process.

- - -

Features

- -
    -
  • [x] Chainable Request / Response Methods
  • -
  • [x] URL / JSON / plist Parameter Encoding
  • -
  • [x] Upload File / Data / Stream / MultipartFormData
  • -
  • [x] Download File using Request or Resume Data
  • -
  • [x] Authentication with URLCredential
  • -
  • [x] HTTP Response Validation
  • -
  • [x] Upload and Download Progress Closures with Progress
  • -
  • [x] cURL Command Output
  • -
  • [x] Dynamically Adapt and Retry Requests
  • -
  • [x] TLS Certificate and Public Key Pinning
  • -
  • [x] Network Reachability
  • -
  • [x] Comprehensive Unit and Integration Test Coverage
  • -
  • [x] Complete Documentation
  • -
-

Component Libraries

- -

In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem.

- -
    -
  • AlamofireImage - An image library including image response serializers, UIImage and UIImageView extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
  • -
  • AlamofireNetworkActivityIndicator - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support URLSession instances not managed by Alamofire.
  • -
-

Requirements

- -
    -
  • iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • -
  • Xcode 10.2+
  • -
  • Swift 5+
  • -
-

Migration Guides

- - -

Communication

- - -

Installation

-

CocoaPods

- -

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

-
pod 'Alamofire', '~> 5.0.0-rc.3'
-
-

Carthage

- -

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

-
github "Alamofire/Alamofire" "5.0.0-rc.3"
-
-

Swift Package Manager

- -

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms.

- -

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift.

-
dependencies: [
-    .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0-rc.3")
-]
-
-

Manually

- -

If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

-

Embedded Framework

- -
    -
  • Open up Terminal, cd into your top-level project directory, and run the following command if your project is not initialized as a git repository:
  • -
-
  $ git init
-
- -
    -
  • Add Alamofire as a git submodule by running the following command:
  • -
-
  $ git submodule add https://github.com/Alamofire/Alamofire.git
-
- -
    -
  • Open the new Alamofire folder, and drag the Alamofire.xcodeproj into the Project Navigator of your application’s Xcode project.

    - -
    -

    It should appear nested underneath your application’s blue project icon. Whether it is above or below all the other Xcode groups does not matter.

    -
  • -
  • Select the Alamofire.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • -
  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the Targets heading in the sidebar.

  • -
  • In the tab bar at the top of that window, open the General panel.

  • -
  • Click on the + button under the Embedded Binaries section.

  • -
  • You will see two different Alamofire.xcodeproj folders each with two different versions of the Alamofire.framework nested inside a Products folder.

    - -
    -

    It does not matter which Products folder you choose from, but it does matter whether you choose the top or bottom Alamofire.framework.

    -
  • -
  • Select the top Alamofire.framework for iOS and the bottom one for macOS.

    - -
    -

    You can verify which one you selected by inspecting the build log for your project. The build target for Alamofire will be listed as either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire watchOS.

    -
  • -
  • And that’s it!

  • -
- -
-

The Alamofire.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.

-
-

Open Radars

- -

The following radars have some effect on the current implementation of Alamofire.

- -
    -
  • rdar://21349340 - Compiler throwing warning due to toll-free bridging issue in test case
  • -
  • rdar://26870455 - Background URL Session Configurations do not work in the simulator
  • -
  • rdar://26849668 - Some URLProtocol APIs do not properly handle URLRequest
  • -
-

Resolved Radars

- -

The following radars have been resolved over time after being filed against the Alamofire project.

- -
    -
  • rdar://26761490 - Swift string interpolation causing memory leak with common usage. - -
      -
    • (Resolved): 9/1/17 in Xcode 9 beta 6.
    • -
  • -
  • rdar://36082113 - URLSessionTaskMetrics failing to link on watchOS 3.0+ - -
      -
    • (Resolved): Just add CFNetwork to your linked frameworks.
    • -
  • -
-

FAQ

-

What’s the origin of the name Alamofire?

- -

Alamofire is named after the Alamo Fire flower, a hybrid variant of the Bluebonnet, the official state flower of Texas.

-

Credits

- -

Alamofire is owned and maintained by the Alamofire Software Foundation. You can follow them on Twitter at @AlamofireSF for project updates and releases.

-

Security Disclosure

- -

If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.

-

Donations

- -

The ASF is looking to raise money to officially stay registered as a federal non-profit organization. -Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. -Donating to the ASF will enable us to:

- -
    -
  • Pay our yearly legal fees to keep the non-profit in good status
  • -
  • Pay for our mail servers to help us stay on top of all questions and security issues
  • -
  • Potentially fund test servers to make it easier for us to test the edge cases
  • -
  • Potentially fund developers to work on one of our projects full-time
  • -
- -

The community adoption of the ASF libraries has been amazing. -We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. -With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. -If you use any of our libraries for work, see if your employers would be interested in donating. -Any amount you can donate today to help us reach our goal would be greatly appreciated.

- -

paypal

-

License

- -

Alamofire is released under the MIT license. See LICENSE for details.

- -
-
- - -
-
- - - - diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.js deleted file mode 100755 index c31dc05..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.js +++ /dev/null @@ -1,59 +0,0 @@ -window.jazzy = {'docset': false} -if (typeof window.dash != 'undefined') { - document.documentElement.className += ' dash' - window.jazzy.docset = true -} -if (navigator.userAgent.match(/xcode/i)) { - document.documentElement.className += ' xcode' - window.jazzy.docset = true -} - -function toggleItem($link, $content) { - var animationDuration = 300; - $link.toggleClass('token-open'); - $content.slideToggle(animationDuration); -} - -function itemLinkToContent($link) { - return $link.parent().parent().next(); -} - -// On doc load + hash-change, open any targetted item -function openCurrentItemIfClosed() { - if (window.jazzy.docset) { - return; - } - var $link = $(`.token[href="${location.hash}"]`); - $content = itemLinkToContent($link); - if ($content.is(':hidden')) { - toggleItem($link, $content); - } -} - -$(openCurrentItemIfClosed); -$(window).on('hashchange', openCurrentItemIfClosed); - -// On item link ('token') click, toggle its discussion -$('.token').on('click', function(event) { - if (window.jazzy.docset) { - return; - } - var $link = $(this); - toggleItem($link, itemLinkToContent($link)); - - // Keeps the document from jumping to the hash. - var href = $link.attr('href'); - if (history.pushState) { - history.pushState({}, '', href); - } else { - location.hash = href; - } - event.preventDefault(); -}); - -// Clicks on links to the current, closed, item need to open the item -$("a:not('.token')").on('click', function() { - if (location == this.href) { - openCurrentItemIfClosed(); - } -}); diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.search.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.search.js deleted file mode 100644 index e3d1ab9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jazzy.search.js +++ /dev/null @@ -1,70 +0,0 @@ -$(function(){ - var $typeahead = $('[data-typeahead]'); - var $form = $typeahead.parents('form'); - var searchURL = $form.attr('action'); - - function displayTemplate(result) { - return result.name; - } - - function suggestionTemplate(result) { - var t = '
'; - t += '' + result.name + ''; - if (result.parent_name) { - t += '' + result.parent_name + ''; - } - t += '
'; - return t; - } - - $typeahead.one('focus', function() { - $form.addClass('loading'); - - $.getJSON(searchURL).then(function(searchData) { - const searchIndex = lunr(function() { - this.ref('url'); - this.field('name'); - this.field('abstract'); - for (const [url, doc] of Object.entries(searchData)) { - this.add({url: url, name: doc.name, abstract: doc.abstract}); - } - }); - - $typeahead.typeahead( - { - highlight: true, - minLength: 3, - autoselect: true - }, - { - limit: 10, - display: displayTemplate, - templates: { suggestion: suggestionTemplate }, - source: function(query, sync) { - const lcSearch = query.toLowerCase(); - const results = searchIndex.query(function(q) { - q.term(lcSearch, { boost: 100 }); - q.term(lcSearch, { - boost: 10, - wildcard: lunr.Query.wildcard.TRAILING - }); - }).map(function(result) { - var doc = searchData[result.ref]; - doc.url = result.ref; - return doc; - }); - sync(results); - } - } - ); - $form.removeClass('loading'); - $typeahead.trigger('focus'); - }); - }); - - var baseURL = searchURL.slice(0, -"search.json".length); - - $typeahead.on('typeahead:select', function(e, result) { - window.location = baseURL + result.url; - }); -}); diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jquery.min.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jquery.min.js deleted file mode 100755 index a1c07fd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/js/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0=this.length)return z.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},z.QueryLexer.prototype.width=function(){return this.pos-this.start},z.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},z.QueryLexer.prototype.backup=function(){this.pos-=1},z.QueryLexer.prototype.acceptDigitRun=function(){for(var e,t;47<(t=(e=this.next()).charCodeAt(0))&&t<58;);e!=z.QueryLexer.EOS&&this.backup()},z.QueryLexer.prototype.more=function(){return this.pos', - menu: '
' - }; - } - function buildSelectors(classes) { - var selectors = {}; - _.each(classes, function(v, k) { - selectors[k] = "." + v; - }); - return selectors; - } - function buildCss() { - var css = { - wrapper: { - position: "relative", - display: "inline-block" - }, - hint: { - position: "absolute", - top: "0", - left: "0", - borderColor: "transparent", - boxShadow: "none", - opacity: "1" - }, - input: { - position: "relative", - verticalAlign: "top", - backgroundColor: "transparent" - }, - inputWithNoHint: { - position: "relative", - verticalAlign: "top" - }, - menu: { - position: "absolute", - top: "100%", - left: "0", - zIndex: "100", - display: "none" - }, - ltr: { - left: "0", - right: "auto" - }, - rtl: { - left: "auto", - right: " 0" - } - }; - if (_.isMsie()) { - _.mixin(css.input, { - backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" - }); - } - return css; - } - }(); - var EventBus = function() { - "use strict"; - var namespace, deprecationMap; - namespace = "typeahead:"; - deprecationMap = { - render: "rendered", - cursorchange: "cursorchanged", - select: "selected", - autocomplete: "autocompleted" - }; - function EventBus(o) { - if (!o || !o.el) { - $.error("EventBus initialized without el"); - } - this.$el = $(o.el); - } - _.mixin(EventBus.prototype, { - _trigger: function(type, args) { - var $e = $.Event(namespace + type); - this.$el.trigger.call(this.$el, $e, args || []); - return $e; - }, - before: function(type) { - var args, $e; - args = [].slice.call(arguments, 1); - $e = this._trigger("before" + type, args); - return $e.isDefaultPrevented(); - }, - trigger: function(type) { - var deprecatedType; - this._trigger(type, [].slice.call(arguments, 1)); - if (deprecatedType = deprecationMap[type]) { - this._trigger(deprecatedType, [].slice.call(arguments, 1)); - } - } - }); - return EventBus; - }(); - var EventEmitter = function() { - "use strict"; - var splitter = /\s+/, nextTick = getNextTick(); - return { - onSync: onSync, - onAsync: onAsync, - off: off, - trigger: trigger - }; - function on(method, types, cb, context) { - var type; - if (!cb) { - return this; - } - types = types.split(splitter); - cb = context ? bindContext(cb, context) : cb; - this._callbacks = this._callbacks || {}; - while (type = types.shift()) { - this._callbacks[type] = this._callbacks[type] || { - sync: [], - async: [] - }; - this._callbacks[type][method].push(cb); - } - return this; - } - function onAsync(types, cb, context) { - return on.call(this, "async", types, cb, context); - } - function onSync(types, cb, context) { - return on.call(this, "sync", types, cb, context); - } - function off(types) { - var type; - if (!this._callbacks) { - return this; - } - types = types.split(splitter); - while (type = types.shift()) { - delete this._callbacks[type]; - } - return this; - } - function trigger(types) { - var type, callbacks, args, syncFlush, asyncFlush; - if (!this._callbacks) { - return this; - } - types = types.split(splitter); - args = [].slice.call(arguments, 1); - while ((type = types.shift()) && (callbacks = this._callbacks[type])) { - syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); - asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); - syncFlush() && nextTick(asyncFlush); - } - return this; - } - function getFlush(callbacks, context, args) { - return flush; - function flush() { - var cancelled; - for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { - cancelled = callbacks[i].apply(context, args) === false; - } - return !cancelled; - } - } - function getNextTick() { - var nextTickFn; - if (window.setImmediate) { - nextTickFn = function nextTickSetImmediate(fn) { - setImmediate(function() { - fn(); - }); - }; - } else { - nextTickFn = function nextTickSetTimeout(fn) { - setTimeout(function() { - fn(); - }, 0); - }; - } - return nextTickFn; - } - function bindContext(fn, context) { - return fn.bind ? fn.bind(context) : function() { - fn.apply(context, [].slice.call(arguments, 0)); - }; - } - }(); - var highlight = function(doc) { - "use strict"; - var defaults = { - node: null, - pattern: null, - tagName: "strong", - className: null, - wordsOnly: false, - caseSensitive: false, - diacriticInsensitive: false - }; - var accented = { - A: "[AaªÀ-Åà-åĀ-ąǍǎȀ-ȃȦȧᴬᵃḀḁẚẠ-ảₐ℀℁℻⒜Ⓐⓐ㍱-㍴㎀-㎄㎈㎉㎩-㎯㏂㏊㏟㏿Aa]", - B: "[BbᴮᵇḂ-ḇℬ⒝Ⓑⓑ㍴㎅-㎇㏃㏈㏔㏝Bb]", - C: "[CcÇçĆ-čᶜ℀ℂ℃℅℆ℭⅭⅽ⒞Ⓒⓒ㍶㎈㎉㎝㎠㎤㏄-㏇Cc]", - D: "[DdĎďDŽ-džDZ-dzᴰᵈḊ-ḓⅅⅆⅮⅾ⒟Ⓓⓓ㋏㍲㍷-㍹㎗㎭-㎯㏅㏈Dd]", - E: "[EeÈ-Ëè-ëĒ-ěȄ-ȇȨȩᴱᵉḘ-ḛẸ-ẽₑ℡ℯℰⅇ⒠Ⓔⓔ㉐㋍㋎Ee]", - F: "[FfᶠḞḟ℉ℱ℻⒡Ⓕⓕ㎊-㎌㎙ff-fflFf]", - G: "[GgĜ-ģǦǧǴǵᴳᵍḠḡℊ⒢Ⓖⓖ㋌㋍㎇㎍-㎏㎓㎬㏆㏉㏒㏿Gg]", - H: "[HhĤĥȞȟʰᴴḢ-ḫẖℋ-ℎ⒣Ⓗⓗ㋌㍱㎐-㎔㏊㏋㏗Hh]", - I: "[IiÌ-Ïì-ïĨ-İIJijǏǐȈ-ȋᴵᵢḬḭỈ-ịⁱℐℑℹⅈⅠ-ⅣⅥ-ⅨⅪⅫⅰ-ⅳⅵ-ⅸⅺⅻ⒤Ⓘⓘ㍺㏌㏕fiffiIi]", - J: "[JjIJ-ĵLJ-njǰʲᴶⅉ⒥ⒿⓙⱼJj]", - K: "[KkĶķǨǩᴷᵏḰ-ḵK⒦Ⓚⓚ㎄㎅㎉㎏㎑㎘㎞㎢㎦㎪㎸㎾㏀㏆㏍-㏏Kk]", - L: "[LlĹ-ŀLJ-ljˡᴸḶḷḺ-ḽℒℓ℡Ⅼⅼ⒧Ⓛⓛ㋏㎈㎉㏐-㏓㏕㏖㏿flfflLl]", - M: "[MmᴹᵐḾ-ṃ℠™ℳⅯⅿ⒨Ⓜⓜ㍷-㍹㎃㎆㎎㎒㎖㎙-㎨㎫㎳㎷㎹㎽㎿㏁㏂㏎㏐㏔-㏖㏘㏙㏞㏟Mm]", - N: "[NnÑñŃ-ʼnNJ-njǸǹᴺṄ-ṋⁿℕ№⒩Ⓝⓝ㎁㎋㎚㎱㎵㎻㏌㏑Nn]", - O: "[OoºÒ-Öò-öŌ-őƠơǑǒǪǫȌ-ȏȮȯᴼᵒỌ-ỏₒ℅№ℴ⒪Ⓞⓞ㍵㏇㏒㏖Oo]", - P: "[PpᴾᵖṔ-ṗℙ⒫Ⓟⓟ㉐㍱㍶㎀㎊㎩-㎬㎰㎴㎺㏋㏗-㏚Pp]", - Q: "[Qqℚ⒬Ⓠⓠ㏃Qq]", - R: "[RrŔ-řȐ-ȓʳᴿᵣṘ-ṛṞṟ₨ℛ-ℝ⒭Ⓡⓡ㋍㍴㎭-㎯㏚㏛Rr]", - S: "[SsŚ-šſȘșˢṠ-ṣ₨℁℠⒮Ⓢⓢ㎧㎨㎮-㎳㏛㏜stSs]", - T: "[TtŢ-ťȚțᵀᵗṪ-ṱẗ℡™⒯Ⓣⓣ㉐㋏㎔㏏ſtstTt]", - U: "[UuÙ-Üù-üŨ-ųƯưǓǔȔ-ȗᵁᵘᵤṲ-ṷỤ-ủ℆⒰Ⓤⓤ㍳㍺Uu]", - V: "[VvᵛᵥṼ-ṿⅣ-Ⅷⅳ-ⅷ⒱Ⓥⓥⱽ㋎㍵㎴-㎹㏜㏞Vv]", - W: "[WwŴŵʷᵂẀ-ẉẘ⒲Ⓦⓦ㎺-㎿㏝Ww]", - X: "[XxˣẊ-ẍₓ℻Ⅸ-Ⅻⅸ-ⅻ⒳Ⓧⓧ㏓Xx]", - Y: "[YyÝýÿŶ-ŸȲȳʸẎẏẙỲ-ỹ⒴Ⓨⓨ㏉Yy]", - Z: "[ZzŹ-žDZ-dzᶻẐ-ẕℤℨ⒵Ⓩⓩ㎐-㎔Zz]" - }; - return function hightlight(o) { - var regex; - o = _.mixin({}, defaults, o); - if (!o.node || !o.pattern) { - return; - } - o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; - regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly, o.diacriticInsensitive); - traverse(o.node, hightlightTextNode); - function hightlightTextNode(textNode) { - var match, patternNode, wrapperNode; - if (match = regex.exec(textNode.data)) { - wrapperNode = doc.createElement(o.tagName); - o.className && (wrapperNode.className = o.className); - patternNode = textNode.splitText(match.index); - patternNode.splitText(match[0].length); - wrapperNode.appendChild(patternNode.cloneNode(true)); - textNode.parentNode.replaceChild(wrapperNode, patternNode); - } - return !!match; - } - function traverse(el, hightlightTextNode) { - var childNode, TEXT_NODE_TYPE = 3; - for (var i = 0; i < el.childNodes.length; i++) { - childNode = el.childNodes[i]; - if (childNode.nodeType === TEXT_NODE_TYPE) { - i += hightlightTextNode(childNode) ? 1 : 0; - } else { - traverse(childNode, hightlightTextNode); - } - } - } - }; - function accent_replacer(chr) { - return accented[chr.toUpperCase()] || chr; - } - function getRegex(patterns, caseSensitive, wordsOnly, diacriticInsensitive) { - var escapedPatterns = [], regexStr; - for (var i = 0, len = patterns.length; i < len; i++) { - var escapedWord = _.escapeRegExChars(patterns[i]); - if (diacriticInsensitive) { - escapedWord = escapedWord.replace(/\S/g, accent_replacer); - } - escapedPatterns.push(escapedWord); - } - regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; - return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); - } - }(window.document); - var Input = function() { - "use strict"; - var specialKeyCodeMap; - specialKeyCodeMap = { - 9: "tab", - 27: "esc", - 37: "left", - 39: "right", - 13: "enter", - 38: "up", - 40: "down" - }; - function Input(o, www) { - o = o || {}; - if (!o.input) { - $.error("input is missing"); - } - www.mixin(this); - this.$hint = $(o.hint); - this.$input = $(o.input); - this.$input.attr({ - "aria-activedescendant": "", - "aria-owns": this.$input.attr("id") + "_listbox", - role: "combobox", - "aria-readonly": "true", - "aria-autocomplete": "list" - }); - $(www.menu).attr("id", this.$input.attr("id") + "_listbox"); - this.query = this.$input.val(); - this.queryWhenFocused = this.hasFocus() ? this.query : null; - this.$overflowHelper = buildOverflowHelper(this.$input); - this._checkLanguageDirection(); - if (this.$hint.length === 0) { - this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; - } - this.onSync("cursorchange", this._updateDescendent); - } - Input.normalizeQuery = function(str) { - return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " "); - }; - _.mixin(Input.prototype, EventEmitter, { - _onBlur: function onBlur() { - this.resetInputValue(); - this.trigger("blurred"); - }, - _onFocus: function onFocus() { - this.queryWhenFocused = this.query; - this.trigger("focused"); - }, - _onKeydown: function onKeydown($e) { - var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; - this._managePreventDefault(keyName, $e); - if (keyName && this._shouldTrigger(keyName, $e)) { - this.trigger(keyName + "Keyed", $e); - } - }, - _onInput: function onInput() { - this._setQuery(this.getInputValue()); - this.clearHintIfInvalid(); - this._checkLanguageDirection(); - }, - _managePreventDefault: function managePreventDefault(keyName, $e) { - var preventDefault; - switch (keyName) { - case "up": - case "down": - preventDefault = !withModifier($e); - break; - - default: - preventDefault = false; - } - preventDefault && $e.preventDefault(); - }, - _shouldTrigger: function shouldTrigger(keyName, $e) { - var trigger; - switch (keyName) { - case "tab": - trigger = !withModifier($e); - break; - - default: - trigger = true; - } - return trigger; - }, - _checkLanguageDirection: function checkLanguageDirection() { - var dir = (this.$input.css("direction") || "ltr").toLowerCase(); - if (this.dir !== dir) { - this.dir = dir; - this.$hint.attr("dir", dir); - this.trigger("langDirChanged", dir); - } - }, - _setQuery: function setQuery(val, silent) { - var areEquivalent, hasDifferentWhitespace; - areEquivalent = areQueriesEquivalent(val, this.query); - hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false; - this.query = val; - if (!silent && !areEquivalent) { - this.trigger("queryChanged", this.query); - } else if (!silent && hasDifferentWhitespace) { - this.trigger("whitespaceChanged", this.query); - } - }, - _updateDescendent: function updateDescendent(event, id) { - this.$input.attr("aria-activedescendant", id); - }, - bind: function() { - var that = this, onBlur, onFocus, onKeydown, onInput; - onBlur = _.bind(this._onBlur, this); - onFocus = _.bind(this._onFocus, this); - onKeydown = _.bind(this._onKeydown, this); - onInput = _.bind(this._onInput, this); - this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); - if (!_.isMsie() || _.isMsie() > 9) { - this.$input.on("input.tt", onInput); - } else { - this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { - if (specialKeyCodeMap[$e.which || $e.keyCode]) { - return; - } - _.defer(_.bind(that._onInput, that, $e)); - }); - } - return this; - }, - focus: function focus() { - this.$input.focus(); - }, - blur: function blur() { - this.$input.blur(); - }, - getLangDir: function getLangDir() { - return this.dir; - }, - getQuery: function getQuery() { - return this.query || ""; - }, - setQuery: function setQuery(val, silent) { - this.setInputValue(val); - this._setQuery(val, silent); - }, - hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() { - return this.query !== this.queryWhenFocused; - }, - getInputValue: function getInputValue() { - return this.$input.val(); - }, - setInputValue: function setInputValue(value) { - this.$input.val(value); - this.clearHintIfInvalid(); - this._checkLanguageDirection(); - }, - resetInputValue: function resetInputValue() { - this.setInputValue(this.query); - }, - getHint: function getHint() { - return this.$hint.val(); - }, - setHint: function setHint(value) { - this.$hint.val(value); - }, - clearHint: function clearHint() { - this.setHint(""); - }, - clearHintIfInvalid: function clearHintIfInvalid() { - var val, hint, valIsPrefixOfHint, isValid; - val = this.getInputValue(); - hint = this.getHint(); - valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; - isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow(); - !isValid && this.clearHint(); - }, - hasFocus: function hasFocus() { - return this.$input.is(":focus"); - }, - hasOverflow: function hasOverflow() { - var constraint = this.$input.width() - 2; - this.$overflowHelper.text(this.getInputValue()); - return this.$overflowHelper.width() >= constraint; - }, - isCursorAtEnd: function() { - var valueLength, selectionStart, range; - valueLength = this.$input.val().length; - selectionStart = this.$input[0].selectionStart; - if (_.isNumber(selectionStart)) { - return selectionStart === valueLength; - } else if (document.selection) { - range = document.selection.createRange(); - range.moveStart("character", -valueLength); - return valueLength === range.text.length; - } - return true; - }, - destroy: function destroy() { - this.$hint.off(".tt"); - this.$input.off(".tt"); - this.$overflowHelper.remove(); - this.$hint = this.$input = this.$overflowHelper = $("
"); - } - }); - return Input; - function buildOverflowHelper($input) { - return $('').css({ - position: "absolute", - visibility: "hidden", - whiteSpace: "pre", - fontFamily: $input.css("font-family"), - fontSize: $input.css("font-size"), - fontStyle: $input.css("font-style"), - fontVariant: $input.css("font-variant"), - fontWeight: $input.css("font-weight"), - wordSpacing: $input.css("word-spacing"), - letterSpacing: $input.css("letter-spacing"), - textIndent: $input.css("text-indent"), - textRendering: $input.css("text-rendering"), - textTransform: $input.css("text-transform") - }).insertAfter($input); - } - function areQueriesEquivalent(a, b) { - return Input.normalizeQuery(a) === Input.normalizeQuery(b); - } - function withModifier($e) { - return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; - } - }(); - var Dataset = function() { - "use strict"; - var keys, nameGenerator; - keys = { - dataset: "tt-selectable-dataset", - val: "tt-selectable-display", - obj: "tt-selectable-object" - }; - nameGenerator = _.getIdGenerator(); - function Dataset(o, www) { - o = o || {}; - o.templates = o.templates || {}; - o.templates.notFound = o.templates.notFound || o.templates.empty; - if (!o.source) { - $.error("missing source"); - } - if (!o.node) { - $.error("missing node"); - } - if (o.name && !isValidName(o.name)) { - $.error("invalid dataset name: " + o.name); - } - www.mixin(this); - this.highlight = !!o.highlight; - this.name = _.toStr(o.name || nameGenerator()); - this.limit = o.limit || 5; - this.displayFn = getDisplayFn(o.display || o.displayKey); - this.templates = getTemplates(o.templates, this.displayFn); - this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source; - this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async; - this._resetLastSuggestion(); - this.$el = $(o.node).attr("role", "presentation").addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name); - } - Dataset.extractData = function extractData(el) { - var $el = $(el); - if ($el.data(keys.obj)) { - return { - dataset: $el.data(keys.dataset) || "", - val: $el.data(keys.val) || "", - obj: $el.data(keys.obj) || null - }; - } - return null; - }; - _.mixin(Dataset.prototype, EventEmitter, { - _overwrite: function overwrite(query, suggestions) { - suggestions = suggestions || []; - if (suggestions.length) { - this._renderSuggestions(query, suggestions); - } else if (this.async && this.templates.pending) { - this._renderPending(query); - } else if (!this.async && this.templates.notFound) { - this._renderNotFound(query); - } else { - this._empty(); - } - this.trigger("rendered", suggestions, false, this.name); - }, - _append: function append(query, suggestions) { - suggestions = suggestions || []; - if (suggestions.length && this.$lastSuggestion.length) { - this._appendSuggestions(query, suggestions); - } else if (suggestions.length) { - this._renderSuggestions(query, suggestions); - } else if (!this.$lastSuggestion.length && this.templates.notFound) { - this._renderNotFound(query); - } - this.trigger("rendered", suggestions, true, this.name); - }, - _renderSuggestions: function renderSuggestions(query, suggestions) { - var $fragment; - $fragment = this._getSuggestionsFragment(query, suggestions); - this.$lastSuggestion = $fragment.children().last(); - this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions)); - }, - _appendSuggestions: function appendSuggestions(query, suggestions) { - var $fragment, $lastSuggestion; - $fragment = this._getSuggestionsFragment(query, suggestions); - $lastSuggestion = $fragment.children().last(); - this.$lastSuggestion.after($fragment); - this.$lastSuggestion = $lastSuggestion; - }, - _renderPending: function renderPending(query) { - var template = this.templates.pending; - this._resetLastSuggestion(); - template && this.$el.html(template({ - query: query, - dataset: this.name - })); - }, - _renderNotFound: function renderNotFound(query) { - var template = this.templates.notFound; - this._resetLastSuggestion(); - template && this.$el.html(template({ - query: query, - dataset: this.name - })); - }, - _empty: function empty() { - this.$el.empty(); - this._resetLastSuggestion(); - }, - _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) { - var that = this, fragment; - fragment = document.createDocumentFragment(); - _.each(suggestions, function getSuggestionNode(suggestion) { - var $el, context; - context = that._injectQuery(query, suggestion); - $el = $(that.templates.suggestion(context)).data(keys.dataset, that.name).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable); - fragment.appendChild($el[0]); - }); - this.highlight && highlight({ - className: this.classes.highlight, - node: fragment, - pattern: query - }); - return $(fragment); - }, - _getFooter: function getFooter(query, suggestions) { - return this.templates.footer ? this.templates.footer({ - query: query, - suggestions: suggestions, - dataset: this.name - }) : null; - }, - _getHeader: function getHeader(query, suggestions) { - return this.templates.header ? this.templates.header({ - query: query, - suggestions: suggestions, - dataset: this.name - }) : null; - }, - _resetLastSuggestion: function resetLastSuggestion() { - this.$lastSuggestion = $(); - }, - _injectQuery: function injectQuery(query, obj) { - return _.isObject(obj) ? _.mixin({ - _query: query - }, obj) : obj; - }, - update: function update(query) { - var that = this, canceled = false, syncCalled = false, rendered = 0; - this.cancel(); - this.cancel = function cancel() { - canceled = true; - that.cancel = $.noop; - that.async && that.trigger("asyncCanceled", query, that.name); - }; - this.source(query, sync, async); - !syncCalled && sync([]); - function sync(suggestions) { - if (syncCalled) { - return; - } - syncCalled = true; - suggestions = (suggestions || []).slice(0, that.limit); - rendered = suggestions.length; - that._overwrite(query, suggestions); - if (rendered < that.limit && that.async) { - that.trigger("asyncRequested", query, that.name); - } - } - function async(suggestions) { - suggestions = suggestions || []; - if (!canceled && rendered < that.limit) { - that.cancel = $.noop; - var idx = Math.abs(rendered - that.limit); - rendered += idx; - that._append(query, suggestions.slice(0, idx)); - that.async && that.trigger("asyncReceived", query, that.name); - } - } - }, - cancel: $.noop, - clear: function clear() { - this._empty(); - this.cancel(); - this.trigger("cleared"); - }, - isEmpty: function isEmpty() { - return this.$el.is(":empty"); - }, - destroy: function destroy() { - this.$el = $("
"); - } - }); - return Dataset; - function getDisplayFn(display) { - display = display || _.stringify; - return _.isFunction(display) ? display : displayFn; - function displayFn(obj) { - return obj[display]; - } - } - function getTemplates(templates, displayFn) { - return { - notFound: templates.notFound && _.templatify(templates.notFound), - pending: templates.pending && _.templatify(templates.pending), - header: templates.header && _.templatify(templates.header), - footer: templates.footer && _.templatify(templates.footer), - suggestion: templates.suggestion || suggestionTemplate - }; - function suggestionTemplate(context) { - return $('
').attr("id", _.guid()).text(displayFn(context)); - } - } - function isValidName(str) { - return /^[_a-zA-Z0-9-]+$/.test(str); - } - }(); - var Menu = function() { - "use strict"; - function Menu(o, www) { - var that = this; - o = o || {}; - if (!o.node) { - $.error("node is required"); - } - www.mixin(this); - this.$node = $(o.node); - this.query = null; - this.datasets = _.map(o.datasets, initializeDataset); - function initializeDataset(oDataset) { - var node = that.$node.find(oDataset.node).first(); - oDataset.node = node.length ? node : $("
").appendTo(that.$node); - return new Dataset(oDataset, www); - } - } - _.mixin(Menu.prototype, EventEmitter, { - _onSelectableClick: function onSelectableClick($e) { - this.trigger("selectableClicked", $($e.currentTarget)); - }, - _onRendered: function onRendered(type, dataset, suggestions, async) { - this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); - this.trigger("datasetRendered", dataset, suggestions, async); - }, - _onCleared: function onCleared() { - this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); - this.trigger("datasetCleared"); - }, - _propagate: function propagate() { - this.trigger.apply(this, arguments); - }, - _allDatasetsEmpty: function allDatasetsEmpty() { - return _.every(this.datasets, _.bind(function isDatasetEmpty(dataset) { - var isEmpty = dataset.isEmpty(); - this.$node.attr("aria-expanded", !isEmpty); - return isEmpty; - }, this)); - }, - _getSelectables: function getSelectables() { - return this.$node.find(this.selectors.selectable); - }, - _removeCursor: function _removeCursor() { - var $selectable = this.getActiveSelectable(); - $selectable && $selectable.removeClass(this.classes.cursor); - }, - _ensureVisible: function ensureVisible($el) { - var elTop, elBottom, nodeScrollTop, nodeHeight; - elTop = $el.position().top; - elBottom = elTop + $el.outerHeight(true); - nodeScrollTop = this.$node.scrollTop(); - nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10); - if (elTop < 0) { - this.$node.scrollTop(nodeScrollTop + elTop); - } else if (nodeHeight < elBottom) { - this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight)); - } - }, - bind: function() { - var that = this, onSelectableClick; - onSelectableClick = _.bind(this._onSelectableClick, this); - this.$node.on("click.tt", this.selectors.selectable, onSelectableClick); - this.$node.on("mouseover", this.selectors.selectable, function() { - that.setCursor($(this)); - }); - this.$node.on("mouseleave", function() { - that._removeCursor(); - }); - _.each(this.datasets, function(dataset) { - dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that); - }); - return this; - }, - isOpen: function isOpen() { - return this.$node.hasClass(this.classes.open); - }, - open: function open() { - this.$node.scrollTop(0); - this.$node.addClass(this.classes.open); - }, - close: function close() { - this.$node.attr("aria-expanded", false); - this.$node.removeClass(this.classes.open); - this._removeCursor(); - }, - setLanguageDirection: function setLanguageDirection(dir) { - this.$node.attr("dir", dir); - }, - selectableRelativeToCursor: function selectableRelativeToCursor(delta) { - var $selectables, $oldCursor, oldIndex, newIndex; - $oldCursor = this.getActiveSelectable(); - $selectables = this._getSelectables(); - oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1; - newIndex = oldIndex + delta; - newIndex = (newIndex + 1) % ($selectables.length + 1) - 1; - newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex; - return newIndex === -1 ? null : $selectables.eq(newIndex); - }, - setCursor: function setCursor($selectable) { - this._removeCursor(); - if ($selectable = $selectable && $selectable.first()) { - $selectable.addClass(this.classes.cursor); - this._ensureVisible($selectable); - } - }, - getSelectableData: function getSelectableData($el) { - return $el && $el.length ? Dataset.extractData($el) : null; - }, - getActiveSelectable: function getActiveSelectable() { - var $selectable = this._getSelectables().filter(this.selectors.cursor).first(); - return $selectable.length ? $selectable : null; - }, - getTopSelectable: function getTopSelectable() { - var $selectable = this._getSelectables().first(); - return $selectable.length ? $selectable : null; - }, - update: function update(query) { - var isValidUpdate = query !== this.query; - if (isValidUpdate) { - this.query = query; - _.each(this.datasets, updateDataset); - } - return isValidUpdate; - function updateDataset(dataset) { - dataset.update(query); - } - }, - empty: function empty() { - _.each(this.datasets, clearDataset); - this.query = null; - this.$node.addClass(this.classes.empty); - function clearDataset(dataset) { - dataset.clear(); - } - }, - destroy: function destroy() { - this.$node.off(".tt"); - this.$node = $("
"); - _.each(this.datasets, destroyDataset); - function destroyDataset(dataset) { - dataset.destroy(); - } - } - }); - return Menu; - }(); - var Status = function() { - "use strict"; - function Status(options) { - this.$el = $("", { - role: "status", - "aria-live": "polite" - }).css({ - position: "absolute", - padding: "0", - border: "0", - height: "1px", - width: "1px", - "margin-bottom": "-1px", - "margin-right": "-1px", - overflow: "hidden", - clip: "rect(0 0 0 0)", - "white-space": "nowrap" - }); - options.$input.after(this.$el); - _.each(options.menu.datasets, _.bind(function(dataset) { - if (dataset.onSync) { - dataset.onSync("rendered", _.bind(this.update, this)); - dataset.onSync("cleared", _.bind(this.cleared, this)); - } - }, this)); - } - _.mixin(Status.prototype, { - update: function update(event, suggestions) { - var length = suggestions.length; - var words; - if (length === 1) { - words = { - result: "result", - is: "is" - }; - } else { - words = { - result: "results", - is: "are" - }; - } - this.$el.text(length + " " + words.result + " " + words.is + " available, use up and down arrow keys to navigate."); - }, - cleared: function() { - this.$el.text(""); - } - }); - return Status; - }(); - var DefaultMenu = function() { - "use strict"; - var s = Menu.prototype; - function DefaultMenu() { - Menu.apply(this, [].slice.call(arguments, 0)); - } - _.mixin(DefaultMenu.prototype, Menu.prototype, { - open: function open() { - !this._allDatasetsEmpty() && this._show(); - return s.open.apply(this, [].slice.call(arguments, 0)); - }, - close: function close() { - this._hide(); - return s.close.apply(this, [].slice.call(arguments, 0)); - }, - _onRendered: function onRendered() { - if (this._allDatasetsEmpty()) { - this._hide(); - } else { - this.isOpen() && this._show(); - } - return s._onRendered.apply(this, [].slice.call(arguments, 0)); - }, - _onCleared: function onCleared() { - if (this._allDatasetsEmpty()) { - this._hide(); - } else { - this.isOpen() && this._show(); - } - return s._onCleared.apply(this, [].slice.call(arguments, 0)); - }, - setLanguageDirection: function setLanguageDirection(dir) { - this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl); - return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0)); - }, - _hide: function hide() { - this.$node.hide(); - }, - _show: function show() { - this.$node.css("display", "block"); - } - }); - return DefaultMenu; - }(); - var Typeahead = function() { - "use strict"; - function Typeahead(o, www) { - var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged; - o = o || {}; - if (!o.input) { - $.error("missing input"); - } - if (!o.menu) { - $.error("missing menu"); - } - if (!o.eventBus) { - $.error("missing event bus"); - } - www.mixin(this); - this.eventBus = o.eventBus; - this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; - this.input = o.input; - this.menu = o.menu; - this.enabled = true; - this.autoselect = !!o.autoselect; - this.active = false; - this.input.hasFocus() && this.activate(); - this.dir = this.input.getLangDir(); - this._hacks(); - this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this); - onFocused = c(this, "activate", "open", "_onFocused"); - onBlurred = c(this, "deactivate", "_onBlurred"); - onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed"); - onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed"); - onEscKeyed = c(this, "isActive", "_onEscKeyed"); - onUpKeyed = c(this, "isActive", "open", "_onUpKeyed"); - onDownKeyed = c(this, "isActive", "open", "_onDownKeyed"); - onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed"); - onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed"); - onQueryChanged = c(this, "_openIfActive", "_onQueryChanged"); - onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged"); - this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this); - } - _.mixin(Typeahead.prototype, { - _hacks: function hacks() { - var $input, $menu; - $input = this.input.$input || $("
"); - $menu = this.menu.$node || $("
"); - $input.on("blur.tt", function($e) { - var active, isActive, hasActive; - active = document.activeElement; - isActive = $menu.is(active); - hasActive = $menu.has(active).length > 0; - if (_.isMsie() && (isActive || hasActive)) { - $e.preventDefault(); - $e.stopImmediatePropagation(); - _.defer(function() { - $input.focus(); - }); - } - }); - $menu.on("mousedown.tt", function($e) { - $e.preventDefault(); - }); - }, - _onSelectableClicked: function onSelectableClicked(type, $el) { - this.select($el); - }, - _onDatasetCleared: function onDatasetCleared() { - this._updateHint(); - }, - _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) { - this._updateHint(); - if (this.autoselect) { - var cursorClass = this.selectors.cursor.substr(1); - this.menu.$node.find(this.selectors.suggestion).first().addClass(cursorClass); - } - this.eventBus.trigger("render", suggestions, async, dataset); - }, - _onAsyncRequested: function onAsyncRequested(type, dataset, query) { - this.eventBus.trigger("asyncrequest", query, dataset); - }, - _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) { - this.eventBus.trigger("asynccancel", query, dataset); - }, - _onAsyncReceived: function onAsyncReceived(type, dataset, query) { - this.eventBus.trigger("asyncreceive", query, dataset); - }, - _onFocused: function onFocused() { - this._minLengthMet() && this.menu.update(this.input.getQuery()); - }, - _onBlurred: function onBlurred() { - if (this.input.hasQueryChangedSinceLastFocus()) { - this.eventBus.trigger("change", this.input.getQuery()); - } - }, - _onEnterKeyed: function onEnterKeyed(type, $e) { - var $selectable; - if ($selectable = this.menu.getActiveSelectable()) { - if (this.select($selectable)) { - $e.preventDefault(); - $e.stopPropagation(); - } - } else if (this.autoselect) { - if (this.select(this.menu.getTopSelectable())) { - $e.preventDefault(); - $e.stopPropagation(); - } - } - }, - _onTabKeyed: function onTabKeyed(type, $e) { - var $selectable; - if ($selectable = this.menu.getActiveSelectable()) { - this.select($selectable) && $e.preventDefault(); - } else if ($selectable = this.menu.getTopSelectable()) { - this.autocomplete($selectable) && $e.preventDefault(); - } - }, - _onEscKeyed: function onEscKeyed() { - this.close(); - }, - _onUpKeyed: function onUpKeyed() { - this.moveCursor(-1); - }, - _onDownKeyed: function onDownKeyed() { - this.moveCursor(+1); - }, - _onLeftKeyed: function onLeftKeyed() { - if (this.dir === "rtl" && this.input.isCursorAtEnd()) { - this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); - } - }, - _onRightKeyed: function onRightKeyed() { - if (this.dir === "ltr" && this.input.isCursorAtEnd()) { - this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); - } - }, - _onQueryChanged: function onQueryChanged(e, query) { - this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty(); - }, - _onWhitespaceChanged: function onWhitespaceChanged() { - this._updateHint(); - }, - _onLangDirChanged: function onLangDirChanged(e, dir) { - if (this.dir !== dir) { - this.dir = dir; - this.menu.setLanguageDirection(dir); - } - }, - _openIfActive: function openIfActive() { - this.isActive() && this.open(); - }, - _minLengthMet: function minLengthMet(query) { - query = _.isString(query) ? query : this.input.getQuery() || ""; - return query.length >= this.minLength; - }, - _updateHint: function updateHint() { - var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match; - $selectable = this.menu.getTopSelectable(); - data = this.menu.getSelectableData($selectable); - val = this.input.getInputValue(); - if (data && !_.isBlankString(val) && !this.input.hasOverflow()) { - query = Input.normalizeQuery(val); - escapedQuery = _.escapeRegExChars(query); - frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i"); - match = frontMatchRegEx.exec(data.val); - match && this.input.setHint(val + match[1]); - } else { - this.input.clearHint(); - } - }, - isEnabled: function isEnabled() { - return this.enabled; - }, - enable: function enable() { - this.enabled = true; - }, - disable: function disable() { - this.enabled = false; - }, - isActive: function isActive() { - return this.active; - }, - activate: function activate() { - if (this.isActive()) { - return true; - } else if (!this.isEnabled() || this.eventBus.before("active")) { - return false; - } else { - this.active = true; - this.eventBus.trigger("active"); - return true; - } - }, - deactivate: function deactivate() { - if (!this.isActive()) { - return true; - } else if (this.eventBus.before("idle")) { - return false; - } else { - this.active = false; - this.close(); - this.eventBus.trigger("idle"); - return true; - } - }, - isOpen: function isOpen() { - return this.menu.isOpen(); - }, - open: function open() { - if (!this.isOpen() && !this.eventBus.before("open")) { - this.menu.open(); - this._updateHint(); - this.eventBus.trigger("open"); - } - return this.isOpen(); - }, - close: function close() { - if (this.isOpen() && !this.eventBus.before("close")) { - this.menu.close(); - this.input.clearHint(); - this.input.resetInputValue(); - this.eventBus.trigger("close"); - } - return !this.isOpen(); - }, - setVal: function setVal(val) { - this.input.setQuery(_.toStr(val)); - }, - getVal: function getVal() { - return this.input.getQuery(); - }, - select: function select($selectable) { - var data = this.menu.getSelectableData($selectable); - if (data && !this.eventBus.before("select", data.obj, data.dataset)) { - this.input.setQuery(data.val, true); - this.eventBus.trigger("select", data.obj, data.dataset); - this.close(); - return true; - } - return false; - }, - autocomplete: function autocomplete($selectable) { - var query, data, isValid; - query = this.input.getQuery(); - data = this.menu.getSelectableData($selectable); - isValid = data && query !== data.val; - if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) { - this.input.setQuery(data.val); - this.eventBus.trigger("autocomplete", data.obj, data.dataset); - return true; - } - return false; - }, - moveCursor: function moveCursor(delta) { - var query, $candidate, data, suggestion, datasetName, cancelMove, id; - query = this.input.getQuery(); - $candidate = this.menu.selectableRelativeToCursor(delta); - data = this.menu.getSelectableData($candidate); - suggestion = data ? data.obj : null; - datasetName = data ? data.dataset : null; - id = $candidate ? $candidate.attr("id") : null; - this.input.trigger("cursorchange", id); - cancelMove = this._minLengthMet() && this.menu.update(query); - if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) { - this.menu.setCursor($candidate); - if (data) { - this.input.setInputValue(data.val); - } else { - this.input.resetInputValue(); - this._updateHint(); - } - this.eventBus.trigger("cursorchange", suggestion, datasetName); - return true; - } - return false; - }, - destroy: function destroy() { - this.input.destroy(); - this.menu.destroy(); - } - }); - return Typeahead; - function c(ctx) { - var methods = [].slice.call(arguments, 1); - return function() { - var args = [].slice.call(arguments); - _.each(methods, function(method) { - return ctx[method].apply(ctx, args); - }); - }; - } - }(); - (function() { - "use strict"; - var old, keys, methods; - old = $.fn.typeahead; - keys = { - www: "tt-www", - attrs: "tt-attrs", - typeahead: "tt-typeahead" - }; - methods = { - initialize: function initialize(o, datasets) { - var www; - datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1); - o = o || {}; - www = WWW(o.classNames); - return this.each(attach); - function attach() { - var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, status, typeahead, MenuConstructor; - _.each(datasets, function(d) { - d.highlight = !!o.highlight; - }); - $input = $(this); - $wrapper = $(www.html.wrapper); - $hint = $elOrNull(o.hint); - $menu = $elOrNull(o.menu); - defaultHint = o.hint !== false && !$hint; - defaultMenu = o.menu !== false && !$menu; - defaultHint && ($hint = buildHintFromInput($input, www)); - defaultMenu && ($menu = $(www.html.menu).css(www.css.menu)); - $hint && $hint.val(""); - $input = prepInput($input, www); - if (defaultHint || defaultMenu) { - $wrapper.css(www.css.wrapper); - $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint); - $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null); - } - MenuConstructor = defaultMenu ? DefaultMenu : Menu; - eventBus = new EventBus({ - el: $input - }); - input = new Input({ - hint: $hint, - input: $input - }, www); - menu = new MenuConstructor({ - node: $menu, - datasets: datasets - }, www); - status = new Status({ - $input: $input, - menu: menu - }); - typeahead = new Typeahead({ - input: input, - menu: menu, - eventBus: eventBus, - minLength: o.minLength, - autoselect: o.autoselect - }, www); - $input.data(keys.www, www); - $input.data(keys.typeahead, typeahead); - } - }, - isEnabled: function isEnabled() { - var enabled; - ttEach(this.first(), function(t) { - enabled = t.isEnabled(); - }); - return enabled; - }, - enable: function enable() { - ttEach(this, function(t) { - t.enable(); - }); - return this; - }, - disable: function disable() { - ttEach(this, function(t) { - t.disable(); - }); - return this; - }, - isActive: function isActive() { - var active; - ttEach(this.first(), function(t) { - active = t.isActive(); - }); - return active; - }, - activate: function activate() { - ttEach(this, function(t) { - t.activate(); - }); - return this; - }, - deactivate: function deactivate() { - ttEach(this, function(t) { - t.deactivate(); - }); - return this; - }, - isOpen: function isOpen() { - var open; - ttEach(this.first(), function(t) { - open = t.isOpen(); - }); - return open; - }, - open: function open() { - ttEach(this, function(t) { - t.open(); - }); - return this; - }, - close: function close() { - ttEach(this, function(t) { - t.close(); - }); - return this; - }, - select: function select(el) { - var success = false, $el = $(el); - ttEach(this.first(), function(t) { - success = t.select($el); - }); - return success; - }, - autocomplete: function autocomplete(el) { - var success = false, $el = $(el); - ttEach(this.first(), function(t) { - success = t.autocomplete($el); - }); - return success; - }, - moveCursor: function moveCursoe(delta) { - var success = false; - ttEach(this.first(), function(t) { - success = t.moveCursor(delta); - }); - return success; - }, - val: function val(newVal) { - var query; - if (!arguments.length) { - ttEach(this.first(), function(t) { - query = t.getVal(); - }); - return query; - } else { - ttEach(this, function(t) { - t.setVal(_.toStr(newVal)); - }); - return this; - } - }, - destroy: function destroy() { - ttEach(this, function(typeahead, $input) { - revert($input); - typeahead.destroy(); - }); - return this; - } - }; - $.fn.typeahead = function(method) { - if (methods[method]) { - return methods[method].apply(this, [].slice.call(arguments, 1)); - } else { - return methods.initialize.apply(this, arguments); - } - }; - $.fn.typeahead.noConflict = function noConflict() { - $.fn.typeahead = old; - return this; - }; - function ttEach($els, fn) { - $els.each(function() { - var $input = $(this), typeahead; - (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input); - }); - } - function buildHintFromInput($input, www) { - return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop({ - readonly: true, - required: false - }).removeAttr("id name placeholder").removeClass("required").attr({ - spellcheck: "false", - tabindex: -1 - }); - } - function prepInput($input, www) { - $input.data(keys.attrs, { - dir: $input.attr("dir"), - autocomplete: $input.attr("autocomplete"), - spellcheck: $input.attr("spellcheck"), - style: $input.attr("style") - }); - $input.addClass(www.classes.input).attr({ - spellcheck: false - }); - try { - !$input.attr("dir") && $input.attr("dir", "auto"); - } catch (e) {} - return $input; - } - function getBackgroundStyles($el) { - return { - backgroundAttachment: $el.css("background-attachment"), - backgroundClip: $el.css("background-clip"), - backgroundColor: $el.css("background-color"), - backgroundImage: $el.css("background-image"), - backgroundOrigin: $el.css("background-origin"), - backgroundPosition: $el.css("background-position"), - backgroundRepeat: $el.css("background-repeat"), - backgroundSize: $el.css("background-size") - }; - } - function revert($input) { - var www, $wrapper; - www = $input.data(keys.www); - $wrapper = $input.parent().filter(www.selectors.wrapper); - _.each($input.data(keys.attrs), function(val, key) { - _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); - }); - $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input); - if ($wrapper.length) { - $input.detach().insertAfter($wrapper); - $wrapper.remove(); - } - } - function $elOrNull(obj) { - var isValid, $el; - isValid = _.isJQuery(obj) || _.isElement(obj); - $el = isValid ? $(obj).first() : []; - return $el.length ? $el : null; - } - })(); -}); \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/search.json b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/search.json deleted file mode 100644 index b2282cd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/search.json +++ /dev/null @@ -1 +0,0 @@ -{"Typealiases.html#/s:9Alamofire10Parametersa":{"name":"Parameters","abstract":"

A dictionary of parameters to apply to a URLRequest.

"},"Typealiases.html#/s:9Alamofire12AdaptHandlera":{"name":"AdaptHandler","abstract":"

RequestAdapter closure definition.

"},"Typealiases.html#/s:9Alamofire12RetryHandlera":{"name":"RetryHandler","abstract":"

RequestRetrier closure definition.

"},"Typealiases.html#/s:9Alamofire14AFDataResponsea":{"name":"AFDataResponse","abstract":"

Default type of DataResponse returned by Alamofire, with an AFError Failure type.

"},"Typealiases.html#/s:9Alamofire18AFDownloadResponsea":{"name":"AFDownloadResponse","abstract":"

Default type of DownloadResponse returned by Alamofire, with an AFError Failure type.

"},"Typealiases.html#/s:9Alamofire8AFResulta":{"name":"AFResult","abstract":"

Default type of Result returned by Alamofire, with an AFError Failure type.

"},"Structs/Empty.html#/s:9Alamofire5EmptyV5valueACvpZ":{"name":"value","abstract":"

Static Empty instance used for all Empty responses.

","parent_name":"Empty"},"Structs/Empty.html#/s:9Alamofire13EmptyResponseP10emptyValuexyFZ":{"name":"emptyValue()","parent_name":"Empty"},"Structs/GoogleXSSIPreprocessor.html#/s:9Alamofire22GoogleXSSIPreprocessorVACycfc":{"name":"init()","abstract":"

Undocumented

","parent_name":"GoogleXSSIPreprocessor"},"Structs/GoogleXSSIPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","parent_name":"GoogleXSSIPreprocessor"},"Structs/PassthroughPreprocessor.html#/s:9Alamofire23PassthroughPreprocessorVACycfc":{"name":"init()","abstract":"

Undocumented

","parent_name":"PassthroughPreprocessor"},"Structs/PassthroughPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","parent_name":"PassthroughPreprocessor"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

The URL request sent to the server.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

The server’s response to the URL request.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7fileURL10Foundation0E0VSgvp":{"name":"fileURL","abstract":"

The final destination URL of the data returned from the server after it is moved.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV10resumeData10Foundation0E0VSgvp":{"name":"resumeData","abstract":"

The resume data generated if the request was cancelled.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

The final metrics of the response.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV21serializationDurationSdvp":{"name":"serializationDuration","abstract":"

The time taken to serialize the response.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV6results6ResultOyxq_Gvp":{"name":"result","abstract":"

The result of response serialization.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV5valuexSgvp":{"name":"value","abstract":"

Returns the associated value of the result if it is a success, nil otherwise.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV5errorq_Sgvp":{"name":"error","abstract":"

Returns the associated error value if the result if it is a failure, nil otherwise.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7request8response7fileURL10resumeData7metrics21serializationDuration6resultACyxq_G10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAL0G0VSgAL0I0VSgSo23NSURLSessionTaskMetricsCSgSds6ResultOyxq_Gtcfc":{"name":"init(request:response:fileURL:resumeData:metrics:serializationDuration:result:)","abstract":"

Creates a DownloadResponse instance with the specified parameters derived from response serialization.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV11descriptionSSvp":{"name":"description","abstract":"

The textual representation used when written to an output stream, which includes whether the result was a","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV16debugDescriptionSSvp":{"name":"debugDescription","abstract":"

The debug textual representation used when written to an output stream, which includes the URL request, the URL","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV3mapyACyqd__q_Gqd__xXElF":{"name":"map(_:)","abstract":"

Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV6tryMapyACyqd__s5Error_pGqd__xKXElF":{"name":"tryMap(_:)","abstract":"

Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV8mapErroryACyxqd__Gqd__q_XEs0E0Rd__lF":{"name":"mapError(_:)","abstract":"

Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV11tryMapErroryACyxs0F0_pGqd__q_KXEsAERd__lF":{"name":"tryMapError(_:)","abstract":"

Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DownloadResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

The URL request sent to the server.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

The server’s response to the URL request.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV4data10Foundation0B0VSgvp":{"name":"data","abstract":"

The data returned by the server.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

The final metrics of the response.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV21serializationDurationSdvp":{"name":"serializationDuration","abstract":"

The time taken to serialize the response.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV6results6ResultOyxq_Gvp":{"name":"result","abstract":"

The result of response serialization.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV5valuexSgvp":{"name":"value","abstract":"

Returns the associated value of the result if it is a success, nil otherwise.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV5errorq_Sgvp":{"name":"error","abstract":"

Returns the associated error value if the result if it is a failure, nil otherwise.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7request8response4data7metrics21serializationDuration6resultACyxq_G10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgSo23NSURLSessionTaskMetricsCSgSds6ResultOyxq_Gtcfc":{"name":"init(request:response:data:metrics:serializationDuration:result:)","abstract":"

Creates a DataResponse instance with the specified parameters derived from the response serialization.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV11descriptionSSvp":{"name":"description","abstract":"

The textual representation used when written to an output stream, which includes whether the result was a","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV16debugDescriptionSSvp":{"name":"debugDescription","abstract":"

The debug textual representation used when written to an output stream, which includes the URL request, the URL","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV3mapyACyqd__q_Gqd__xXElF":{"name":"map(_:)","abstract":"

Evaluates the specified closure when the result of this DataResponse is a success, passing the unwrapped","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV6tryMapyACyqd__s5Error_pGqd__xKXElF":{"name":"tryMap(_:)","abstract":"

Evaluates the given closure when the result of this DataResponse is a success, passing the unwrapped result","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV8mapErroryACyxqd__Gqd__q_XEs0E0Rd__lF":{"name":"mapError(_:)","abstract":"

Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV11tryMapErroryACyxs0F0_pGqd__q_KXEsAERd__lF":{"name":"tryMapError(_:)","abstract":"

Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DataResponse"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO6followyA2EmF":{"name":"follow","abstract":"

Follow the redirect as defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO11doNotFollowyA2EmF":{"name":"doNotFollow","abstract":"

Do not follow the redirect defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO6modifyyAE10Foundation10URLRequestVSgSo16NSURLSessionTaskC_AISo17NSHTTPURLResponseCtccAEmF":{"name":"modify(_:)","abstract":"

Modify the redirect request defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html":{"name":"Behavior","abstract":"

Defines the behavior of the Redirector type.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV6followACvpZ":{"name":"follow","abstract":"

Returns a Redirector with a .follow Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV11doNotFollowACvpZ":{"name":"doNotFollow","abstract":"

Returns a Redirector with a .doNotFollow Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV8behaviorAC8BehaviorOvp":{"name":"behavior","abstract":"

The Behavior of the Redirector.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV8behaviorA2C8BehaviorO_tcfc":{"name":"init(behavior:)","abstract":"

Creates a Redirector instance from the Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire15RedirectHandlerP4task_18willBeRedirectedTo3for10completionySo16NSURLSessionTaskC_10Foundation10URLRequestVSo17NSHTTPURLResponseCyALSgctF":{"name":"task(_:willBeRedirectedTo:for:completion:)","parent_name":"Redirector"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7defaultACvpZ":{"name":"default","abstract":"

Returns a JSONEncoding instance with default writing options.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV13prettyPrintedACvpZ":{"name":"prettyPrinted","abstract":"

Returns a JSONEncoding instance with .prettyPrinted writing options.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7optionsSo20NSJSONWritingOptionsVvp":{"name":"options","abstract":"

The options for writing the parameters as JSON data.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7optionsACSo20NSJSONWritingOptionsV_tcfc":{"name":"init(options:)","abstract":"

Creates an instance using the specified WritingOptions.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV6encode_14withJSONObject10Foundation10URLRequestVAA0G11Convertible_p_ypSgtKF":{"name":"encode(_:withJSONObject:)","abstract":"

Encodes any JSON compatible object into a URLRequest.

","parent_name":"JSONEncoding"},"Structs/URLEncoding/BoolEncoding.html#/s:9Alamofire11URLEncodingV12BoolEncodingO7numericyA2EmF":{"name":"numeric","abstract":"

Encode true as 1 and false as 0. This is the default behavior.

","parent_name":"BoolEncoding"},"Structs/URLEncoding/BoolEncoding.html#/s:9Alamofire11URLEncodingV12BoolEncodingO7literalyA2EmF":{"name":"literal","abstract":"

Encode true and false as string literals.

","parent_name":"BoolEncoding"},"Structs/URLEncoding/ArrayEncoding.html#/s:9Alamofire11URLEncodingV13ArrayEncodingO8bracketsyA2EmF":{"name":"brackets","abstract":"

An empty set of square brackets is appended to the key for every value. This is the default behavior.

","parent_name":"ArrayEncoding"},"Structs/URLEncoding/ArrayEncoding.html#/s:9Alamofire11URLEncodingV13ArrayEncodingO10noBracketsyA2EmF":{"name":"noBrackets","abstract":"

No brackets are appended. The key is encoded as is.

","parent_name":"ArrayEncoding"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO15methodDependentyA2EmF":{"name":"methodDependent","abstract":"

Applies encoded query string result to existing query string for GET, HEAD and DELETE requests and","parent_name":"Destination"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO11queryStringyA2EmF":{"name":"queryString","abstract":"

Sets or appends encoded query string result to existing query string.

","parent_name":"Destination"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO8httpBodyyA2EmF":{"name":"httpBody","abstract":"

Sets encoded query string result as the HTTP body of the URL request.

","parent_name":"Destination"},"Structs/URLEncoding/Destination.html":{"name":"Destination","abstract":"

Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the","parent_name":"URLEncoding"},"Structs/URLEncoding/ArrayEncoding.html":{"name":"ArrayEncoding","abstract":"

Configures how Array parameters are encoded.

","parent_name":"URLEncoding"},"Structs/URLEncoding/BoolEncoding.html":{"name":"BoolEncoding","abstract":"

Configures how Bool parameters are encoded.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV7defaultACvpZ":{"name":"default","abstract":"

Returns a default URLEncoding instance with a .methodDependent destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11queryStringACvpZ":{"name":"queryString","abstract":"

Returns a URLEncoding instance with a .queryString destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV8httpBodyACvpZ":{"name":"httpBody","abstract":"

Returns a URLEncoding instance with an .httpBody destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11destinationAC11DestinationOvp":{"name":"destination","abstract":"

The destination defining where the encoded query string is to be applied to the URL request.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV13arrayEncodingAC05ArrayD0Ovp":{"name":"arrayEncoding","abstract":"

The encoding to use for Array parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV12boolEncodingAC04BoolD0Ovp":{"name":"boolEncoding","abstract":"

The encoding to use for Bool parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11destination13arrayEncoding04boolE0A2C11DestinationO_AC05ArrayE0OAC04BoolE0Otcfc":{"name":"init(destination:arrayEncoding:boolEncoding:)","abstract":"

Creates an instance using the specified parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV15queryComponents7fromKey5valueSaySS_SStGSS_yptF":{"name":"queryComponents(fromKey:value:)","abstract":"

Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV6escapeyS2SF":{"name":"escape(_:)","abstract":"

Creates a percent-escaped string following RFC 3986 for a query string key or value.

","parent_name":"URLEncoding"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV7connectACvpZ":{"name":"connect","abstract":"

CONNECT method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV6deleteACvpZ":{"name":"delete","abstract":"

DELETE method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV3getACvpZ":{"name":"get","abstract":"

GET method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV4headACvpZ":{"name":"head","abstract":"

HEAD method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV7optionsACvpZ":{"name":"options","abstract":"

OPTIONS method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV5patchACvpZ":{"name":"patch","abstract":"

PATCH method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV4postACvpZ":{"name":"post","abstract":"

POST method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV3putACvpZ":{"name":"put","abstract":"

PUT method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV5traceACvpZ":{"name":"trace","abstract":"

TRACE method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:SY8rawValue03RawB0Qzvp":{"name":"rawValue","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:SY8rawValuexSg03RawB0Qz_tcfc":{"name":"init(rawValue:)","parent_name":"HTTPMethod"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV4nameSSvp":{"name":"name","abstract":"

Name of the header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV5valueSSvp":{"name":"value","abstract":"

Value of the header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV4name5valueACSS_SStcfc":{"name":"init(name:value:)","abstract":"

Creates an instance from the given name and value.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV6acceptyACSSFZ":{"name":"accept(_:)","abstract":"

Returns an Accept header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13acceptCharsetyACSSFZ":{"name":"acceptCharset(_:)","abstract":"

Returns an Accept-Charset header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV14acceptLanguageyACSSFZ":{"name":"acceptLanguage(_:)","abstract":"

Returns an Accept-Language header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV14acceptEncodingyACSSFZ":{"name":"acceptEncoding(_:)","abstract":"

Returns an Accept-Encoding header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorization8username8passwordACSS_SStFZ":{"name":"authorization(username:password:)","abstract":"

Returns a Basic Authorization header using the username and password provided.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorization11bearerTokenACSS_tFZ":{"name":"authorization(bearerToken:)","abstract":"

Returns a Bearer Authorization header using the bearerToken provided

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorizationyACSSFZ":{"name":"authorization(_:)","abstract":"

Returns an Authorization header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV18contentDispositionyACSSFZ":{"name":"contentDisposition(_:)","abstract":"

Returns a Content-Disposition header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV11contentTypeyACSSFZ":{"name":"contentType(_:)","abstract":"

Returns a Content-Type header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV9userAgentyACSSFZ":{"name":"userAgent(_:)","abstract":"

Returns a User-Agent header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV21defaultAcceptEncodingACvpZ":{"name":"defaultAcceptEncoding","abstract":"

Returns Alamofire’s default Accept-Encoding header, appropriate for the encodings supported by particular OS","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV21defaultAcceptLanguageACvpZ":{"name":"defaultAcceptLanguage","abstract":"

Returns Alamofire’s default Accept-Language header, generated by querying Locale for the user’s","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV16defaultUserAgentACvpZ":{"name":"defaultUserAgent","abstract":"

Returns Alamofire’s default User-Agent header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVACycfc":{"name":"init()","abstract":"

Creates an empty instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVyACSayAA10HTTPHeaderVGcfc":{"name":"init(_:)","abstract":"

Creates an instance from an array of HTTPHeaders. Duplicate case-insensitive names are collapsed into the last","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVyACSDyS2SGcfc":{"name":"init(_:)","abstract":"

Creates an instance from a [String: String]. Duplicate case-insensitive names are collapsed into the last name","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV3add4name5valueySS_SStF":{"name":"add(name:value:)","abstract":"

Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV3addyyAA10HTTPHeaderVF":{"name":"add(_:)","abstract":"

Case-insensitively updates or appends the provided HTTPHeader into the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6update4name5valueySS_SStF":{"name":"update(name:value:)","abstract":"

Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6updateyyAA10HTTPHeaderVF":{"name":"update(_:)","abstract":"

Case-insensitively updates or appends the provided HTTPHeader into the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6remove4nameySS_tF":{"name":"remove(name:)","abstract":"

Case-insensitively removes an HTTPHeader, if it exists, from the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV4sortyyF":{"name":"sort()","abstract":"

Sort the current instance by header name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6sortedACyF":{"name":"sorted()","abstract":"

Returns an instance sorted by header name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV5value3forSSSgSS_tF":{"name":"value(for:)","abstract":"

Case-insensitively find a header’s value by name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVySSSgSScip":{"name":"subscript(_:)","abstract":"

Case-insensitively access the header with the given name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV10dictionarySDyS2SGvp":{"name":"dictionary","abstract":"

The dictionary representation of all headers.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s30ExpressibleByDictionaryLiteralP010dictionaryD0x3KeyQz_5ValueQztd_tcfc":{"name":"init(dictionaryLiteral:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s25ExpressibleByArrayLiteralP05arrayD0x0cD7ElementQzd_tcfc":{"name":"init(arrayLiteral:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:ST12makeIterator0B0QzyF":{"name":"makeIterator()","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl10startIndex0B0Qzvp":{"name":"startIndex","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl8endIndex0B0Qzvp":{"name":"endIndex","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sly7ElementQz5IndexQzcip":{"name":"subscript(_:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl5index5after5IndexQzAD_tF":{"name":"index(after:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV7defaultACvpZ":{"name":"default","abstract":"

The default set of HTTPHeaders used by Alamofire. Includes Accept-Encoding, Accept-Language, and","parent_name":"HTTPHeaders"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO5cacheyA2EmF":{"name":"cache","abstract":"

Stores the cached response in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO10doNotCacheyA2EmF":{"name":"doNotCache","abstract":"

Prevents the cached response from being stored in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO6modifyyAESo19NSCachedURLResponseCSgSo20NSURLSessionDataTaskC_AHtccAEmF":{"name":"modify(_:)","abstract":"

Modifies the cached response before storing it in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html":{"name":"Behavior","abstract":"

Defines the behavior of the ResponseCacher type.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV5cacheACvpZ":{"name":"cache","abstract":"

Returns a ResponseCacher with a follow Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV10doNotCacheACvpZ":{"name":"doNotCache","abstract":"

Returns a ResponseCacher with a do not follow Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV8behaviorAC8BehaviorOvp":{"name":"behavior","abstract":"

The Behavior of the ResponseCacher.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV8behaviorA2C8BehaviorO_tcfc":{"name":"init(behavior:)","abstract":"

Creates a ResponseCacher instance from the Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire21CachedResponseHandlerP8dataTask_09willCacheC010completionySo016NSURLSessionDataF0C_So19NSCachedURLResponseCyAJSgctF":{"name":"dataTask(_:willCacheResponse:completion:)","parent_name":"ResponseCacher"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE12certificatesSaySo17SecCertificateRefaGvp":{"name":"certificates","abstract":"

Returns all valid cer, crt, and der certificates in the bundle.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE10publicKeysSaySo9SecKeyRefaGvp":{"name":"publicKeys","abstract":"

Returns all public keys for the valid certificates in the bundle.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE5paths19forResourcesOfTypesSaySSGAH_tF":{"name":"paths(forResourcesOfTypes:)","abstract":"

Returns all pathnames for the resources identified by the provided file extensions.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8evaluate13afterApplyingySo0c6PolicyE0a_tKF":{"name":"evaluate(afterApplying:)","abstract":"

Evaluates self after applying the SecPolicy value provided.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8validate6policy13errorProducerySo0c6PolicyE0a_s5Error_ps5Int32V_So0cD10ResultTypeVtXEtKF":{"name":"validate(policy:errorProducer:)","abstract":"

Attempts to validate self using the SecPolicy provided and transforming any error produced using the closure passed.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE5apply6policyAESo0c6PolicyE0a_tKF":{"name":"apply(policy:)","abstract":"

Applies a SecPolicy to self, throwing if it fails.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8evaluateyyKF":{"name":"evaluate()","abstract":"

Evaluate self, throwing an Error if evaluation fails.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8validate13errorProducerys5Error_ps5Int32V_So0cD10ResultTypeVtXE_tKF":{"name":"validate(errorProducer:)","abstract":"

Validate self, passing any failure values through errorProducer.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE21setAnchorCertificatesyySaySo0c11CertificateE0aGKF":{"name":"setAnchorCertificates(_:)","abstract":"

Sets a custom certificate chain on self, allowing full validation of a self-signed certificate and its chain.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE10publicKeysSaySo0c3KeyE0aGvp":{"name":"publicKeys","abstract":"

The public keys contained in self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE12certificatesSaySo0c11CertificateE0aGvp":{"name":"certificates","abstract":"

The SecCertificates contained i self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE15certificateDataSay10Foundation0G0VGvp":{"name":"certificateData","abstract":"

The Data values for all certificates contained in self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE24performDefaultValidation7forHostySS_tKF":{"name":"performDefaultValidation(forHost:)","abstract":"

Validates self after applying SecPolicy.af.default. This evaluation does not validate the hostname.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE17performValidation7forHostySS_tKF":{"name":"performValidation(forHost:)","abstract":"

Validates self after applying SecPolicy.af.hostname(host), which performs the default validation as well as","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE7defaultAEvpZ":{"name":"default","abstract":"

Creates a SecPolicy instance which will validate server certificates but not require a host name match.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE8hostnameyAESSFZ":{"name":"hostname(_:)","abstract":"

Creates a SecPolicy instance which will validate server certificates and much match the provided hostname.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE10revocation7optionsAeA24RevocationTrustEvaluatorC7OptionsV_tKFZ":{"name":"revocation(options:)","abstract":"

Creates a SecPolicy which checks the revocation of certificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASaySo17SecCertificateRefaGRszlE4dataSay10Foundation4DataVGvp":{"name":"data","abstract":"

All Data values for the contained SecCertificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASaySo17SecCertificateRefaGRszlE10publicKeysSaySo0c3KeyE0aGvp":{"name":"publicKeys","abstract":"

All public SecKey values for the contained SecCertificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo17SecCertificateRefaRszlE9publicKeySo0cgE0aSgvp":{"name":"publicKey","abstract":"

The public key for self, if it can be extracted.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAAs5Int32VRszlE9isSuccessSbvp":{"name":"isSuccess","abstract":"

Returns whether self is errSecSuccess.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo18SecTrustResultTypeVRszlE9isSuccessSbvp":{"name":"isSuccess","abstract":"

Returns whether self is.unspecifiedor.proceed`.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo25NSURLSessionConfigurationCRbzlE7defaultAEvpZ":{"name":"default","abstract":"

Alamofire’s default configuration. Same as URLSessionConfiguration.default but adds Alamofire default","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html":{"name":"AlamofireExtension","abstract":"

Type that acts as a generic extension point for all AlamofireExtended types.

"},"Structs/ResponseCacher.html":{"name":"ResponseCacher","abstract":"

ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached"},"Structs/HTTPHeaders.html":{"name":"HTTPHeaders","abstract":"

An order-preserving and case-insensitive representation of HTTP headers.

"},"Structs/HTTPHeader.html":{"name":"HTTPHeader","abstract":"

A representation of a single HTTP header’s name / value pair.

"},"Structs/HTTPMethod.html":{"name":"HTTPMethod","abstract":"

Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so"},"Structs/URLEncoding.html":{"name":"URLEncoding","abstract":"

Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP"},"Structs/JSONEncoding.html":{"name":"JSONEncoding","abstract":"

Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the"},"Structs/Redirector.html":{"name":"Redirector","abstract":"

Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

"},"Structs/DataResponse.html":{"name":"DataResponse","abstract":"

Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

"},"Structs/DownloadResponse.html":{"name":"DownloadResponse","abstract":"

Used to store all data associated with a serialized response of a download request.

"},"Structs/PassthroughPreprocessor.html":{"name":"PassthroughPreprocessor","abstract":"

DataPreprocessor that returns passed Data without any transform.

"},"Structs/GoogleXSSIPreprocessor.html":{"name":"GoogleXSSIPreprocessor","abstract":"

DataPreprocessor that trims Google’s typical )]}',\\n XSSI JSON header.

"},"Structs/Empty.html":{"name":"Empty","abstract":"

Type representing an empty response. Use Empty.value to get the static instance.

"},"Protocols/URLRequestConvertible.html#/s:9Alamofire21URLRequestConvertibleP02asB010Foundation0B0VyKF":{"name":"asURLRequest()","abstract":"

Returns a URLRequest or throws if an Error was encountered.

","parent_name":"URLRequestConvertible"},"Protocols/URLRequestConvertible.html#/s:9Alamofire21URLRequestConvertiblePAAE10urlRequest10Foundation0B0VSgvp":{"name":"urlRequest","abstract":"

The URLRequest returned by discarding any Error encountered.

","parent_name":"URLRequestConvertible"},"Protocols/URLConvertible.html#/s:9Alamofire14URLConvertibleP5asURL10Foundation0D0VyKF":{"name":"asURL()","abstract":"

Returns a URL from the conforming instance or throws.

","parent_name":"URLConvertible"},"Protocols/ServerTrustEvaluating.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","abstract":"

Evaluates the given SecTrust value for the given host.

","parent_name":"ServerTrustEvaluating"},"Protocols/DataDecoder.html#/s:9Alamofire11DataDecoderP6decode_4fromqd__qd__m_10Foundation0B0VtKSeRd__lF":{"name":"decode(_:from:)","abstract":"

Decode Data into the provided type.

","parent_name":"DataDecoder"},"Protocols/EmptyResponse.html#/s:9Alamofire13EmptyResponseP10emptyValuexyFZ":{"name":"emptyValue()","abstract":"

Empty value for the conforming type.

","parent_name":"EmptyResponse"},"Protocols/DataPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","abstract":"

Process Data before it’s handled by a serializer.

","parent_name":"DataPreprocessor"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","abstract":"

DataPreprocessor used to prepare incoming Data for serialization.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","abstract":"

HTTPMethods for which empty response bodies are considered appropriate.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","abstract":"

HTTP response codes for which empty response bodies are considered appropriate.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE23defaultDataPreprocessorAA0eF0_pvpZ":{"name":"defaultDataPreprocessor","abstract":"

Default DataPreprocessor. PassthroughPreprocessor by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE26defaultEmptyRequestMethodsShyAA10HTTPMethodVGvpZ":{"name":"defaultEmptyRequestMethods","abstract":"

Default HTTPMethods for which empty response bodies are considered appropriate. [.head] by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE012defaultEmptyB5CodesShySiGvpZ":{"name":"defaultEmptyResponseCodes","abstract":"

HTTP response codes for which empty response bodies are considered appropriate. [204, 205] by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE018requestAllowsEmptyB4DataySbSg10Foundation10URLRequestVSgF":{"name":"requestAllowsEmptyResponseData(_:)","abstract":"

Determines whether the request allows empty response bodies, if request exists.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE019responseAllowsEmptyB4DataySbSgSo17NSHTTPURLResponseCSgF":{"name":"responseAllowsEmptyResponseData(_:)","abstract":"

Determines whether the response allows empty response bodies, if response exists`.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE05emptyB7Allowed10forRequest8responseSb10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgtF":{"name":"emptyResponseAllowed(forRequest:response:)","abstract":"

Determines whether request and response allow empty response bodies.

","parent_name":"ResponseSerializer"},"Protocols/DownloadResponseSerializerProtocol.html#/s:9Alamofire34DownloadResponseSerializerProtocolP16SerializedObjectQa":{"name":"SerializedObject","abstract":"

The type of serialized object to be created.

","parent_name":"DownloadResponseSerializerProtocol"},"Protocols/DownloadResponseSerializerProtocol.html#/s:9Alamofire34DownloadResponseSerializerProtocolP09serializeB07request8response7fileURL5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0J0VSgs5Error_pSgtKF":{"name":"serializeDownload(request:response:fileURL:error:)","abstract":"

Serialize the downloaded response Data from disk into the provided type..

","parent_name":"DownloadResponseSerializerProtocol"},"Protocols/DataResponseSerializerProtocol.html#/s:9Alamofire30DataResponseSerializerProtocolP16SerializedObjectQa":{"name":"SerializedObject","abstract":"

The type of serialized object to be created.

","parent_name":"DataResponseSerializerProtocol"},"Protocols/DataResponseSerializerProtocol.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","abstract":"

Serialize the response Data into the provided type..

","parent_name":"DataResponseSerializerProtocol"},"Protocols/RequestInterceptor.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"RequestInterceptor"},"Protocols/RequestInterceptor.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"RequestInterceptor"},"Protocols/RequestRetrier.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","abstract":"

Determines whether the Request should be retried by calling the completion closure.

","parent_name":"RequestRetrier"},"Protocols/RequestAdapter.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","abstract":"

Inspects and adapts the specified URLRequest in some manner and calls the completion handler with the Result.

","parent_name":"RequestAdapter"},"Protocols/UploadableConvertible.html#/s:9Alamofire21UploadableConvertibleP06createB0AA13UploadRequestC0B0OyKF":{"name":"createUploadable()","abstract":"

Produces an UploadRequest.Uploadable value from the instance.

","parent_name":"UploadableConvertible"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP20sessionConfigurationSo012NSURLSessionE0Cvp":{"name":"sessionConfiguration","abstract":"

URLSessionConfiguration used to create the underlying URLSessionTasks.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP16startImmediatelySbvp":{"name":"startImmediately","abstract":"

Determines whether the Request should automatically call resume() when adding the first response handler.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP7cleanup5afteryAA0B0C_tF":{"name":"cleanup(after:)","abstract":"

Notifies the delegate the Request has reached a point where it needs cleanup.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP11retryResult3for5dueTo10completionyAA0B0C_AA7AFErrorOyAA05RetryE0OctF":{"name":"retryResult(for:dueTo:completion:)","abstract":"

Asynchronously ask the delegate whether a Request will be retried.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP05retryB0_9withDelayyAA0B0C_SdSgtF":{"name":"retryRequest(_:withDelay:)","abstract":"

Asynchronously retry the Request.

","parent_name":"RequestDelegate"},"Protocols/RedirectHandler.html#/s:9Alamofire15RedirectHandlerP4task_18willBeRedirectedTo3for10completionySo16NSURLSessionTaskC_10Foundation10URLRequestVSo17NSHTTPURLResponseCyALSgctF":{"name":"task(_:willBeRedirectedTo:for:completion:)","abstract":"

Determines how the HTTP redirect response should be redirected to the new request.

","parent_name":"RedirectHandler"},"Protocols/ParameterEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","abstract":"

Creates a URLRequest by encoding parameters and applying them on the passed request.

","parent_name":"ParameterEncoding"},"Protocols/ParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","abstract":"

Encode the provided Encodable parameters into request.

","parent_name":"ParameterEncoder"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","abstract":"

The DispatchQueue onto which Alamofire’s root CompositeEventMonitor will dispatch events. .main by default.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","abstract":"

Event called during URLSessionDelegate‘s urlSession(_:didBecomeInvalidWithError:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didReceive:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:needNewBodyStream:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didFinishCollecting:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didCompleteWithError:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:taskIsWaitingForConnectivity:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","abstract":"

Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:didReceive:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","abstract":"

Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:willCacheResponse:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didFinishDownloadingTo:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","abstract":"

Event called when a URLRequest is first created for a Request. If a RequestAdapter is active, the","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","abstract":"

Event called when the attempt to create a URLRequest from a Request‘s original URLRequestConvertible value fails.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","abstract":"

Event called when a RequestAdapter adapts the Request‘s initial URLRequest.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","abstract":"

Event called when a RequestAdapter fails to adapt the Request‘s initial URLRequest.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","abstract":"

Event called when a final URLRequest is created for a Request.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","abstract":"

Event called when a URLSessionTask subclass instance is created for a Request.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","abstract":"

Event called when a Request receives a URLSessionTaskMetrics value.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","abstract":"

Event called when a Request fails due to an error created by Alamofire. e.g. When certificate pinning fails.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","abstract":"

Event called when a Request‘s task completes, possibly with an error. A Request may receive this event","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","abstract":"

Event called when a Request is about to be retried.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","abstract":"

Event called when a Request finishes and response serializers are being called.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","abstract":"

Event called when a Request receives a resume call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is resumed.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","abstract":"

Event called when a Request receives a suspend call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is suspended.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","abstract":"

Event called when a Request receives a cancel call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is cancelled.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","abstract":"

Event called when a DataRequest calls a Validation.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DataRequest creates a DataResponse<Data?> value without calling a ResponseSerializer.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DataRequest calls a ResponseSerializer and creates a generic DataResponse<Value, AFError>.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","abstract":"

Event called when an UploadRequest creates its Uploadable value, indicating the type of upload it represents.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","abstract":"

Event called when an UploadRequest failed to create its Uploadable value due to an error.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","abstract":"

Event called when an UploadRequest provides the InputStream from its Uploadable value. This only occurs if","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","abstract":"

Event called when a DownloadRequest‘s URLSessionDownloadTask finishes and the temporary file has been moved.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","abstract":"

Event called when a DownloadRequest‘s Destination closure is called and creates the destination URL the","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","abstract":"

Event called when a DownloadRequest calls a Validation.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DownloadRequest creates a DownloadResponse<URL?, AFError> without calling a ResponseSerializer.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DownloadRequest calls a DownloadResponseSerializer and creates a generic DownloadResponse<Value, AFError>

","parent_name":"EventMonitor"},"Protocols/CachedResponseHandler.html#/s:9Alamofire21CachedResponseHandlerP8dataTask_09willCacheC010completionySo016NSURLSessionDataF0C_So19NSCachedURLResponseCyAJSgctF":{"name":"dataTask(_:willCacheResponse:completion:)","abstract":"

Determines whether the HTTP response should be stored in the cache.

","parent_name":"CachedResponseHandler"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP0B4TypeQa":{"name":"ExtendedType","abstract":"

Type being extended.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP2afAA0A9ExtensionVy0B4TypeQzGmvpZ":{"name":"af","abstract":"

Static Alamofire extension point.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP2afAA0A9ExtensionVy0B4TypeQzGvp":{"name":"af","abstract":"

Instance Alamofire extension point.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html":{"name":"AlamofireExtended","abstract":"

Protocol describing the af extension points for Alamofire extended types.

"},"Protocols/CachedResponseHandler.html":{"name":"CachedResponseHandler","abstract":"

A type that handles whether the data task should store the HTTP response in the cache.

"},"Protocols/EventMonitor.html":{"name":"EventMonitor","abstract":"

Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various"},"Protocols/ParameterEncoder.html":{"name":"ParameterEncoder","abstract":"

A type that can encode any Encodable type into a URLRequest.

"},"Protocols/ParameterEncoding.html":{"name":"ParameterEncoding","abstract":"

A type used to define how a set of parameters are applied to a URLRequest.

"},"Protocols/RedirectHandler.html":{"name":"RedirectHandler","abstract":"

A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

"},"Protocols/RequestDelegate.html":{"name":"RequestDelegate","abstract":"

Protocol abstraction for Request‘s communication back to the SessionDelegate.

"},"Protocols/UploadableConvertible.html":{"name":"UploadableConvertible","abstract":"

A type that can produce an UploadRequest.Uploadable value.

"},"Protocols.html#/s:9Alamofire17UploadConvertibleP":{"name":"UploadConvertible","abstract":"

A type that can be converted to an upload, whether from an UploadRequest.Uploadable or URLRequestConvertible.

"},"Protocols/RequestAdapter.html":{"name":"RequestAdapter","abstract":"

A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

"},"Protocols/RequestRetrier.html":{"name":"RequestRetrier","abstract":"

A type that determines whether a request should be retried after being executed by the specified session manager"},"Protocols/RequestInterceptor.html":{"name":"RequestInterceptor","abstract":"

Type that provides both RequestAdapter and RequestRetrier functionality.

"},"Protocols/DataResponseSerializerProtocol.html":{"name":"DataResponseSerializerProtocol","abstract":"

The type to which all data response serializers must conform in order to serialize a response.

"},"Protocols/DownloadResponseSerializerProtocol.html":{"name":"DownloadResponseSerializerProtocol","abstract":"

The type to which all download response serializers must conform in order to serialize a response.

"},"Protocols/ResponseSerializer.html":{"name":"ResponseSerializer","abstract":"

A serializer that can handle both data and download responses.

"},"Protocols/DataPreprocessor.html":{"name":"DataPreprocessor","abstract":"

Type used to preprocess Data before it handled by a serializer.

"},"Protocols/EmptyResponse.html":{"name":"EmptyResponse","abstract":"

Protocol representing an empty response. Use T.emptyValue() to get an instance.

"},"Protocols/DataDecoder.html":{"name":"DataDecoder","abstract":"

Any type which can decode Data into a Decodable type.

"},"Protocols/ServerTrustEvaluating.html":{"name":"ServerTrustEvaluating","abstract":"

A protocol describing the API used to evaluate server trusts.

"},"Protocols/URLConvertible.html":{"name":"URLConvertible","abstract":"

Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct"},"Protocols/URLRequestConvertible.html":{"name":"URLRequestConvertible","abstract":"

Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

"},"Extensions/CharacterSet.html#/s:10Foundation12CharacterSetV9AlamofireE17afURLQueryAllowedACvpZ":{"name":"afURLQueryAllowed","abstract":"

Creates a CharacterSet from RFC 3986 allowed characters.

","parent_name":"CharacterSet"},"Extensions/URLComponents.html#/s:10Foundation13URLComponentsV9AlamofireE5asURLAA0E0VyKF":{"name":"asURL()","abstract":"

Returns a URL if the self‘s url is not nil, otherwise throws.

","parent_name":"URLComponents"},"Extensions/URL.html#/s:10Foundation3URLV9AlamofireE02asB0ACyKF":{"name":"asURL()","abstract":"

Returns self.

","parent_name":"URL"},"Extensions/String.html#/s:SS9AlamofireE5asURL10Foundation0C0VyKF":{"name":"asURL()","abstract":"

Returns a URL if self can be used to initialize a URL instance, otherwise throws.

","parent_name":"String"},"Extensions/Array.html#/s:Sa9AlamofireAA21ServerTrustEvaluating_pRszlE8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","abstract":"

Evaluates the given SecTrust value for the given host.

","parent_name":"Array"},"Extensions/Notification.html#/s:10Foundation12NotificationV9AlamofireE7requestAD7RequestCSgvp":{"name":"request","abstract":"

The Request contained by the instance’s userInfo, nil otherwise.

","parent_name":"Notification"},"Extensions/URLSessionConfiguration.html#/s:So25NSURLSessionConfigurationC9AlamofireE7headersAC11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns httpAdditionalHeaders as HTTPHeaders.

","parent_name":"URLSessionConfiguration"},"Extensions/HTTPURLResponse.html#/s:So17NSHTTPURLResponseC9AlamofireE7headersAC11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns allHeaderFields as HTTPHeaders.

","parent_name":"HTTPURLResponse"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE7headersAD11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns allHTTPHeaderFields as HTTPHeaders.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE02asB0ACyKF":{"name":"asURLRequest()","abstract":"

Returns self.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE3url6method7headersAcD14URLConvertible_p_AD10HTTPMethodVAD11HTTPHeadersVSgtKcfc":{"name":"init(url:method:headers:)","abstract":"

Creates an instance with the specified url, method, and headers.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE6methodAD10HTTPMethodVSgvp":{"name":"method","abstract":"

Returns the httpMethod as Alamofire’s HTTPMethod type.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE8validateyyKF":{"name":"validate()","abstract":"

Undocumented

","parent_name":"URLRequest"},"Extensions/Error.html#/s:s5ErrorP9AlamofireE9asAFErrorAC0D0OSgvp":{"name":"asAFError","abstract":"

Returns the instance cast as an AFError.

","parent_name":"Error"},"Extensions/Error.html#/s:s5ErrorP9AlamofireE9asAFError10orFailWith4file4lineAC0D0OSSyXK_s12StaticStringVSutF":{"name":"asAFError(orFailWith:file:line:)","abstract":"

Returns the instance cast as an AFError. If casting fails, a fatalError with the specified message is thrown.

","parent_name":"Error"},"Extensions/Error.html":{"name":"Error"},"Extensions/URLRequest.html":{"name":"URLRequest"},"Extensions/HTTPURLResponse.html":{"name":"HTTPURLResponse"},"Extensions/URLSessionConfiguration.html":{"name":"URLSessionConfiguration"},"Extensions/Notification.html":{"name":"Notification"},"Extensions/Array.html":{"name":"Array"},"Extensions/String.html":{"name":"String"},"Extensions/URL.html":{"name":"URL"},"Extensions/URLComponents.html":{"name":"URLComponents"},"Extensions/CharacterSet.html":{"name":"CharacterSet"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO5retryyA2CmF":{"name":"retry","abstract":"

Retry should be attempted immediately.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO14retryWithDelayyACSdcACmF":{"name":"retryWithDelay(_:)","abstract":"

Retry should be attempted after the associated TimeInterval.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO05doNotB0yA2CmF":{"name":"doNotRetry","abstract":"

Do not retry.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO05doNotB9WithErroryACs0G0_pcACmF":{"name":"doNotRetryWithError(_:)","abstract":"

Do not retry due to the associated AFError.

","parent_name":"RetryResult"},"Enums/AF.html#/s:9Alamofire2AFO7request_6method10parameters8encoding7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtFZ":{"name":"request(_:method:parameters:encoding:headers:interceptor:)","abstract":"

Creates a DataRequest using Session.default to retrieve the contents of the specified url using the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO7request_6method10parameters7encoder7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtSERzlFZ":{"name":"request(_:method:parameters:encoder:headers:interceptor:)","abstract":"

Creates a DataRequest using Session.default to retrieve the contents of the specified url using the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO7request_11interceptorAA11DataRequestCAA21URLRequestConvertible_p_AA0F11Interceptor_pSgtFZ":{"name":"request(_:interceptor:)","abstract":"

Creates a DataRequest using Session.default to execute the specified urlRequest.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_6method10parameters8encoding7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAZ_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(_:method:parameters:encoding:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to download the contents of the specified url to","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_6method10parameters7encoder7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAY_So17NSHTTPURLResponseCtcSgtSERzlFZ":{"name":"download(_:method:parameters:encoder:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to download the contents of the specified url to the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_11interceptor2toAA15DownloadRequestCAA21URLRequestConvertible_p_AA0G11Interceptor_pSg10Foundation3URLV011destinationL0_AH7OptionsV7optionstAN_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(_:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to execute the specified urlRequest and download","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download12resumingWith11interceptor2toAA15DownloadRequestC10Foundation4DataV_AA0I11Interceptor_pSgAJ3URLV011destinationM0_AI7OptionsV7optionstAP_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(resumingWith:interceptor:to:)","abstract":"

Creates a DownloadRequest using the Session.default from the resumeData produced from a previous","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data, URLRequest components, and RequestInterceptor.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data using the URLRequestConvertible value and RequestInterceptor.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL, using a URLRequest from the provided","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL using the URLRequestConvertible value and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the InputStream provided using a URLRequest from the provided components and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the provided InputStream using the URLRequestConvertible value and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtFZ":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the multipart form data built using a closure and sent using the provided","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtFZ":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtFZ":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtFZ":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible","parent_name":"AF"},"Enums/AFError/URLRequestValidationFailureReason.html#/s:9Alamofire7AFErrorO33URLRequestValidationFailureReasonO20bodyDataInGETRequestyAE10Foundation0H0VcAEmF":{"name":"bodyDataInGETRequest(_:)","abstract":"

URLRequest with GET method had body data.

","parent_name":"URLRequestValidationFailureReason"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV4hostSSvp":{"name":"host","abstract":"

The host for which the evaluation was performed.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV5trustSo03SecD3Refavp":{"name":"trust","abstract":"

The SecTrust value which was evaluated.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV6statuss5Int32Vvp":{"name":"status","abstract":"

The OSStatus of evaluation operation.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV6resultSo03SecD10ResultTypeVvp":{"name":"result","abstract":"

The result of the evaluation operation.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html":{"name":"Output","abstract":"

The output of a server trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO19noRequiredEvaluatoryAESS_tcAEmF":{"name":"noRequiredEvaluator(host:)","abstract":"

No ServerTrustEvaluator was found for the associated host.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO19noCertificatesFoundyA2EmF":{"name":"noCertificatesFound","abstract":"

No certificates were found with which to perform the trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO17noPublicKeysFoundyA2EmF":{"name":"noPublicKeysFound","abstract":"

No public keys were found with which to perform the trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO23policyApplicationFailedyAESo03SecD3Refa_So0j6PolicyK0as5Int32VtcAEmF":{"name":"policyApplicationFailed(trust:policy:status:)","abstract":"

During evaluation, application of the associated SecPolicy failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO31settingAnchorCertificatesFailedyAEs5Int32V_SaySo17SecCertificateRefaGtcAEmF":{"name":"settingAnchorCertificatesFailed(status:certificates:)","abstract":"

During evaluation, setting the associated anchor certificates failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO30revocationPolicyCreationFailedyA2EmF":{"name":"revocationPolicyCreationFailed","abstract":"

During evaluation, creation of the revocation policy failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO21trustEvaluationFailedyAEs5Error_pSg_tcAEmF":{"name":"trustEvaluationFailed(error:)","abstract":"

SecTrust evaluation failed with the associated Error, if one was produced.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO23defaultEvaluationFailedyA2E6OutputV_tcAEmF":{"name":"defaultEvaluationFailed(output:)","abstract":"

Default evaluation failed with the associated Output.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO20hostValidationFailedyA2E6OutputV_tcAEmF":{"name":"hostValidationFailed(output:)","abstract":"

Host validation failed with the associated Output.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO21revocationCheckFailedyA2E6OutputV_AA010RevocationD9EvaluatorC7OptionsVtcAEmF":{"name":"revocationCheckFailed(output:options:)","abstract":"

Revocation check failed with the associated Output and options.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO24certificatePinningFailedyAESS_So03SecD3RefaSaySo0j11CertificateK0aGAKtcAEmF":{"name":"certificatePinningFailed(host:trust:pinnedCertificates:serverCertificates:)","abstract":"

Certificate pinning failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO22publicKeyPinningFailedyAESS_So03SecD3RefaSaySo0khL0aGAKtcAEmF":{"name":"publicKeyPinningFailed(host:trust:pinnedKeys:serverKeys:)","abstract":"

Public key pinning failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO22customEvaluationFailedyAEs5Error_p_tcAEmF":{"name":"customEvaluationFailed(error:)","abstract":"

Custom server trust evaluation failed due to the associated Error.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO24inputDataNilOrZeroLengthyA2EmF":{"name":"inputDataNilOrZeroLength","abstract":"

The server response contained no data or the data was zero length.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO12inputFileNilyA2EmF":{"name":"inputFileNil","abstract":"

The file containing the server response did not exist.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO19inputFileReadFailedyAE10Foundation3URLV_tcAEmF":{"name":"inputFileReadFailed(at:)","abstract":"

The file containing the server response could not be read from the associated URL.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO06stringD6FailedyAESS10FoundationE8EncodingV_tcAEmF":{"name":"stringSerializationFailed(encoding:)","abstract":"

String serialization failed using the provided String.Encoding.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO04jsonD6FailedyAEs5Error_p_tcAEmF":{"name":"jsonSerializationFailed(error:)","abstract":"

JSON serialization failed with an underlying system error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO14decodingFailedyAEs5Error_p_tcAEmF":{"name":"decodingFailed(error:)","abstract":"

A DataDecoder failed to decode the response due to the associated Error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customSerializationFailed(error:)","abstract":"

A custom response serializer failed due to the associated Error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO012invalidEmptyC0yAESS_tcAEmF":{"name":"invalidEmptyResponse(type:)","abstract":"

Generic serialization failed for an empty response that wasn’t type Empty but instead the associated type.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO11dataFileNilyA2EmF":{"name":"dataFileNil","abstract":"

The data file containing the server response did not exist.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO18dataFileReadFailedyAE10Foundation3URLV_tcAEmF":{"name":"dataFileReadFailed(at:)","abstract":"

The data file containing the server response at the associated URL could not be read.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO18missingContentTypeyAESaySSG_tcAEmF":{"name":"missingContentType(acceptableContentTypes:)","abstract":"

The response did not contain a Content-Type and the acceptableContentTypes provided did not contain a","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO23unacceptableContentTypeyAESaySSG_SStcAEmF":{"name":"unacceptableContentType(acceptableContentTypes:responseContentType:)","abstract":"

The response Content-Type did not match any type in the provided acceptableContentTypes.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO22unacceptableStatusCodeyAESi_tcAEmF":{"name":"unacceptableStatusCode(code:)","abstract":"

The response status code was not acceptable.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customValidationFailed(error:)","abstract":"

Custom response validation failed due to the associated Error.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO17RequiredComponentO3urlyA2GmF":{"name":"url","abstract":"

The URL was missing or unable to be extracted from the passed URLRequest or during encoding.

","parent_name":"RequiredComponent"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO17RequiredComponentO10httpMethodyAGSS_tcAGmF":{"name":"httpMethod(rawValue:)","abstract":"

The HTTPMethod could not be extracted from the passed URLRequest.

","parent_name":"RequiredComponent"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html":{"name":"RequiredComponent","abstract":"

Possible missing components.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncoderFailureReason.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO24missingRequiredComponentyA2E0hI0OcAEmF":{"name":"missingRequiredComponent(_:)","abstract":"

A RequiredComponent was missing during encoding.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncoderFailureReason.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO13encoderFailedyAEs5Error_p_tcAEmF":{"name":"encoderFailed(error:)","abstract":"

The underlying encoder failed with the associated error.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO10missingURLyA2EmF":{"name":"missingURL","abstract":"

The URLRequest did not have a URL to encode.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO04jsonD6FailedyAEs5Error_p_tcAEmF":{"name":"jsonEncodingFailed(error:)","abstract":"

JSON serialization failed with an underlying system error during the encoding process.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customEncodingFailed(error:)","abstract":"

Custom parameter encoding failed due to the associated Error.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO18bodyPartURLInvalidyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartURLInvalid(url:)","abstract":"

The fileURL provided for reading an encodable body part isn’t a file URL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23bodyPartFilenameInvalidyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFilenameInvalid(in:)","abstract":"

The filename of the fileURL provided has either an empty lastPathComponent or `pathExtension.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO24bodyPartFileNotReachableyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileNotReachable(at:)","abstract":"

The file at the fileURL provided was not reachable.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO33bodyPartFileNotReachableWithErroryAE10Foundation3URLV_s0M0_ptcAEmF":{"name":"bodyPartFileNotReachableWithError(atURL:error:)","abstract":"

Attempting to check the reachability of the fileURL provided threw an error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23bodyPartFileIsDirectoryyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileIsDirectory(at:)","abstract":"

The file at the fileURL provided is actually a directory.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO28bodyPartFileSizeNotAvailableyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileSizeNotAvailable(at:)","abstract":"

The size of the file at the fileURL provided was not returned by the system.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO36bodyPartFileSizeQueryFailedWithErroryAE10Foundation3URLV_s0N0_ptcAEmF":{"name":"bodyPartFileSizeQueryFailedWithError(forURL:error:)","abstract":"

The attempt to find the size of the file at the fileURL provided threw an error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO33bodyPartInputStreamCreationFailedyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartInputStreamCreationFailed(for:)","abstract":"

An InputStream could not be created for the provided fileURL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO26outputStreamCreationFailedyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamCreationFailed(for:)","abstract":"

An OutputStream could not be created when attempting to write the encoded data to disk.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO29outputStreamFileAlreadyExistsyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamFileAlreadyExists(at:)","abstract":"

The encoded body data could not be written to disk because a file already exists at the provided fileURL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO22outputStreamURLInvalidyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamURLInvalid(url:)","abstract":"

The fileURL provided for writing the encoded body data to disk is not a file URL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23outputStreamWriteFailedyAEs5Error_p_tcAEmF":{"name":"outputStreamWriteFailed(error:)","abstract":"

The attempt to write the encoded body data to disk failed with an underlying error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO21inputStreamReadFailedyAEs5Error_p_tcAEmF":{"name":"inputStreamReadFailed(error:)","abstract":"

The attempt to read an encoded body part InputStream failed with underlying system error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html":{"name":"MultipartEncodingFailureReason","abstract":"

The underlying reason the .multipartEncodingFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ParameterEncodingFailureReason.html":{"name":"ParameterEncodingFailureReason","abstract":"

The underlying reason the .parameterEncodingFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ParameterEncoderFailureReason.html":{"name":"ParameterEncoderFailureReason","abstract":"

The underlying reason the .parameterEncoderFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ResponseValidationFailureReason.html":{"name":"ResponseValidationFailureReason","abstract":"

The underlying reason the .responseValidationFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ResponseSerializationFailureReason.html":{"name":"ResponseSerializationFailureReason","abstract":"

The underlying reason the response serialization error occurred.

","parent_name":"AFError"},"Enums/AFError/ServerTrustFailureReason.html":{"name":"ServerTrustFailureReason","abstract":"

Underlying reason a server trust evaluation error occurred.

","parent_name":"AFError"},"Enums/AFError/URLRequestValidationFailureReason.html":{"name":"URLRequestValidationFailureReason","abstract":"

The underlying reason the .urlRequestValidationFailed

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22createUploadableFailedyACs5Error_p_tcACmF":{"name":"createUploadableFailed(error:)","abstract":"

UploadableConvertible threw an error in createUploadable().

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22createURLRequestFailedyACs5Error_p_tcACmF":{"name":"createURLRequestFailed(error:)","abstract":"

URLRequestConvertible threw an error in asURLRequest().

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24downloadedFileMoveFailedyACs5Error_p_10Foundation3URLVAHtcACmF":{"name":"downloadedFileMoveFailed(error:source:destination:)","abstract":"

SessionDelegate threw an error while attempting to move downloaded file to destination URL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19explicitlyCancelledyA2CmF":{"name":"explicitlyCancelled","abstract":"

Request was explicitly cancelled.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO10invalidURLyAcA14URLConvertible_p_tcACmF":{"name":"invalidURL(url:)","abstract":"

URLConvertible type failed to create a valid URL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23multipartEncodingFailedyA2C09MultipartD13FailureReasonO_tcACmF":{"name":"multipartEncodingFailed(reason:)","abstract":"

Multipart form encoding failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23parameterEncodingFailedyA2C09ParameterD13FailureReasonO_tcACmF":{"name":"parameterEncodingFailed(reason:)","abstract":"

ParameterEncoding threw an error during the encoding process.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22parameterEncoderFailedyA2C09ParameterD13FailureReasonO_tcACmF":{"name":"parameterEncoderFailed(reason:)","abstract":"

ParameterEncoder threw an error while running the encoder.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23requestAdaptationFailedyACs5Error_p_tcACmF":{"name":"requestAdaptationFailed(error:)","abstract":"

RequestAdapter threw an error during adaptation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18requestRetryFailedyACs5Error_p_sAE_ptcACmF":{"name":"requestRetryFailed(retryError:originalError:)","abstract":"

RequestRetrier threw an error during the request retry process.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24responseValidationFailedyA2C08ResponseD13FailureReasonO_tcACmF":{"name":"responseValidationFailed(reason:)","abstract":"

Response validation failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27responseSerializationFailedyA2C08ResponseD13FailureReasonO_tcACmF":{"name":"responseSerializationFailed(reason:)","abstract":"

Response serialization failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27serverTrustEvaluationFailedyA2C06ServerD13FailureReasonO_tcACmF":{"name":"serverTrustEvaluationFailed(reason:)","abstract":"

ServerTrustEvaluating instance threw an error during trust evaluation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO20sessionDeinitializedyA2CmF":{"name":"sessionDeinitialized","abstract":"

Session which issued the Request was deinitialized, most likely because its reference went out of scope.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18sessionInvalidatedyACs5Error_pSg_tcACmF":{"name":"sessionInvalidated(error:)","abstract":"

Session was explicitly invalidated, possibly with the Error produced by the underlying URLSession.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO17sessionTaskFailedyACs5Error_p_tcACmF":{"name":"sessionTaskFailed(error:)","abstract":"

URLSessionTask completed with error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO26urlRequestValidationFailedyA2C010URLRequestE13FailureReasonO_tcACmF":{"name":"urlRequestValidationFailed(reason:)","abstract":"

URLRequest failed validation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27isSessionDeinitializedErrorSbvp":{"name":"isSessionDeinitializedError","abstract":"

Returns whether the instance is .sessionDeinitialized.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isSessionInvalidatedErrorSbvp":{"name":"isSessionInvalidatedError","abstract":"

Returns whether the instance is .sessionInvalidated.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO26isExplicitlyCancelledErrorSbvp":{"name":"isExplicitlyCancelledError","abstract":"

Returns whether the instance is .explicitlyCancelled.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO17isInvalidURLErrorSbvp":{"name":"isInvalidURLError","abstract":"

Returns whether the instance is .invalidURL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isParameterEncodingErrorSbvp":{"name":"isParameterEncodingError","abstract":"

Returns whether the instance is .parameterEncodingFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isParameterEncoderErrorSbvp":{"name":"isParameterEncoderError","abstract":"

Returns whether the instance is .parameterEncoderFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isMultipartEncodingErrorSbvp":{"name":"isMultipartEncodingError","abstract":"

Returns whether the instance is .multipartEncodingFailed. When true, the url and underlyingError","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isRequestAdaptationErrorSbvp":{"name":"isRequestAdaptationError","abstract":"

Returns whether the instance is .requestAdaptationFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isResponseValidationErrorSbvp":{"name":"isResponseValidationError","abstract":"

Returns whether the instance is .responseValidationFailed. When true, the acceptableContentTypes,","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO28isResponseSerializationErrorSbvp":{"name":"isResponseSerializationError","abstract":"

Returns whether the instance is .responseSerializationFailed. When true, the failedStringEncoding and","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO28isServerTrustEvaluationErrorSbvp":{"name":"isServerTrustEvaluationError","abstract":"

Returns whether the instance is .serverTrustEvaluationFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19isRequestRetryErrorSbvp":{"name":"isRequestRetryError","abstract":"

Returns whether the instance is requestRetryFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isCreateUploadableErrorSbvp":{"name":"isCreateUploadableError","abstract":"

Returns whether the instance is createUploadableFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isCreateURLRequestErrorSbvp":{"name":"isCreateURLRequestError","abstract":"

Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isDownloadedFileMoveErrorSbvp":{"name":"isDownloadedFileMoveError","abstract":"

Returns whether the instance is downloadedFileMoveFailed. When true, the destination and underlyingError properties will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18isSessionTaskErrorSbvp":{"name":"isSessionTaskError","abstract":"

Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO14urlConvertibleAA14URLConvertible_pSgvp":{"name":"urlConvertible","abstract":"

The URLConvertible associated with the error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO3url10Foundation3URLVSgvp":{"name":"url","abstract":"

The URL associated with the error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO15underlyingErrors0D0_pSgvp":{"name":"underlyingError","abstract":"

The underlying Error responsible for generating the failure associated with .sessionInvalidated,","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22acceptableContentTypesSaySSGSgvp":{"name":"acceptableContentTypes","abstract":"

The acceptable Content-Types of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19responseContentTypeSSSgvp":{"name":"responseContentType","abstract":"

The response Content-Type of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO12responseCodeSiSgvp":{"name":"responseCode","abstract":"

The response code of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO20failedStringEncodingSS10FoundationE0E0VSgvp":{"name":"failedStringEncoding","abstract":"

The String.Encoding associated with a failed .stringResponse() call.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO9sourceURL10Foundation0D0VSgvp":{"name":"sourceURL","abstract":"

The source URL of a .downloadedFileMoveFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO14destinationURL10Foundation0D0VSgvp":{"name":"destinationURL","abstract":"

The destination URL of a .downloadedFileMoveFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:10Foundation14LocalizedErrorP16errorDescriptionSSSgvp":{"name":"errorDescription","parent_name":"AFError"},"Enums/AFError.html":{"name":"AFError","abstract":"

AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with"},"Enums/AF.html":{"name":"AF","abstract":"

Global namespace containing API for the default Session instance.

"},"Enums/RetryResult.html":{"name":"RetryResult","abstract":"

Outcome of determination whether retry is necessary.

"},"Classes/URLEncodedFormEncoder/Error.html#/s:9Alamofire21URLEncodedFormEncoderC5ErrorO17invalidRootObjectyAESScAEmF":{"name":"invalidRootObject(_:)","abstract":"

An invalid root object was created by the encoder. Only keyed values are valid.

","parent_name":"Error"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13SpaceEncodingO14percentEscapedyA2EmF":{"name":"percentEscaped","abstract":"

Encodes spaces according to normal percent escaping rules (%20).

","parent_name":"SpaceEncoding"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13SpaceEncodingO12plusReplacedyA2EmF":{"name":"plusReplaced","abstract":"

Encodes spaces as +,

","parent_name":"SpaceEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO14useDefaultKeysyA2EmF":{"name":"useDefaultKeys","abstract":"

Use the keys specified by each type. This is the default encoding.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO18convertToSnakeCaseyA2EmF":{"name":"convertToSnakeCase","abstract":"

Convert from camelCaseKeys to snake_case_keys before writing a key.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO18convertToKebabCaseyA2EmF":{"name":"convertToKebabCase","abstract":"

Same as convertToSnakeCase, but using - instead of _.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO11capitalizedyA2EmF":{"name":"capitalized","abstract":"

Capitalize the first letter only.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO10uppercasedyA2EmF":{"name":"uppercased","abstract":"

Uppercase all letters.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO10lowercasedyA2EmF":{"name":"lowercased","abstract":"

Lowercase all letters.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO6customyAES2SccAEmF":{"name":"custom(_:)","abstract":"

A custom encoding using the provided closure.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO010deferredToE0yA2EmF":{"name":"deferredToDate","abstract":"

Defers encoding to the Date type. This is the default encoding.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO16secondsSince1970yA2EmF":{"name":"secondsSince1970","abstract":"

Encodes Dates as seconds since midnight UTC on January 1, 1970.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO21millisecondsSince1970yA2EmF":{"name":"millisecondsSince1970","abstract":"

Encodes Dates as milliseconds since midnight UTC on January 1, 1970.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO7iso8601yA2EmF":{"name":"iso8601","abstract":"

Encodes Dates according to the ISO8601 and RFC3339 standards.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO9formattedyAESo15NSDateFormatterCcAEmF":{"name":"formatted(_:)","abstract":"

Encodes Dates using the given DateFormatter.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO6customyAESS10Foundation0E0VKccAEmF":{"name":"custom(_:)","abstract":"

Encodes Dates using the given closure.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO010deferredToE0yA2EmF":{"name":"deferredToData","abstract":"

Defers encoding to the Data type.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO6base64yA2EmF":{"name":"base64","abstract":"

Encodes Data as a Base64-encoded string. This is the default encoding.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO6customyAESS10Foundation0E0VKccAEmF":{"name":"custom(_:)","abstract":"

Encode the Data as a custom value encoded by the given closure.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/BoolEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12BoolEncodingO7numericyA2EmF":{"name":"numeric","abstract":"

Encodes true as 1, false as 0.

","parent_name":"BoolEncoding"},"Classes/URLEncodedFormEncoder/BoolEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12BoolEncodingO7literalyA2EmF":{"name":"literal","abstract":"

Encodes true as true, false as false. This is the default encoding.

","parent_name":"BoolEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13ArrayEncodingO8bracketsyA2EmF":{"name":"brackets","abstract":"

An empty set of square brackets ([]) are appended to the key for every value. This is the default encoding.

","parent_name":"ArrayEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13ArrayEncodingO10noBracketsyA2EmF":{"name":"noBrackets","abstract":"

No brackets are appended to the key and the key is encoded as is.

","parent_name":"ArrayEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html":{"name":"ArrayEncoding","abstract":"

Encoding to use for Array values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/BoolEncoding.html":{"name":"BoolEncoding","abstract":"

Encoding to use for Bool values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/DataEncoding.html":{"name":"DataEncoding","abstract":"

Encoding to use for Data values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/DateEncoding.html":{"name":"DateEncoding","abstract":"

Encoding to use for Date values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/KeyEncoding.html":{"name":"KeyEncoding","abstract":"

Encoding to use for keys.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html":{"name":"SpaceEncoding","abstract":"

Encoding to use for spaces.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/Error.html":{"name":"Error","abstract":"

URLEncodedFormEncoder error.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC24alphabetizeKeyValuePairsSbvp":{"name":"alphabetizeKeyValuePairs","abstract":"

Whether or not to sort the encoded key value pairs.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC13arrayEncodingAC05ArrayF0Ovp":{"name":"arrayEncoding","abstract":"

The ArrayEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12boolEncodingAC04BoolF0Ovp":{"name":"boolEncoding","abstract":"

The BoolEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12dataEncodingAC04DataF0Ovp":{"name":"dataEncoding","abstract":"

THe DataEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12dateEncodingAC04DateF0Ovp":{"name":"dateEncoding","abstract":"

The DateEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC11keyEncodingAC03KeyF0Ovp":{"name":"keyEncoding","abstract":"

The KeyEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC13spaceEncodingAC05SpaceF0Ovp":{"name":"spaceEncoding","abstract":"

The SpaceEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC17allowedCharacters10Foundation12CharacterSetVvp":{"name":"allowedCharacters","abstract":"

The CharacterSet of allowed (non-escaped) characters.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC24alphabetizeKeyValuePairs13arrayEncoding04boolJ004dataJ004dateJ003keyJ005spaceJ017allowedCharactersACSb_AC05ArrayJ0OAC04BoolJ0OAC04DataJ0OAC04DateJ0OAC0fJ0OAC05SpaceJ0O10Foundation12CharacterSetVtcfc":{"name":"init(alphabetizeKeyValuePairs:arrayEncoding:boolEncoding:dataEncoding:dateEncoding:keyEncoding:spaceEncoding:allowedCharacters:)","abstract":"

Creates an instance from the supplied parameters.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC6encodeySSSE_pKF":{"name":"encode(_:)","abstract":"

Encodes the value as a URL form encoded String.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC6encodey10Foundation4DataVSE_pKF":{"name":"encode(_:)","abstract":"

Encodes the value as Data. This is performed by first creating an encoded String and then returning the","parent_name":"URLEncodedFormEncoder"},"Classes/SessionDelegate.html#/s:9Alamofire15SessionDelegateC11fileManagerACSo06NSFileE0C_tcfc":{"name":"init(fileManager:)","abstract":"

Creates an instance from the given FileManager.

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:didBecomeInvalidWithError:":{"name":"urlSession(_:didBecomeInvalidWithError:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didReceiveChallenge:completionHandler:":{"name":"urlSession(_:task:didReceive:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:needNewBodyStream:":{"name":"urlSession(_:task:needNewBodyStream:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didFinishCollectingMetrics:":{"name":"urlSession(_:task:didFinishCollecting:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didCompleteWithError:":{"name":"urlSession(_:task:didCompleteWithError:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:taskIsWaitingForConnectivity:":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:dataTask:didReceiveData:":{"name":"urlSession(_:dataTask:didReceive:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:dataTask:willCacheResponse:completionHandler:":{"name":"urlSession(_:dataTask:willCacheResponse:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didFinishDownloadingToURL:":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/Session.html#/s:9Alamofire7SessionC7defaultACvpZ":{"name":"default","abstract":"

Shared singleton instance used by all AF.request APIs. Cannot be modified.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7sessionSo12NSURLSessionCvp":{"name":"session","abstract":"

Underlying URLSession used to create URLSessionTasks for this instance, and for which this instance’s","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8delegateAA0B8DelegateCvp":{"name":"delegate","abstract":"

Instance’s SessionDelegate, which handles the URLSessionDelegate methods and Request interaction.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC9rootQueueSo17OS_dispatch_queueCvp":{"name":"rootQueue","abstract":"

Root DispatchQueue for all internal callbacks and state update. MUST be a serial queue.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC24startRequestsImmediatelySbvp":{"name":"startRequestsImmediately","abstract":"

Value determining whether this instance automatically calls resume() on all created Requests.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC12requestQueueSo17OS_dispatch_queueCvp":{"name":"requestQueue","abstract":"

DispatchQueue on which URLRequests are created asynchronously. By default this queue uses rootQueue as its","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC18serializationQueueSo17OS_dispatch_queueCvp":{"name":"serializationQueue","abstract":"

DispatchQueue passed to all Requests on which they perform their response serialization. By default this","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC11interceptorAA18RequestInterceptor_pSgvp":{"name":"interceptor","abstract":"

RequestInterceptor used for all Request created by the instance. RequestInterceptors can also be set on a","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC18serverTrustManagerAA06ServerdE0CSgvp":{"name":"serverTrustManager","abstract":"

ServerTrustManager instance used to evaluate all trust challenges and provide certificate and key pinning.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC15redirectHandlerAA08RedirectD0_pSgvp":{"name":"redirectHandler","abstract":"

RedirectHandler instance used to provide customization for request redirection.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC21cachedResponseHandlerAA06CacheddE0_pSgvp":{"name":"cachedResponseHandler","abstract":"

CachedResponseHandler instance used to provide customization of cached response handling.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC12eventMonitorAA014CompositeEventD0Cvp":{"name":"eventMonitor","abstract":"

CompositeEventMonitor used to compose Alamofire’s defaultEventMonitors and any passed EventMonitors.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC20defaultEventMonitorsSayAA0D7Monitor_pGvp":{"name":"defaultEventMonitors","abstract":"

EventMonitors included in all instances. [AlamofireNotifications()] by default.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7session8delegate9rootQueue24startRequestsImmediately07requestF0013serializationF011interceptor18serverTrustManager15redirectHandler014cachedResponseQ013eventMonitorsACSo12NSURLSessionC_AA0B8DelegateCSo17OS_dispatch_queueCSbATSgAuA18RequestInterceptor_pSgAA06ServernO0CSgAA08RedirectQ0_pSgAA06CachedsQ0_pSgSayAA12EventMonitor_pGtcfc":{"name":"init(session:delegate:rootQueue:startRequestsImmediately:requestQueue:serializationQueue:interceptor:serverTrustManager:redirectHandler:cachedResponseHandler:eventMonitors:)","abstract":"

Creates a Session from a URLSession and other parameters.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC13configuration8delegate9rootQueue24startRequestsImmediately07requestF0013serializationF011interceptor18serverTrustManager15redirectHandler014cachedResponseQ013eventMonitorsACSo25NSURLSessionConfigurationC_AA0B8DelegateCSo17OS_dispatch_queueCSbATSgAuA18RequestInterceptor_pSgAA06ServernO0CSgAA08RedirectQ0_pSgAA06CachedsQ0_pSgSayAA12EventMonitor_pGtcfc":{"name":"init(configuration:delegate:rootQueue:startRequestsImmediately:requestQueue:serializationQueue:interceptor:serverTrustManager:redirectHandler:cachedResponseHandler:eventMonitors:)","abstract":"

Creates a Session from a URLSessionConfiguration.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC17cancelAllRequests17completingOnQueue10completionySo17OS_dispatch_queueC_yycSgtF":{"name":"cancelAllRequests(completingOnQueue:completion:)","abstract":"

Cancel all active Requests, optionally calling a completion handler when complete.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_6method10parameters8encoding7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtF":{"name":"request(_:method:parameters:encoding:headers:interceptor:)","abstract":"

Creates a DataRequest from a URLRequest created using the passed components and a RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_6method10parameters7encoder7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtSERzlF":{"name":"request(_:method:parameters:encoder:headers:interceptor:)","abstract":"

Creates a DataRequest from a URLRequest created using the passed components, Encodable parameters, and a","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_11interceptorAA11DataRequestCAA21URLRequestConvertible_p_AA0F11Interceptor_pSgtF":{"name":"request(_:interceptor:)","abstract":"

Creates a DataRequest from a URLRequestConvertible value and a RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_6method10parameters8encoding7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAZ_So17NSHTTPURLResponseCtcSgtF":{"name":"download(_:method:parameters:encoding:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using a URLRequest created using the passed components, RequestInterceptor, and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_6method10parameters7encoder7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAY_So17NSHTTPURLResponseCtcSgtSERzlF":{"name":"download(_:method:parameters:encoder:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest from a URLRequest created using the passed components, Encodable parameters, and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_11interceptor2toAA15DownloadRequestCAA21URLRequestConvertible_p_AA0G11Interceptor_pSg10Foundation3URLV011destinationL0_AH7OptionsV7optionstAN_So17NSHTTPURLResponseCtcSgtF":{"name":"download(_:interceptor:to:)","abstract":"

Creates a DownloadRequest from a URLRequestConvertible value, a RequestInterceptor, and a Destination.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download12resumingWith11interceptor2toAA15DownloadRequestC10Foundation4DataV_AA0I11Interceptor_pSgAJ3URLV011destinationM0_AI7OptionsV7optionstAP_So17NSHTTPURLResponseCtcSgtF":{"name":"download(resumingWith:interceptor:to:)","abstract":"

Creates a DownloadRequest from the resumeData produced from a previously cancelled DownloadRequest, as","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data, URLRequest components, and RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data using the URLRequestConvertible value and RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL, using a URLRequest from the provided","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL using the URLRequestConvertible value and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the InputStream provided using a URLRequest from the provided components and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the provided InputStream using the URLRequestConvertible value and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtF":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the multipart form data built using a closure and sent using the provided","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtF":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtF":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtF":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP20sessionConfigurationSo012NSURLSessionE0Cvp":{"name":"sessionConfiguration","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP16startImmediatelySbvp":{"name":"startImmediately","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP7cleanup5afteryAA0B0C_tF":{"name":"cleanup(after:)","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP11retryResult3for5dueTo10completionyAA0B0C_AA7AFErrorOyAA05RetryE0OctF":{"name":"retryResult(for:dueTo:completion:)","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP05retryB0_9withDelayyAA0B0C_SdSgtF":{"name":"retryRequest(_:withDelay:)","parent_name":"Session"},"Classes/DisabledEvaluator.html#/s:9Alamofire17DisabledEvaluatorCACycfc":{"name":"init()","abstract":"

Creates an instance.

","parent_name":"DisabledEvaluator"},"Classes/DisabledEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"DisabledEvaluator"},"Classes/CompositeTrustEvaluator.html#/s:9Alamofire23CompositeTrustEvaluatorC10evaluatorsACSayAA06ServerC10Evaluating_pG_tcfc":{"name":"init(evaluators:)","abstract":"

Creates a CompositeTrustEvaluator.

","parent_name":"CompositeTrustEvaluator"},"Classes/CompositeTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"CompositeTrustEvaluator"},"Classes/PublicKeysTrustEvaluator.html#/s:9Alamofire24PublicKeysTrustEvaluatorC4keys24performDefaultValidation12validateHostACSaySo9SecKeyRefaG_S2btcfc":{"name":"init(keys:performDefaultValidation:validateHost:)","abstract":"

Creates a PublicKeysTrustEvaluator.

","parent_name":"PublicKeysTrustEvaluator"},"Classes/PublicKeysTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"PublicKeysTrustEvaluator"},"Classes/PinnedCertificatesTrustEvaluator.html#/s:9Alamofire32PinnedCertificatesTrustEvaluatorC12certificates016acceptSelfSignedC024performDefaultValidation12validateHostACSaySo17SecCertificateRefaG_S3btcfc":{"name":"init(certificates:acceptSelfSignedCertificates:performDefaultValidation:validateHost:)","abstract":"

Creates a PinnedCertificatesTrustEvaluator.

","parent_name":"PinnedCertificatesTrustEvaluator"},"Classes/PinnedCertificatesTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"PinnedCertificatesTrustEvaluator"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV3crlAEvpZ":{"name":"crl","abstract":"

Perform revocation checking using the CRL (Certification Revocation List) method.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV21networkAccessDisabledAEvpZ":{"name":"networkAccessDisabled","abstract":"

Consult only locally cached replies; do not use network access.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV4ocspAEvpZ":{"name":"ocsp","abstract":"

Perform revocation checking using OCSP (Online Certificate Status Protocol).

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV9preferCRLAEvpZ":{"name":"preferCRL","abstract":"

Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV23requirePositiveResponseAEvpZ":{"name":"requirePositiveResponse","abstract":"

Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV3anyAEvpZ":{"name":"any","abstract":"

Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV8rawValueSuvp":{"name":"rawValue","abstract":"

The raw value of the option.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV8rawValueAESu_tcfc":{"name":"init(rawValue:)","abstract":"

Creates an Options value with the given CFOptionFlags.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html":{"name":"Options","abstract":"

Represents the options to be use when evaluating the status of a certificate.","parent_name":"RevocationTrustEvaluator"},"Classes/RevocationTrustEvaluator.html#/s:9Alamofire24RevocationTrustEvaluatorC24performDefaultValidation12validateHost7optionsACSb_SbAC7OptionsVtcfc":{"name":"init(performDefaultValidation:validateHost:options:)","abstract":"

Creates a RevocationTrustEvaluator.

","parent_name":"RevocationTrustEvaluator"},"Classes/RevocationTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"RevocationTrustEvaluator"},"Classes/DefaultTrustEvaluator.html#/s:9Alamofire21DefaultTrustEvaluatorC12validateHostACSb_tcfc":{"name":"init(validateHost:)","abstract":"

Creates a DefaultTrustEvaluator.

","parent_name":"DefaultTrustEvaluator"},"Classes/DefaultTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"DefaultTrustEvaluator"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC23allHostsMustBeEvaluatedSbvp":{"name":"allHostsMustBeEvaluated","abstract":"

Determines whether all hosts for this ServerTrustManager must be evaluated. true by default.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC10evaluatorsSDySSAA0bC10Evaluating_pGvp":{"name":"evaluators","abstract":"

The dictionary of policies mapped to a particular host.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC23allHostsMustBeEvaluated10evaluatorsACSb_SDySSAA0bC10Evaluating_pGtcfc":{"name":"init(allHostsMustBeEvaluated:evaluators:)","abstract":"

Initializes the ServerTrustManager instance with the given evaluators.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC06serverC9Evaluator7forHostAA0bC10Evaluating_pSgSS_tKF":{"name":"serverTrustEvaluator(forHost:)","abstract":"

Returns the ServerTrustEvaluating value for the given host, if one is set.

","parent_name":"ServerTrustManager"},"Classes/ConnectionLostRetryPolicy.html#/s:9Alamofire25ConnectionLostRetryPolicyC10retryLimit22exponentialBackoffBase0hI5Scale20retryableHTTPMethodsACSu_SuSdShyAA10HTTPMethodVGtcfc":{"name":"init(retryLimit:exponentialBackoffBase:exponentialBackoffScale:retryableHTTPMethods:)","abstract":"

Creates a ConnectionLostRetryPolicy instance from the specified parameters.

","parent_name":"ConnectionLostRetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC07defaultB5LimitSuvpZ":{"name":"defaultRetryLimit","abstract":"

The default retry limit for retry policies.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC29defaultExponentialBackoffBaseSuvpZ":{"name":"defaultExponentialBackoffBase","abstract":"

The default exponential backoff base for retry policies (must be a minimum of 2).

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC30defaultExponentialBackoffScaleSdvpZ":{"name":"defaultExponentialBackoffScale","abstract":"

The default exponential backoff scale for retry policies.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC27defaultRetryableHTTPMethodsShyAA10HTTPMethodVGvpZ":{"name":"defaultRetryableHTTPMethods","abstract":"

The default HTTP methods to retry.","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC31defaultRetryableHTTPStatusCodesShySiGvpZ":{"name":"defaultRetryableHTTPStatusCodes","abstract":"

The default HTTP status codes to retry.","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC29defaultRetryableURLErrorCodesShy10Foundation0F0V4CodeVGvpZ":{"name":"defaultRetryableURLErrorCodes","abstract":"

The default URL error codes to retry.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC10retryLimitSuvp":{"name":"retryLimit","abstract":"

The total number of times the request is allowed to be retried.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC22exponentialBackoffBaseSuvp":{"name":"exponentialBackoffBase","abstract":"

The base of the exponential backoff policy (should always be greater than or equal to 2).

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC23exponentialBackoffScaleSdvp":{"name":"exponentialBackoffScale","abstract":"

The scale of the exponential backoff.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC20retryableHTTPMethodsShyAA10HTTPMethodVGvp":{"name":"retryableHTTPMethods","abstract":"

The HTTP methods that are allowed to be retried.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC24retryableHTTPStatusCodesShySiGvp":{"name":"retryableHTTPStatusCodes","abstract":"

The HTTP status codes that are automatically retried by the policy.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC22retryableURLErrorCodesShy10Foundation0E0V4CodeVGvp":{"name":"retryableURLErrorCodes","abstract":"

The URL error codes that are automatically retried by the policy.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC10retryLimit22exponentialBackoffBase0fG5Scale20retryableHTTPMethods0J15HTTPStatusCodes0j8URLErrorM0ACSu_SuSdShyAA10HTTPMethodVGShySiGShy10Foundation0N0V4CodeVGtcfc":{"name":"init(retryLimit:exponentialBackoffBase:exponentialBackoffScale:retryableHTTPMethods:retryableHTTPStatusCodes:retryableURLErrorCodes:)","abstract":"

Creates an ExponentialBackoffRetryPolicy from the specified parameters.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"RetryPolicy"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire27DecodableResponseSerializerC7decoderAA11DataDecoder_pvp":{"name":"decoder","abstract":"

The DataDecoder instance used to decode responses.

","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire27DecodableResponseSerializerC16dataPreprocessor7decoder05emptyC5Codes0H14RequestMethodsACyxGAA04DataF0_p_AA0L7Decoder_pShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:decoder:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance using the values provided.

","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"DecodableResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire22JSONResponseSerializerC7optionsSo20NSJSONReadingOptionsVvp":{"name":"options","abstract":"

JSONSerialization.ReadingOptions used when serializing a response.

","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire22JSONResponseSerializerC16dataPreprocessor18emptyResponseCodes0F14RequestMethods7optionsAcA04DataE0_p_ShySiGShyAA10HTTPMethodVGSo20NSJSONReadingOptionsVtcfc":{"name":"init(dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:)","abstract":"

Creates an instance with the provided values.

","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"JSONResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire24StringResponseSerializerC8encodingSS10FoundationE8EncodingVSgvp":{"name":"encoding","abstract":"

Optional string encoding used to validate the response.

","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire24StringResponseSerializerC16dataPreprocessor8encoding05emptyC5Codes0H14RequestMethodsAcA04DataF0_p_SS10FoundationE8EncodingVSgShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:encoding:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance with the provided values.

","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"StringResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire22DataResponseSerializerC16dataPreprocessor05emptyC5Codes0G14RequestMethodsAcA0bF0_p_ShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance using the provided values.

","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"DataResponseSerializer"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8adaptersSayAA14RequestAdapter_pGvp":{"name":"adapters","abstract":"

All RequestAdapters associated with the instance. These adapters will be run until one fails.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8retriersSayAA14RequestRetrier_pGvp":{"name":"retriers","abstract":"

All RequestRetriers associated with the instance. These retriers will be run one at a time until one triggers retry.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC12adaptHandler05retryD0ACy10Foundation10URLRequestV_AA7SessionCys6ResultOyAHs5Error_pGctc_yAA7RequestC_AJsAM_pyAA05RetryI0Octctcfc":{"name":"init(adaptHandler:retryHandler:)","abstract":"

Creates an instance from AdaptHandler and RetryHandler closures.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC7adapter7retrierAcA14RequestAdapter_p_AA0E7Retrier_ptcfc":{"name":"init(adapter:retrier:)","abstract":"

Creates an instance from RequestAdapter and RequestRetrier values.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8adapters8retriersACSayAA14RequestAdapter_pG_SayAA0E7Retrier_pGtcfc":{"name":"init(adapters:retriers:)","abstract":"

Creates an instance from the arrays of RequestAdapter and RequestRetrier values.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"Interceptor"},"Classes/Retrier.html#/s:9Alamofire7RetrierCyACyAA7RequestC_AA7SessionCs5Error_pyAA11RetryResultOctccfc":{"name":"init(_:)","abstract":"

Creates an instance using the provided closure.

","parent_name":"Retrier"},"Classes/Retrier.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"Retrier"},"Classes/Adapter.html#/s:9Alamofire7AdapterCyACy10Foundation10URLRequestV_AA7SessionCys6ResultOyAFs5Error_pGctccfc":{"name":"init(_:)","abstract":"

Creates an instance using the provided closure.

","parent_name":"Adapter"},"Classes/Adapter.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"Adapter"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO4datayAE10Foundation4DataVcAEmF":{"name":"data(_:)","abstract":"

Upload from the provided Data value.

","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO4fileyAE10Foundation3URLV_SbtcAEmF":{"name":"file(_:shouldRemove:)","abstract":"

Upload from the provided file URL, as well as a Bool determining whether the source file should be","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO6streamyAESo13NSInputStreamCcAEmF":{"name":"stream(_:)","abstract":"

Upload from the provided InputStream.

","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire21UploadableConvertibleP06createB0AA13UploadRequestC0B0OyKF":{"name":"createUploadable()","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html":{"name":"Uploadable","abstract":"

Type describing the origin of the upload, whether Data, file, or stream.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC6uploadAA21UploadableConvertible_pvp":{"name":"upload","abstract":"

The UploadableConvertible value used to produce the Uploadable value for this instance.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC11fileManagerSo06NSFileE0Cvp":{"name":"fileManager","abstract":"

FileManager used to perform cleanup tasks, including the removal of multipart form encoded payloads written","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC10uploadableAC10UploadableOSgvp":{"name":"uploadable","abstract":"

Uploadable value used by the instance.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC7cleanupyyF":{"name":"cleanup()","parent_name":"UploadRequest"},"Classes/DownloadRequest/Downloadable.html#/s:9Alamofire15DownloadRequestC12DownloadableO7requestyAeA21URLRequestConvertible_pcAEmF":{"name":"request(_:)","abstract":"

Download should be started from the URLRequest produced by the associated URLRequestConvertible value.

","parent_name":"Downloadable"},"Classes/DownloadRequest/Downloadable.html#/s:9Alamofire15DownloadRequestC12DownloadableO10resumeDatayAE10Foundation0F0VcAEmF":{"name":"resumeData(_:)","abstract":"

Download should be started from the associated resume Data value.

","parent_name":"Downloadable"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV29createIntermediateDirectoriesAEvpZ":{"name":"createIntermediateDirectories","abstract":"

Specifies that intermediate directories for the destination URL should be created.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV18removePreviousFileAEvpZ":{"name":"removePreviousFile","abstract":"

Specifies that any previous file at the destination URL should be removed.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV8rawValueSivp":{"name":"rawValue","abstract":"

Returns the raw bitmask value of the option and satisfies the RawRepresentable protocol.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:s9OptionSetP8rawValuex03RawD0Qz_tcfc":{"name":"init(rawValue:)","parent_name":"Options"},"Classes/DownloadRequest/Options.html":{"name":"Options","abstract":"

A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC11Destinationa":{"name":"Destination","abstract":"

A closure executed once a download request has successfully completed in order to determine where to move the","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC09suggestedB11Destination3for2in7options10Foundation3URLV011destinationJ0_AC7OptionsVAGtAJ_So17NSHTTPURLResponseCtcSo21NSSearchPathDirectoryV_So0nO10DomainMaskVAMtFZ":{"name":"suggestedDownloadDestination(for:in:options:)","abstract":"

Creates a download file destination closure which uses the default file manager to move the temporary file to a","parent_name":"DownloadRequest"},"Classes/DownloadRequest/Downloadable.html":{"name":"Downloadable","abstract":"

Type describing the source used to create the underlying URLSessionDownloadTask.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC10resumeData10Foundation0E0VSgvp":{"name":"resumeData","abstract":"

If the download is resumable and eventually cancelled, this value may be used to resume the download using the","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC7fileURL10Foundation0E0VSgvp":{"name":"fileURL","abstract":"

If the download is successful, the URL where the file was downloaded.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12downloadableAC12DownloadableOvp":{"name":"downloadable","abstract":"

Downloadable value used for this instance.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC4task13forResumeData5usingSo16NSURLSessionTaskC10Foundation0G0V_So0I0CtF":{"name":"task(forResumeData:using:)","abstract":"

Creates a URLSessionTask from the provided resume data.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancelACXDyF":{"name":"cancel()","abstract":"

Cancels the instance. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancel19producingResumeDataACXDSb_tF":{"name":"cancel(producingResumeData:)","abstract":"

Cancels the instance, optionally producing resume data. Once cancelled, a DownloadRequest can no longer be","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancel21byProducingResumeDataACXDy10Foundation0H0VSgc_tF":{"name":"cancel(byProducingResumeData:)","abstract":"

Cancels the instance while producing resume data. Once cancelled, a DownloadRequest can no longer be resumed","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validateyACXDs6ResultOyyts5Error_pG10Foundation10URLRequestVSg_So17NSHTTPURLResponseCAI3URLVSgtcF":{"name":"validate(_:)","abstract":"

Validates the request, using the specified closure.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8response5queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation3URLVSgAA7AFErrorOGctF":{"name":"response(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0C_xyAA0B8ResponseVy16SerializedObjectQzAA7AFErrorOGctAA0bkF8ProtocolRzlF":{"name":"response(queue:responseSerializer:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12responseData5queue17completionHandlerACXDSo012OS_dispatch_F0C_yAA0B8ResponseVy10Foundation0E0VAA7AFErrorOGctF":{"name":"responseData(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC14responseString5queue8encoding17completionHandlerACXDSo012OS_dispatch_F0C_SS10FoundationE8EncodingVSgyAA0B8ResponseVySSAA7AFErrorOGctF":{"name":"responseString(queue:encoding:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12responseJSON5queue7options17completionHandlerACXDSo012OS_dispatch_F0C_So20NSJSONReadingOptionsVyAA0B8ResponseVyypAA7AFErrorOGctF":{"name":"responseJSON(queue:options:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC10Validationa":{"name":"Validation","abstract":"

A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validate10statusCodeACXDx_tSTRzSi7ElementRtzlF":{"name":"validate(statusCode:)","abstract":"

Validates that the response has a status code in the specified sequence.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validate11contentTypeACXDxyXA_tSTRzSS7ElementRtzlF":{"name":"validate(contentType:)","abstract":"

Validates that the response has a content type in the specified sequence.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validateACXDyF":{"name":"validate()","abstract":"

Validates that the response has a status code in the default acceptable range of 200…299, and that the content","parent_name":"DownloadRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC11convertibleAA21URLRequestConvertible_pvp":{"name":"convertible","abstract":"

URLRequestConvertible value used to create URLRequests for this instance.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC4data10Foundation0B0VSgvp":{"name":"data","abstract":"

Data read from the server so far.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validateyACXDs6ResultOyyts5Error_pG10Foundation10URLRequestVSg_So17NSHTTPURLResponseCAI0B0VSgtcF":{"name":"validate(_:)","abstract":"

Validates the request, using the specified closure.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8response5queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation0B0VSgAA7AFErrorOGctF":{"name":"response(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0C_xyAA0B8ResponseVy16SerializedObjectQzAA7AFErrorOGctAA0bkF8ProtocolRzlF":{"name":"response(queue:responseSerializer:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC08responseB05queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation0B0VAA7AFErrorOGctF":{"name":"responseData(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC14responseString5queue8encoding17completionHandlerACXDSo012OS_dispatch_F0C_SS10FoundationE8EncodingVSgyAA0B8ResponseVySSAA7AFErrorOGctF":{"name":"responseString(queue:encoding:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC12responseJSON5queue7options17completionHandlerACXDSo012OS_dispatch_F0C_So20NSJSONReadingOptionsVyAA0B8ResponseVyypAA7AFErrorOGctF":{"name":"responseJSON(queue:options:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC17responseDecodable2of5queue7decoder17completionHandlerACXDxm_So012OS_dispatch_G0CAA0B7Decoder_pyAA0B8ResponseVyxAA7AFErrorOGctSeRzlF":{"name":"responseDecodable(of:queue:decoder:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC10Validationa":{"name":"Validation","abstract":"

A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validate10statusCodeACXDx_tSTRzSi7ElementRtzlF":{"name":"validate(statusCode:)","abstract":"

Validates that the response has a status code in the specified sequence.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validate11contentTypeACXDxyXA_tSTRzSS7ElementRtzlF":{"name":"validate(contentType:)","abstract":"

Validates that the response has a content type in the specified sequence.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validateACXDyF":{"name":"validate()","abstract":"

Validates that the response has a status code in the default acceptable range of 200…299, and that the content","parent_name":"DataRequest"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO15methodDependentyA2EmF":{"name":"methodDependent","abstract":"

Applies the encoded query string to any existing query string for .get, .head, and .delete request.","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO11queryStringyA2EmF":{"name":"queryString","abstract":"

Applies the encoded query string to any existing query string from the URLRequest.

","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO8httpBodyyA2EmF":{"name":"httpBody","abstract":"

Applies the encoded query string to the httpBody of the URLRequest.

","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html":{"name":"Destination","abstract":"

Defines where the URL-encoded string should be set for each URLRequest.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7defaultACvpZ":{"name":"default","abstract":"

Returns an encoder with default parameters.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7encoderAA0bcE0Cvp":{"name":"encoder","abstract":"

The URLEncodedFormEncoder to use.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11destinationAC11DestinationOvp":{"name":"destination","abstract":"

The Destination for the URL-encoded string.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7encoder11destinationAcA0bcE0C_AC11DestinationOtcfc":{"name":"init(encoder:destination:)","abstract":"

Creates an instance with the provided URLEncodedFormEncoder instance and Destination value.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","parent_name":"URLEncodedFormParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7defaultACvpZ":{"name":"default","abstract":"

Returns an encoder with default parameters.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC13prettyPrintedACvpZ":{"name":"prettyPrinted","abstract":"

Returns an encoder with JSONEncoder.outputFormatting set to .prettyPrinted.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC10sortedKeysACvpZ":{"name":"sortedKeys","abstract":"

Returns an encoder with JSONEncoder.outputFormatting set to .sortedKeys.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7encoder10Foundation11JSONEncoderCvp":{"name":"encoder","abstract":"

JSONEncoder used to encode parameters.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7encoderAC10Foundation11JSONEncoderC_tcfc":{"name":"init(encoder:)","abstract":"

Creates an instance with the provided JSONEncoder.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","parent_name":"JSONParameterEncoder"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"AlamofireNotifications"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO11initializedyA2EmF":{"name":"initialized","abstract":"

Initial state of the Request.

","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO7resumedyA2EmF":{"name":"resumed","abstract":"

State set when resume() is called. Any tasks created for the Request will have resume() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO9suspendedyA2EmF":{"name":"suspended","abstract":"

State set when suspend() is called. Any tasks created for the Request will have suspend() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO9cancelledyA2EmF":{"name":"cancelled","abstract":"

State set when cancel() is called. Any tasks created for the Request will have cancel() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO8finishedyA2EmF":{"name":"finished","abstract":"

State set when all response serialization completion closures have been cleared on the Request and","parent_name":"State"},"Classes/Request/State.html":{"name":"State","abstract":"

State of the Request, with managed transitions between states set when calling resume(), suspend(), or","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC2id10Foundation4UUIDVvp":{"name":"id","abstract":"

UUID providing a unique identifier for the Request, used in the Hashable and Equatable conformances.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15underlyingQueueSo17OS_dispatch_queueCvp":{"name":"underlyingQueue","abstract":"

The serial queue for all internal async actions.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC18serializationQueueSo17OS_dispatch_queueCvp":{"name":"serializationQueue","abstract":"

The queue used for all serialization actions. By default it’s a serial queue that targets underlyingQueue.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12eventMonitorAA05EventD0_pSgvp":{"name":"eventMonitor","abstract":"

EventMonitor used for event callbacks.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11interceptorAA0B11Interceptor_pSgvp":{"name":"interceptor","abstract":"

The Request‘s interceptor.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8delegateAA0B8Delegate_pSgvp":{"name":"delegate","abstract":"

The Request‘s delegate.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5stateAC5StateOvp":{"name":"state","abstract":"

State of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC13isInitializedSbvp":{"name":"isInitialized","abstract":"

Returns whether state is .initialized.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC9isResumedSbvp":{"name":"isResumed","abstract":"

Returns whether state is.resumed`.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11isSuspendedSbvp":{"name":"isSuspended","abstract":"

Returns whether state is .suspended.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11isCancelledSbvp":{"name":"isCancelled","abstract":"

Returns whether state is .cancelled.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10isFinishedSbvp":{"name":"isFinished","abstract":"

Returns whether state is .finished.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15ProgressHandlera":{"name":"ProgressHandler","abstract":"

Closure type executed when monitoring the upload or download progress of a request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC14uploadProgressSo10NSProgressCvp":{"name":"uploadProgress","abstract":"

Progress of the upload of the body of the executed URLRequest. Reset to 0 if the Request is retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16downloadProgressSo10NSProgressCvp":{"name":"downloadProgress","abstract":"

Progress of the download of any response data. Reset to 0 if the Request is retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15redirectHandlerAA08RedirectD0_pSgvp":{"name":"redirectHandler","abstract":"

RedirectHandler set on the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21cachedResponseHandlerAA06CacheddE0_pSgvp":{"name":"cachedResponseHandler","abstract":"

CachedResponseHandler set on the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10credentialSo15NSURLCredentialCSgvp":{"name":"credential","abstract":"

URLCredential used for authentication challenges. Created by calling one of the authenticate methods.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8requestsSay10Foundation10URLRequestVGvp":{"name":"requests","abstract":"

All URLRequests created on behalf of the Request, including original and adapted requests.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC05firstB010Foundation10URLRequestVSgvp":{"name":"firstRequest","abstract":"

First URLRequest created on behalf of the Request. May not be the first one actually executed.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC04lastB010Foundation10URLRequestVSgvp":{"name":"lastRequest","abstract":"

Last URLRequest created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

Current URLRequest created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC17performedRequestsSay10Foundation10URLRequestVGvp":{"name":"performedRequests","abstract":"

URLRequests from all of the URLSessionTasks executed on behalf of the Request. May be different from","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

HTTPURLResponse received from the server, if any. If the Request was retried, this is the response of the","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5tasksSaySo16NSURLSessionTaskCGvp":{"name":"tasks","abstract":"

All URLSessionTasks created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC9firstTaskSo012NSURLSessionD0CSgvp":{"name":"firstTask","abstract":"

First URLSessionTask created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8lastTaskSo012NSURLSessionD0CSgvp":{"name":"lastTask","abstract":"

Last URLSessionTask crated on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC4taskSo16NSURLSessionTaskCSgvp":{"name":"task","abstract":"

Current URLSessionTask created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10allMetricsSaySo016NSURLSessionTaskD0CGvp":{"name":"allMetrics","abstract":"

All URLSessionTaskMetrics gathered on behalf of the Request. Should correspond to the tasks created.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12firstMetricsSo016NSURLSessionTaskD0CSgvp":{"name":"firstMetrics","abstract":"

First URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11lastMetricsSo016NSURLSessionTaskD0CSgvp":{"name":"lastMetrics","abstract":"

Last URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

Current URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10retryCountSivp":{"name":"retryCount","abstract":"

Number of times the Request has been retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5errorAA7AFErrorOSgvp":{"name":"error","abstract":"

Error returned from Alamofire internally, from the network request directly, or any validators executed.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC6cancelACXDyF":{"name":"cancel()","abstract":"

Cancels the instance. Once cancelled, a Request can no longer be resumed or suspended.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7suspendACXDyF":{"name":"suspend()","abstract":"

Suspends the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC6resumeACXDyF":{"name":"resume()","abstract":"

Resumes the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12authenticate8username8password11persistenceACXDSS_SSSo26NSURLCredentialPersistenceVtF":{"name":"authenticate(username:password:persistence:)","abstract":"

Associates a credential using the provided values with the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12authenticate4withACXDSo15NSURLCredentialC_tF":{"name":"authenticate(with:)","abstract":"

Associates the provided credential with the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16downloadProgress5queue7closureACXDSo012OS_dispatch_E0C_ySo10NSProgressCctF":{"name":"downloadProgress(queue:closure:)","abstract":"

Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC14uploadProgress5queue7closureACXDSo012OS_dispatch_E0C_ySo10NSProgressCctF":{"name":"uploadProgress(queue:closure:)","abstract":"

Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8redirect5usingACXDAA15RedirectHandler_p_tF":{"name":"redirect(using:)","abstract":"

Sets the redirect handler for the instance which will be used if a redirect response is encountered.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC13cacheResponse5usingACXDAA06CachedD7Handler_p_tF":{"name":"cacheResponse(using:)","abstract":"

Sets the cached response handler for the Request which will be used when attempting to cache a response.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15cURLDescription7callingACXDySSc_tF":{"name":"cURLDescription(calling:)","abstract":"

Sets a handler to be called when the cURL description of the request is available.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didResumeNotificationSo18NSNotificationNameavpZ":{"name":"didResumeNotification","abstract":"

Posted when a Request is resumed. The Notification contains the resumed Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC22didSuspendNotificationSo18NSNotificationNameavpZ":{"name":"didSuspendNotification","abstract":"

Posted when a Request is suspended. The Notification contains the suspended Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didCancelNotificationSo18NSNotificationNameavpZ":{"name":"didCancelNotification","abstract":"

Posted when a Request is cancelled. The Notification contains the cancelled Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didFinishNotificationSo18NSNotificationNameavpZ":{"name":"didFinishNotification","abstract":"

Posted when a Request is finished. The Notification contains the completed Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC25didResumeTaskNotificationSo18NSNotificationNameavpZ":{"name":"didResumeTaskNotification","abstract":"

Posted when a URLSessionTask is resumed. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC26didSuspendTaskNotificationSo18NSNotificationNameavpZ":{"name":"didSuspendTaskNotification","abstract":"

Posted when a URLSessionTask is suspended. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC25didCancelTaskNotificationSo18NSNotificationNameavpZ":{"name":"didCancelTaskNotification","abstract":"

Posted when a URLSessionTask is cancelled. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC27didCompleteTaskNotificationSo18NSNotificationNameavpZ":{"name":"didCompleteTaskNotification","abstract":"

Posted when a URLSessionTask is completed. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:SQ2eeoiySbx_xtFZ":{"name":"==(_:_:)","parent_name":"Request"},"Classes/Request.html#/s:SH4hash4intoys6HasherVz_tF":{"name":"hash(into:)","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11descriptionSSvp":{"name":"description","abstract":"

A textual representation of this instance, including the HTTPMethod and URL if the URLRequest has been","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15cURLDescriptionSSyF":{"name":"cURLDescription()","abstract":"

cURL representation of the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16ValidationResulta":{"name":"ValidationResult","abstract":"

Used to represent whether a validation succeeded or failed.

","parent_name":"Request"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO14ConnectionTypeO14ethernetOrWiFiyA2GmF":{"name":"ethernetOrWiFi","abstract":"

The connection type is either over Ethernet or WiFi.

","parent_name":"ConnectionType"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO14ConnectionTypeO8cellularyA2GmF":{"name":"cellular","abstract":"

The connection type is a cellular connection.

","parent_name":"ConnectionType"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO7unknownyA2EmF":{"name":"unknown","abstract":"

It is unknown whether the network is reachable.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO12notReachableyA2EmF":{"name":"notReachable","abstract":"

The network is not reachable.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO9reachableyA2E14ConnectionTypeOcAEmF":{"name":"reachable(_:)","abstract":"

The network is reachable on the associated ConnectionType.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html":{"name":"ConnectionType","abstract":"

Defines the various connection types detected by reachability flags.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html":{"name":"NetworkReachabilityStatus","abstract":"

Defines the various states of network reachability.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC8Listenera":{"name":"Listener","abstract":"

A closure executed when the network reachability status changes. The closure takes a single argument: the","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC7defaultACSgvpZ":{"name":"default","abstract":"

Default NetworkReachabilityManager for the zero address and a listenerQueue of .main.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC11isReachableSbvp":{"name":"isReachable","abstract":"

Whether the network is currently reachable.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC21isReachableOnCellularSbvp":{"name":"isReachableOnCellular","abstract":"

Whether the network is currently reachable over the cellular interface.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC27isReachableOnEthernetOrWiFiSbvp":{"name":"isReachableOnEthernetOrWiFi","abstract":"

Whether the network is currently reachable over Ethernet or WiFi interface.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC17reachabilityQueueSo17OS_dispatch_queueCvp":{"name":"reachabilityQueue","abstract":"

DispatchQueue on which reachability will update.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC5flagsSo09SCNetworkC5FlagsVSgvp":{"name":"flags","abstract":"

Flags of the current reachability type, if any.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC6statusAC0bC6StatusOvp":{"name":"status","abstract":"

The current network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC4hostACSgSS_tcfc":{"name":"init(host:)","abstract":"

Creates an instance with the specified host.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerCACSgycfc":{"name":"init()","abstract":"

Creates an instance that monitors the address 0.0.0.0.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC14startListening7onQueue0G16UpdatePerformingSbSo17OS_dispatch_queueC_yAC0bC6StatusOctF":{"name":"startListening(onQueue:onUpdatePerforming:)","abstract":"

Starts listening for changes in network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC13stopListeningyyF":{"name":"stopListening()","abstract":"

Stops listening for changes in network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC23encodingMemoryThresholds6UInt64VvpZ":{"name":"encodingMemoryThreshold","abstract":"

Default memory threshold used when encoding MultipartFormData, in bytes.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC11contentTypeSSvp":{"name":"contentType","abstract":"

The Content-Type header value containing the boundary used to generate the multipart/form-data.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC13contentLengths6UInt64Vvp":{"name":"contentLength","abstract":"

The content length of all body parts used to generate the multipart/form-data not including the boundaries.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC8boundarySSvp":{"name":"boundary","abstract":"

The boundary used to separate the body parts in the encoded form data.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC11fileManager8boundaryACSo06NSFileF0C_SSSgtcfc":{"name":"init(fileManager:boundary:)","abstract":"

Creates an instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withName04fileG08mimeTypey10Foundation0D0V_S2SSgAKtF":{"name":"append(_:withName:fileName:mimeType:)","abstract":"

Creates a body part from the data and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withNamey10Foundation3URLV_SStF":{"name":"append(_:withName:)","abstract":"

Creates a body part from the file and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withName04fileG08mimeTypey10Foundation3URLV_S3StF":{"name":"append(_:withName:fileName:mimeType:)","abstract":"

Creates a body part from the file and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_10withLength4name8fileName8mimeTypeySo13NSInputStreamC_s6UInt64VS3StF":{"name":"append(_:withLength:name:fileName:mimeType:)","abstract":"

Creates a body part from the stream and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_10withLength7headersySo13NSInputStreamC_s6UInt64VAA11HTTPHeadersVtF":{"name":"append(_:withLength:headers:)","abstract":"

Creates a body part with the stream, length, and headers and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6encode10Foundation0D0VyKF":{"name":"encode()","abstract":"

Encodes all appended body parts into a single Data value.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC012writeEncodedD02toy10Foundation3URLV_tKF":{"name":"writeEncodedData(to:)","abstract":"

Writes all appended body parts to the given file URL.

","parent_name":"MultipartFormData"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC32sessionDidBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtcSgvp":{"name":"sessionDidBecomeInvalidWithError","abstract":"

Closure called on the urlSession(_:didBecomeInvalidWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23taskDidReceiveChallengeySo12NSURLSessionC_So0I4TaskCSo019NSURLAuthenticationH0CtcSgvp":{"name":"taskDidReceiveChallenge","abstract":"

Closure called on the urlSession(_:task:didReceive:completionHandler:).

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC19taskDidSendBodyDataySo12NSURLSessionC_So0J4TaskCs5Int64VA2JtcSgvp":{"name":"taskDidSendBodyData","abstract":"

Closure that receives urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC21taskNeedNewBodyStreamySo12NSURLSessionC_So0J4TaskCtcSgvp":{"name":"taskNeedNewBodyStream","abstract":"

Closure called on the urlSession(_:task:needNewBodyStream:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30taskWillPerformHTTPRedirectionySo12NSURLSessionC_So0I4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtcSgvp":{"name":"taskWillPerformHTTPRedirection","abstract":"

Closure called on the urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30taskDidFinishCollectingMetricsySo12NSURLSessionC_So0J4TaskCSo0jkI0CtcSgvp":{"name":"taskDidFinishCollectingMetrics","abstract":"

Closure called on the urlSession(_:task:didFinishCollecting:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC15taskDidCompleteySo12NSURLSessionC_So0H4TaskCs5Error_pSgtcSgvp":{"name":"taskDidComplete","abstract":"

Closure called on the urlSession(_:task:didCompleteWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC28taskIsWaitingForConnectivityySo12NSURLSessionC_So0J4TaskCtcSgvp":{"name":"taskIsWaitingForConnectivity","abstract":"

Closure called on the urlSession(_:taskIsWaitingForConnectivity:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC22dataTaskDidReceiveDataySo12NSURLSessionC_So0jiF0C10Foundation0I0VtcSgvp":{"name":"dataTaskDidReceiveData","abstract":"

Closure that receives the urlSession(_:dataTask:didReceive:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC25dataTaskWillCacheResponseySo12NSURLSessionC_So0j4DataF0CSo19NSCachedURLResponseCtcSgvp":{"name":"dataTaskWillCacheResponse","abstract":"

Closure called on the urlSession(_:dataTask:willCacheResponse:completionHandler:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC37downloadTaskDidFinishDownloadingToURLySo12NSURLSessionC_So0l8DownloadF0C10Foundation0K0VtcSgvp":{"name":"downloadTaskDidFinishDownloadingToURL","abstract":"

Closure called on the urlSession(_:downloadTask:didFinishDownloadingTo:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC24downloadTaskDidWriteDataySo12NSURLSessionC_So0j8DownloadF0Cs5Int64VA2JtcSgvp":{"name":"downloadTaskDidWriteData","abstract":"

Closure called on the urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC29downloadTaskDidResumeAtOffsetySo12NSURLSessionC_So0k8DownloadF0Cs5Int64VAJtcSgvp":{"name":"downloadTaskDidResumeAtOffset","abstract":"

Closure called on the urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC33requestDidCreateInitialURLRequestyAA7RequestC_10Foundation0I0VtcSgvp":{"name":"requestDidCreateInitialURLRequest","abstract":"

Closure called on the request(_:didCreateInitialURLRequest:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC41requestDidFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtcSgvp":{"name":"requestDidFailToCreateURLRequestWithError","abstract":"

Closure called on the request(_:didFailToCreateURLRequestWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC038requestDidAdaptInitialRequestToAdaptedI0yAA0I0C_10Foundation10URLRequestVAItcSgvp":{"name":"requestDidAdaptInitialRequestToAdaptedRequest","abstract":"

Closure called on the request(_:didAdaptInitialRequest:to:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC40requestDidFailToAdaptURLRequestWithErroryAA7RequestC_10Foundation0J0VAA7AFErrorOtcSgvp":{"name":"requestDidFailToAdaptURLRequestWithError","abstract":"

Closure called on the request(_:didFailToAdaptURLRequest:withError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC26requestDidCreateURLRequestyAA7RequestC_10Foundation0H0VtcSgvp":{"name":"requestDidCreateURLRequest","abstract":"

Closure called on the request(_:didCreateURLRequest:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidCreateTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidCreateTask","abstract":"

Closure called on the request(_:didCreateTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23requestDidGatherMetricsyAA7RequestC_So016NSURLSessionTaskH0CtcSgvp":{"name":"requestDidGatherMetrics","abstract":"

Closure called on the request(_:didGatherMetrics:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC32requestDidFailTaskEarlyWithErroryAA7RequestC_So012NSURLSessionH0CAA7AFErrorOtcSgvp":{"name":"requestDidFailTaskEarlyWithError","abstract":"

Closure called on the request(_:didFailTask:earlyWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC31requestDidCompleteTaskWithErroryAA7RequestC_So012NSURLSessionH0CAA7AFErrorOSgtcSgvp":{"name":"requestDidCompleteTaskWithError","abstract":"

Closure called on the request(_:didCompleteTask:with:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC17requestIsRetryingyAA7RequestCcSgvp":{"name":"requestIsRetrying","abstract":"

Closure called on the requestIsRetrying(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidFinishyAA7RequestCcSgvp":{"name":"requestDidFinish","abstract":"

Closure called on the requestDidFinish(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidResumeyAA7RequestCcSgvp":{"name":"requestDidResume","abstract":"

Closure called on the requestDidResume(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidResumeTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidResumeTask","abstract":"

Closure called on the request(_:didResumeTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC17requestDidSuspendyAA7RequestCcSgvp":{"name":"requestDidSuspend","abstract":"

Closure called on the requestDidSuspend(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC21requestDidSuspendTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidSuspendTask","abstract":"

Closure called on the request(_:didSuspendTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidCancelyAA7RequestCcSgvp":{"name":"requestDidCancel","abstract":"

Closure called on the requestDidCancel(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidCancelTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidCancelTask","abstract":"

Closure called on the request(_:didCancelTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC47requestDidValidateRequestResponseDataWithResultyAA0jH0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAG0J0VSgs0L0Oyyts5Error_pGtcSgvp":{"name":"requestDidValidateRequestResponseDataWithResult","abstract":"

Closure called on the request(_:didValidateRequest:response:data:withResult:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23requestDidParseResponseyAA11DataRequestC_AA0iH0Vy10Foundation0I0VSgAA7AFErrorOGtcSgvp":{"name":"requestDidParseResponse","abstract":"

Closure called on the request(_:didParseResponse:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC26requestDidCreateUploadableyAA13UploadRequestC_AF0H0OtcSgvp":{"name":"requestDidCreateUploadable","abstract":"

Closure called on the request(_:didCreateUploadable:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC41requestDidFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtcSgvp":{"name":"requestDidFailToCreateUploadableWithError","abstract":"

Closure called on the request(_:didFailToCreateUploadableWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC28requestDidProvideInputStreamyAA13UploadRequestC_So07NSInputI0CtcSgvp":{"name":"requestDidProvideInputStream","abstract":"

Closure called on the request(_:didProvideInputStream:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC46requestDidFinishDownloadingUsingTaskWithResultyAA15DownloadRequestC_So012NSURLSessionJ0Cs0L0Oy10Foundation3URLVAA7AFErrorOGtcSgvp":{"name":"requestDidFinishDownloadingUsingTaskWithResult","abstract":"

Closure called on the request(_:didFinishDownloadingUsing:with:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30requestDidCreateDestinationURLyAA15DownloadRequestC_10Foundation0I0VtcSgvp":{"name":"requestDidCreateDestinationURL","abstract":"

Closure called on the request(_:didCreateDestinationURL:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC50requestDidValidateRequestResponseFileURLWithResultyAA08DownloadH0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAG3URLVSgs0L0Oyyts5Error_pGtcSgvp":{"name":"requestDidValidateRequestResponseFileURLWithResult","abstract":"

Closure called on the request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC31requestDidParseDownloadResponseyAA0H7RequestC_AA0hI0Vy10Foundation3URLVSgAA7AFErrorOGtcSgvp":{"name":"requestDidParseDownloadResponse","abstract":"

Closure called on the request(_:didParseResponse:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC5queueACSo012OS_dispatch_E0C_tcfc":{"name":"init(queue:)","abstract":"

Creates an instance using the provided queue.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"ClosureEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html":{"name":"CompositeEventMonitor","abstract":"

An EventMonitor which can contain multiple EventMonitors and calls their methods on their queues.

"},"Classes/ClosureEventMonitor.html":{"name":"ClosureEventMonitor","abstract":"

EventMonitor that allows optional closures to be set to receive events.

"},"Classes/MultipartFormData.html":{"name":"MultipartFormData","abstract":"

Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode"},"Classes/NetworkReachabilityManager.html":{"name":"NetworkReachabilityManager","abstract":"

The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and"},"Classes/Request.html":{"name":"Request","abstract":"

Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback"},"Classes/AlamofireNotifications.html":{"name":"AlamofireNotifications","abstract":"

EventMonitor that provides Alamofire’s notifications.

"},"Classes/JSONParameterEncoder.html":{"name":"JSONParameterEncoder","abstract":"

A ParameterEncoder that encodes types as JSON body data.

"},"Classes/URLEncodedFormParameterEncoder.html":{"name":"URLEncodedFormParameterEncoder","abstract":"

A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending"},"Classes/DataRequest.html":{"name":"DataRequest","abstract":"

Request subclass which handles in-memory Data download using URLSessionDataTask.

"},"Classes/DownloadRequest.html":{"name":"DownloadRequest","abstract":"

Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

"},"Classes/UploadRequest.html":{"name":"UploadRequest","abstract":"

DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

"},"Classes/Adapter.html":{"name":"Adapter","abstract":"

Closure-based RequestAdapter.

"},"Classes/Retrier.html":{"name":"Retrier","abstract":"

Closure-based RequestRetrier.

"},"Classes/Interceptor.html":{"name":"Interceptor","abstract":"

RequestInterceptor which can use multiple RequestAdapter and RequestRetrier values.

"},"Classes/DataResponseSerializer.html":{"name":"DataResponseSerializer","abstract":"

A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a"},"Classes/StringResponseSerializer.html":{"name":"StringResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no"},"Classes/JSONResponseSerializer.html":{"name":"JSONResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning"},"Classes/DecodableResponseSerializer.html":{"name":"DecodableResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data as a generic value using any type that conforms to"},"Classes/RetryPolicy.html":{"name":"RetryPolicy","abstract":"

A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes"},"Classes/ConnectionLostRetryPolicy.html":{"name":"ConnectionLostRetryPolicy","abstract":"

A retry policy that automatically retries idempotent requests for network connection lost errors. For more"},"Classes/ServerTrustManager.html":{"name":"ServerTrustManager","abstract":"

Responsible for managing the mapping of ServerTrustEvaluating values to given hosts.

"},"Classes/DefaultTrustEvaluator.html":{"name":"DefaultTrustEvaluator","abstract":"

An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the"},"Classes/RevocationTrustEvaluator.html":{"name":"RevocationTrustEvaluator","abstract":"

An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate"},"Classes/PinnedCertificatesTrustEvaluator.html":{"name":"PinnedCertificatesTrustEvaluator","abstract":"

Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned"},"Classes/PublicKeysTrustEvaluator.html":{"name":"PublicKeysTrustEvaluator","abstract":"

Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned"},"Classes/CompositeTrustEvaluator.html":{"name":"CompositeTrustEvaluator","abstract":"

Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the"},"Classes/DisabledEvaluator.html":{"name":"DisabledEvaluator","abstract":"

Disables all evaluation which in turn will always consider any server trust as valid.

"},"Classes/Session.html":{"name":"Session","abstract":"

Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common"},"Classes/SessionDelegate.html":{"name":"SessionDelegate","abstract":"

Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

"},"Classes/URLEncodedFormEncoder.html":{"name":"URLEncodedFormEncoder","abstract":"

An object that encodes instances into URL-encoded query strings.

"},"Classes.html":{"name":"Classes","abstract":"

The following classes are available globally.

"},"Enums.html":{"name":"Enumerations","abstract":"

The following enumerations are available globally.

"},"Extensions.html":{"name":"Extensions","abstract":"

The following extensions are available globally.

"},"Protocols.html":{"name":"Protocols","abstract":"

The following protocols are available globally.

"},"Structs.html":{"name":"Structures","abstract":"

The following structures are available globally.

"},"Typealiases.html":{"name":"Type Aliases","abstract":"

The following type aliases are available globally.

"}} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/undocumented.json b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/undocumented.json deleted file mode 100644 index 11210e8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/Documents/undocumented.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "warnings": [ - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 269, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 270, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 281, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 282, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/ResponseSerialization.swift", - "line": 84, - "symbol": "PassthroughPreprocessor.init()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/ResponseSerialization.swift", - "line": 91, - "symbol": "GoogleXSSIPreprocessor.init()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 59, - "symbol": "SessionDelegate.urlSession(_:didBecomeInvalidWithError:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 72, - "symbol": "SessionDelegate.urlSession(_:task:didReceive:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 144, - "symbol": "SessionDelegate.urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 159, - "symbol": "SessionDelegate.urlSession(_:task:needNewBodyStream:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 171, - "symbol": "SessionDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 185, - "symbol": "SessionDelegate.urlSession(_:task:didFinishCollecting:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 193, - "symbol": "SessionDelegate.urlSession(_:task:didCompleteWithError:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 202, - "symbol": "SessionDelegate.urlSession(_:taskIsWaitingForConnectivity:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 210, - "symbol": "SessionDelegate.urlSession(_:dataTask:didReceive:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 220, - "symbol": "SessionDelegate.urlSession(_:dataTask:willCacheResponse:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 237, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 254, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 273, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didFinishDownloadingTo:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/URLRequest+Alamofire.swift", - "line": 34, - "symbol": "URLRequest.validate()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - } - ], - "source_directory": "/Users/jshier/Desktop/Code/Alamofire" -} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/docSet.dsidx b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/docSet.dsidx deleted file mode 100644 index 3a3a880..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.docset/Contents/Resources/docSet.dsidx and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.tgz b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.tgz deleted file mode 100644 index f82b098..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.tgz and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.xml b/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.xml deleted file mode 100644 index 2a5492d..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/docsets/Alamofire.xml +++ /dev/null @@ -1 +0,0 @@ -5.0.0-rc.3https://alamofire.github.io/Alamofire/docsets/Alamofire.tgz diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/carat.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/img/carat.png deleted file mode 100755 index 29d2f7f..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/carat.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/dash.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/img/dash.png deleted file mode 100755 index 6f694c7..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/dash.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/gh.png b/Lesson12/Carthage/Checkouts/Alamofire/docs/img/gh.png deleted file mode 100755 index 628da97..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/gh.png and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/spinner.gif b/Lesson12/Carthage/Checkouts/Alamofire/docs/img/spinner.gif deleted file mode 100644 index e3038d0..0000000 Binary files a/Lesson12/Carthage/Checkouts/Alamofire/docs/img/spinner.gif and /dev/null differ diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/index.html b/Lesson12/Carthage/Checkouts/Alamofire/docs/index.html deleted file mode 100644 index 24cfd10..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/index.html +++ /dev/null @@ -1,650 +0,0 @@ - - - - Alamofire Reference - - - - - - - - - - - - - - - -
-

- - Alamofire Docs - - (98% documented) -

- -

-

- -
-

- -

- - - View on GitHub - -

- -

- - - Install in Dash - -

-
- - - -
- -
- -
-
- -

Alamofire: Elegant Networking in Swift

- -

Build Status -CocoaPods Compatible -Carthage Compatible -Platform -Twitter -Gitter -Open Source Helpers

- -

Alamofire is an HTTP networking library written in Swift.

- -

⚠️⚠️⚠️ WARNING ⚠️⚠️⚠️ This documentation is out of date during the Alamofire 5 beta process.

- - -

Features

- -
    -
  • [x] Chainable Request / Response Methods
  • -
  • [x] URL / JSON / plist Parameter Encoding
  • -
  • [x] Upload File / Data / Stream / MultipartFormData
  • -
  • [x] Download File using Request or Resume Data
  • -
  • [x] Authentication with URLCredential
  • -
  • [x] HTTP Response Validation
  • -
  • [x] Upload and Download Progress Closures with Progress
  • -
  • [x] cURL Command Output
  • -
  • [x] Dynamically Adapt and Retry Requests
  • -
  • [x] TLS Certificate and Public Key Pinning
  • -
  • [x] Network Reachability
  • -
  • [x] Comprehensive Unit and Integration Test Coverage
  • -
  • [x] Complete Documentation
  • -
-

Component Libraries

- -

In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem.

- -
    -
  • AlamofireImage - An image library including image response serializers, UIImage and UIImageView extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
  • -
  • AlamofireNetworkActivityIndicator - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support URLSession instances not managed by Alamofire.
  • -
-

Requirements

- -
    -
  • iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • -
  • Xcode 10.2+
  • -
  • Swift 5+
  • -
-

Migration Guides

- - -

Communication

- - -

Installation

-

CocoaPods

- -

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

-
pod 'Alamofire', '~> 5.0.0-rc.3'
-
-

Carthage

- -

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

-
github "Alamofire/Alamofire" "5.0.0-rc.3"
-
-

Swift Package Manager

- -

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms.

- -

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift.

-
dependencies: [
-    .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.0.0-rc.3")
-]
-
-

Manually

- -

If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

-

Embedded Framework

- -
    -
  • Open up Terminal, cd into your top-level project directory, and run the following command if your project is not initialized as a git repository:
  • -
-
  $ git init
-
- -
    -
  • Add Alamofire as a git submodule by running the following command:
  • -
-
  $ git submodule add https://github.com/Alamofire/Alamofire.git
-
- -
    -
  • Open the new Alamofire folder, and drag the Alamofire.xcodeproj into the Project Navigator of your application’s Xcode project.

    - -
    -

    It should appear nested underneath your application’s blue project icon. Whether it is above or below all the other Xcode groups does not matter.

    -
  • -
  • Select the Alamofire.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • -
  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the Targets heading in the sidebar.

  • -
  • In the tab bar at the top of that window, open the General panel.

  • -
  • Click on the + button under the Embedded Binaries section.

  • -
  • You will see two different Alamofire.xcodeproj folders each with two different versions of the Alamofire.framework nested inside a Products folder.

    - -
    -

    It does not matter which Products folder you choose from, but it does matter whether you choose the top or bottom Alamofire.framework.

    -
  • -
  • Select the top Alamofire.framework for iOS and the bottom one for macOS.

    - -
    -

    You can verify which one you selected by inspecting the build log for your project. The build target for Alamofire will be listed as either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire watchOS.

    -
  • -
  • And that’s it!

  • -
- -
-

The Alamofire.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.

-
-

Open Radars

- -

The following radars have some effect on the current implementation of Alamofire.

- -
    -
  • rdar://21349340 - Compiler throwing warning due to toll-free bridging issue in test case
  • -
  • rdar://26870455 - Background URL Session Configurations do not work in the simulator
  • -
  • rdar://26849668 - Some URLProtocol APIs do not properly handle URLRequest
  • -
-

Resolved Radars

- -

The following radars have been resolved over time after being filed against the Alamofire project.

- -
    -
  • rdar://26761490 - Swift string interpolation causing memory leak with common usage. - -
      -
    • (Resolved): 9/1/17 in Xcode 9 beta 6.
    • -
  • -
  • rdar://36082113 - URLSessionTaskMetrics failing to link on watchOS 3.0+ - -
      -
    • (Resolved): Just add CFNetwork to your linked frameworks.
    • -
  • -
-

FAQ

-

What’s the origin of the name Alamofire?

- -

Alamofire is named after the Alamo Fire flower, a hybrid variant of the Bluebonnet, the official state flower of Texas.

-

Credits

- -

Alamofire is owned and maintained by the Alamofire Software Foundation. You can follow them on Twitter at @AlamofireSF for project updates and releases.

-

Security Disclosure

- -

If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.

-

Donations

- -

The ASF is looking to raise money to officially stay registered as a federal non-profit organization. -Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. -Donating to the ASF will enable us to:

- -
    -
  • Pay our yearly legal fees to keep the non-profit in good status
  • -
  • Pay for our mail servers to help us stay on top of all questions and security issues
  • -
  • Potentially fund test servers to make it easier for us to test the edge cases
  • -
  • Potentially fund developers to work on one of our projects full-time
  • -
- -

The community adoption of the ASF libraries has been amazing. -We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. -With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. -If you use any of our libraries for work, see if your employers would be interested in donating. -Any amount you can donate today to help us reach our goal would be greatly appreciated.

- -

paypal

-

License

- -

Alamofire is released under the MIT license. See LICENSE for details.

- -
-
- - -
-
- - -
- diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.js deleted file mode 100755 index c31dc05..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.js +++ /dev/null @@ -1,59 +0,0 @@ -window.jazzy = {'docset': false} -if (typeof window.dash != 'undefined') { - document.documentElement.className += ' dash' - window.jazzy.docset = true -} -if (navigator.userAgent.match(/xcode/i)) { - document.documentElement.className += ' xcode' - window.jazzy.docset = true -} - -function toggleItem($link, $content) { - var animationDuration = 300; - $link.toggleClass('token-open'); - $content.slideToggle(animationDuration); -} - -function itemLinkToContent($link) { - return $link.parent().parent().next(); -} - -// On doc load + hash-change, open any targetted item -function openCurrentItemIfClosed() { - if (window.jazzy.docset) { - return; - } - var $link = $(`.token[href="${location.hash}"]`); - $content = itemLinkToContent($link); - if ($content.is(':hidden')) { - toggleItem($link, $content); - } -} - -$(openCurrentItemIfClosed); -$(window).on('hashchange', openCurrentItemIfClosed); - -// On item link ('token') click, toggle its discussion -$('.token').on('click', function(event) { - if (window.jazzy.docset) { - return; - } - var $link = $(this); - toggleItem($link, itemLinkToContent($link)); - - // Keeps the document from jumping to the hash. - var href = $link.attr('href'); - if (history.pushState) { - history.pushState({}, '', href); - } else { - location.hash = href; - } - event.preventDefault(); -}); - -// Clicks on links to the current, closed, item need to open the item -$("a:not('.token')").on('click', function() { - if (location == this.href) { - openCurrentItemIfClosed(); - } -}); diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.search.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.search.js deleted file mode 100644 index e3d1ab9..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jazzy.search.js +++ /dev/null @@ -1,70 +0,0 @@ -$(function(){ - var $typeahead = $('[data-typeahead]'); - var $form = $typeahead.parents('form'); - var searchURL = $form.attr('action'); - - function displayTemplate(result) { - return result.name; - } - - function suggestionTemplate(result) { - var t = '
'; - t += '' + result.name + ''; - if (result.parent_name) { - t += '' + result.parent_name + ''; - } - t += '
'; - return t; - } - - $typeahead.one('focus', function() { - $form.addClass('loading'); - - $.getJSON(searchURL).then(function(searchData) { - const searchIndex = lunr(function() { - this.ref('url'); - this.field('name'); - this.field('abstract'); - for (const [url, doc] of Object.entries(searchData)) { - this.add({url: url, name: doc.name, abstract: doc.abstract}); - } - }); - - $typeahead.typeahead( - { - highlight: true, - minLength: 3, - autoselect: true - }, - { - limit: 10, - display: displayTemplate, - templates: { suggestion: suggestionTemplate }, - source: function(query, sync) { - const lcSearch = query.toLowerCase(); - const results = searchIndex.query(function(q) { - q.term(lcSearch, { boost: 100 }); - q.term(lcSearch, { - boost: 10, - wildcard: lunr.Query.wildcard.TRAILING - }); - }).map(function(result) { - var doc = searchData[result.ref]; - doc.url = result.ref; - return doc; - }); - sync(results); - } - } - ); - $form.removeClass('loading'); - $typeahead.trigger('focus'); - }); - }); - - var baseURL = searchURL.slice(0, -"search.json".length); - - $typeahead.on('typeahead:select', function(e, result) { - window.location = baseURL + result.url; - }); -}); diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jquery.min.js b/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jquery.min.js deleted file mode 100755 index a1c07fd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/js/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0=this.length)return z.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},z.QueryLexer.prototype.width=function(){return this.pos-this.start},z.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},z.QueryLexer.prototype.backup=function(){this.pos-=1},z.QueryLexer.prototype.acceptDigitRun=function(){for(var e,t;47<(t=(e=this.next()).charCodeAt(0))&&t<58;);e!=z.QueryLexer.EOS&&this.backup()},z.QueryLexer.prototype.more=function(){return this.pos', - menu: '
' - }; - } - function buildSelectors(classes) { - var selectors = {}; - _.each(classes, function(v, k) { - selectors[k] = "." + v; - }); - return selectors; - } - function buildCss() { - var css = { - wrapper: { - position: "relative", - display: "inline-block" - }, - hint: { - position: "absolute", - top: "0", - left: "0", - borderColor: "transparent", - boxShadow: "none", - opacity: "1" - }, - input: { - position: "relative", - verticalAlign: "top", - backgroundColor: "transparent" - }, - inputWithNoHint: { - position: "relative", - verticalAlign: "top" - }, - menu: { - position: "absolute", - top: "100%", - left: "0", - zIndex: "100", - display: "none" - }, - ltr: { - left: "0", - right: "auto" - }, - rtl: { - left: "auto", - right: " 0" - } - }; - if (_.isMsie()) { - _.mixin(css.input, { - backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" - }); - } - return css; - } - }(); - var EventBus = function() { - "use strict"; - var namespace, deprecationMap; - namespace = "typeahead:"; - deprecationMap = { - render: "rendered", - cursorchange: "cursorchanged", - select: "selected", - autocomplete: "autocompleted" - }; - function EventBus(o) { - if (!o || !o.el) { - $.error("EventBus initialized without el"); - } - this.$el = $(o.el); - } - _.mixin(EventBus.prototype, { - _trigger: function(type, args) { - var $e = $.Event(namespace + type); - this.$el.trigger.call(this.$el, $e, args || []); - return $e; - }, - before: function(type) { - var args, $e; - args = [].slice.call(arguments, 1); - $e = this._trigger("before" + type, args); - return $e.isDefaultPrevented(); - }, - trigger: function(type) { - var deprecatedType; - this._trigger(type, [].slice.call(arguments, 1)); - if (deprecatedType = deprecationMap[type]) { - this._trigger(deprecatedType, [].slice.call(arguments, 1)); - } - } - }); - return EventBus; - }(); - var EventEmitter = function() { - "use strict"; - var splitter = /\s+/, nextTick = getNextTick(); - return { - onSync: onSync, - onAsync: onAsync, - off: off, - trigger: trigger - }; - function on(method, types, cb, context) { - var type; - if (!cb) { - return this; - } - types = types.split(splitter); - cb = context ? bindContext(cb, context) : cb; - this._callbacks = this._callbacks || {}; - while (type = types.shift()) { - this._callbacks[type] = this._callbacks[type] || { - sync: [], - async: [] - }; - this._callbacks[type][method].push(cb); - } - return this; - } - function onAsync(types, cb, context) { - return on.call(this, "async", types, cb, context); - } - function onSync(types, cb, context) { - return on.call(this, "sync", types, cb, context); - } - function off(types) { - var type; - if (!this._callbacks) { - return this; - } - types = types.split(splitter); - while (type = types.shift()) { - delete this._callbacks[type]; - } - return this; - } - function trigger(types) { - var type, callbacks, args, syncFlush, asyncFlush; - if (!this._callbacks) { - return this; - } - types = types.split(splitter); - args = [].slice.call(arguments, 1); - while ((type = types.shift()) && (callbacks = this._callbacks[type])) { - syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); - asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); - syncFlush() && nextTick(asyncFlush); - } - return this; - } - function getFlush(callbacks, context, args) { - return flush; - function flush() { - var cancelled; - for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { - cancelled = callbacks[i].apply(context, args) === false; - } - return !cancelled; - } - } - function getNextTick() { - var nextTickFn; - if (window.setImmediate) { - nextTickFn = function nextTickSetImmediate(fn) { - setImmediate(function() { - fn(); - }); - }; - } else { - nextTickFn = function nextTickSetTimeout(fn) { - setTimeout(function() { - fn(); - }, 0); - }; - } - return nextTickFn; - } - function bindContext(fn, context) { - return fn.bind ? fn.bind(context) : function() { - fn.apply(context, [].slice.call(arguments, 0)); - }; - } - }(); - var highlight = function(doc) { - "use strict"; - var defaults = { - node: null, - pattern: null, - tagName: "strong", - className: null, - wordsOnly: false, - caseSensitive: false, - diacriticInsensitive: false - }; - var accented = { - A: "[AaªÀ-Åà-åĀ-ąǍǎȀ-ȃȦȧᴬᵃḀḁẚẠ-ảₐ℀℁℻⒜Ⓐⓐ㍱-㍴㎀-㎄㎈㎉㎩-㎯㏂㏊㏟㏿Aa]", - B: "[BbᴮᵇḂ-ḇℬ⒝Ⓑⓑ㍴㎅-㎇㏃㏈㏔㏝Bb]", - C: "[CcÇçĆ-čᶜ℀ℂ℃℅℆ℭⅭⅽ⒞Ⓒⓒ㍶㎈㎉㎝㎠㎤㏄-㏇Cc]", - D: "[DdĎďDŽ-džDZ-dzᴰᵈḊ-ḓⅅⅆⅮⅾ⒟Ⓓⓓ㋏㍲㍷-㍹㎗㎭-㎯㏅㏈Dd]", - E: "[EeÈ-Ëè-ëĒ-ěȄ-ȇȨȩᴱᵉḘ-ḛẸ-ẽₑ℡ℯℰⅇ⒠Ⓔⓔ㉐㋍㋎Ee]", - F: "[FfᶠḞḟ℉ℱ℻⒡Ⓕⓕ㎊-㎌㎙ff-fflFf]", - G: "[GgĜ-ģǦǧǴǵᴳᵍḠḡℊ⒢Ⓖⓖ㋌㋍㎇㎍-㎏㎓㎬㏆㏉㏒㏿Gg]", - H: "[HhĤĥȞȟʰᴴḢ-ḫẖℋ-ℎ⒣Ⓗⓗ㋌㍱㎐-㎔㏊㏋㏗Hh]", - I: "[IiÌ-Ïì-ïĨ-İIJijǏǐȈ-ȋᴵᵢḬḭỈ-ịⁱℐℑℹⅈⅠ-ⅣⅥ-ⅨⅪⅫⅰ-ⅳⅵ-ⅸⅺⅻ⒤Ⓘⓘ㍺㏌㏕fiffiIi]", - J: "[JjIJ-ĵLJ-njǰʲᴶⅉ⒥ⒿⓙⱼJj]", - K: "[KkĶķǨǩᴷᵏḰ-ḵK⒦Ⓚⓚ㎄㎅㎉㎏㎑㎘㎞㎢㎦㎪㎸㎾㏀㏆㏍-㏏Kk]", - L: "[LlĹ-ŀLJ-ljˡᴸḶḷḺ-ḽℒℓ℡Ⅼⅼ⒧Ⓛⓛ㋏㎈㎉㏐-㏓㏕㏖㏿flfflLl]", - M: "[MmᴹᵐḾ-ṃ℠™ℳⅯⅿ⒨Ⓜⓜ㍷-㍹㎃㎆㎎㎒㎖㎙-㎨㎫㎳㎷㎹㎽㎿㏁㏂㏎㏐㏔-㏖㏘㏙㏞㏟Mm]", - N: "[NnÑñŃ-ʼnNJ-njǸǹᴺṄ-ṋⁿℕ№⒩Ⓝⓝ㎁㎋㎚㎱㎵㎻㏌㏑Nn]", - O: "[OoºÒ-Öò-öŌ-őƠơǑǒǪǫȌ-ȏȮȯᴼᵒỌ-ỏₒ℅№ℴ⒪Ⓞⓞ㍵㏇㏒㏖Oo]", - P: "[PpᴾᵖṔ-ṗℙ⒫Ⓟⓟ㉐㍱㍶㎀㎊㎩-㎬㎰㎴㎺㏋㏗-㏚Pp]", - Q: "[Qqℚ⒬Ⓠⓠ㏃Qq]", - R: "[RrŔ-řȐ-ȓʳᴿᵣṘ-ṛṞṟ₨ℛ-ℝ⒭Ⓡⓡ㋍㍴㎭-㎯㏚㏛Rr]", - S: "[SsŚ-šſȘșˢṠ-ṣ₨℁℠⒮Ⓢⓢ㎧㎨㎮-㎳㏛㏜stSs]", - T: "[TtŢ-ťȚțᵀᵗṪ-ṱẗ℡™⒯Ⓣⓣ㉐㋏㎔㏏ſtstTt]", - U: "[UuÙ-Üù-üŨ-ųƯưǓǔȔ-ȗᵁᵘᵤṲ-ṷỤ-ủ℆⒰Ⓤⓤ㍳㍺Uu]", - V: "[VvᵛᵥṼ-ṿⅣ-Ⅷⅳ-ⅷ⒱Ⓥⓥⱽ㋎㍵㎴-㎹㏜㏞Vv]", - W: "[WwŴŵʷᵂẀ-ẉẘ⒲Ⓦⓦ㎺-㎿㏝Ww]", - X: "[XxˣẊ-ẍₓ℻Ⅸ-Ⅻⅸ-ⅻ⒳Ⓧⓧ㏓Xx]", - Y: "[YyÝýÿŶ-ŸȲȳʸẎẏẙỲ-ỹ⒴Ⓨⓨ㏉Yy]", - Z: "[ZzŹ-žDZ-dzᶻẐ-ẕℤℨ⒵Ⓩⓩ㎐-㎔Zz]" - }; - return function hightlight(o) { - var regex; - o = _.mixin({}, defaults, o); - if (!o.node || !o.pattern) { - return; - } - o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; - regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly, o.diacriticInsensitive); - traverse(o.node, hightlightTextNode); - function hightlightTextNode(textNode) { - var match, patternNode, wrapperNode; - if (match = regex.exec(textNode.data)) { - wrapperNode = doc.createElement(o.tagName); - o.className && (wrapperNode.className = o.className); - patternNode = textNode.splitText(match.index); - patternNode.splitText(match[0].length); - wrapperNode.appendChild(patternNode.cloneNode(true)); - textNode.parentNode.replaceChild(wrapperNode, patternNode); - } - return !!match; - } - function traverse(el, hightlightTextNode) { - var childNode, TEXT_NODE_TYPE = 3; - for (var i = 0; i < el.childNodes.length; i++) { - childNode = el.childNodes[i]; - if (childNode.nodeType === TEXT_NODE_TYPE) { - i += hightlightTextNode(childNode) ? 1 : 0; - } else { - traverse(childNode, hightlightTextNode); - } - } - } - }; - function accent_replacer(chr) { - return accented[chr.toUpperCase()] || chr; - } - function getRegex(patterns, caseSensitive, wordsOnly, diacriticInsensitive) { - var escapedPatterns = [], regexStr; - for (var i = 0, len = patterns.length; i < len; i++) { - var escapedWord = _.escapeRegExChars(patterns[i]); - if (diacriticInsensitive) { - escapedWord = escapedWord.replace(/\S/g, accent_replacer); - } - escapedPatterns.push(escapedWord); - } - regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; - return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); - } - }(window.document); - var Input = function() { - "use strict"; - var specialKeyCodeMap; - specialKeyCodeMap = { - 9: "tab", - 27: "esc", - 37: "left", - 39: "right", - 13: "enter", - 38: "up", - 40: "down" - }; - function Input(o, www) { - o = o || {}; - if (!o.input) { - $.error("input is missing"); - } - www.mixin(this); - this.$hint = $(o.hint); - this.$input = $(o.input); - this.$input.attr({ - "aria-activedescendant": "", - "aria-owns": this.$input.attr("id") + "_listbox", - role: "combobox", - "aria-readonly": "true", - "aria-autocomplete": "list" - }); - $(www.menu).attr("id", this.$input.attr("id") + "_listbox"); - this.query = this.$input.val(); - this.queryWhenFocused = this.hasFocus() ? this.query : null; - this.$overflowHelper = buildOverflowHelper(this.$input); - this._checkLanguageDirection(); - if (this.$hint.length === 0) { - this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; - } - this.onSync("cursorchange", this._updateDescendent); - } - Input.normalizeQuery = function(str) { - return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " "); - }; - _.mixin(Input.prototype, EventEmitter, { - _onBlur: function onBlur() { - this.resetInputValue(); - this.trigger("blurred"); - }, - _onFocus: function onFocus() { - this.queryWhenFocused = this.query; - this.trigger("focused"); - }, - _onKeydown: function onKeydown($e) { - var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; - this._managePreventDefault(keyName, $e); - if (keyName && this._shouldTrigger(keyName, $e)) { - this.trigger(keyName + "Keyed", $e); - } - }, - _onInput: function onInput() { - this._setQuery(this.getInputValue()); - this.clearHintIfInvalid(); - this._checkLanguageDirection(); - }, - _managePreventDefault: function managePreventDefault(keyName, $e) { - var preventDefault; - switch (keyName) { - case "up": - case "down": - preventDefault = !withModifier($e); - break; - - default: - preventDefault = false; - } - preventDefault && $e.preventDefault(); - }, - _shouldTrigger: function shouldTrigger(keyName, $e) { - var trigger; - switch (keyName) { - case "tab": - trigger = !withModifier($e); - break; - - default: - trigger = true; - } - return trigger; - }, - _checkLanguageDirection: function checkLanguageDirection() { - var dir = (this.$input.css("direction") || "ltr").toLowerCase(); - if (this.dir !== dir) { - this.dir = dir; - this.$hint.attr("dir", dir); - this.trigger("langDirChanged", dir); - } - }, - _setQuery: function setQuery(val, silent) { - var areEquivalent, hasDifferentWhitespace; - areEquivalent = areQueriesEquivalent(val, this.query); - hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false; - this.query = val; - if (!silent && !areEquivalent) { - this.trigger("queryChanged", this.query); - } else if (!silent && hasDifferentWhitespace) { - this.trigger("whitespaceChanged", this.query); - } - }, - _updateDescendent: function updateDescendent(event, id) { - this.$input.attr("aria-activedescendant", id); - }, - bind: function() { - var that = this, onBlur, onFocus, onKeydown, onInput; - onBlur = _.bind(this._onBlur, this); - onFocus = _.bind(this._onFocus, this); - onKeydown = _.bind(this._onKeydown, this); - onInput = _.bind(this._onInput, this); - this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); - if (!_.isMsie() || _.isMsie() > 9) { - this.$input.on("input.tt", onInput); - } else { - this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) { - if (specialKeyCodeMap[$e.which || $e.keyCode]) { - return; - } - _.defer(_.bind(that._onInput, that, $e)); - }); - } - return this; - }, - focus: function focus() { - this.$input.focus(); - }, - blur: function blur() { - this.$input.blur(); - }, - getLangDir: function getLangDir() { - return this.dir; - }, - getQuery: function getQuery() { - return this.query || ""; - }, - setQuery: function setQuery(val, silent) { - this.setInputValue(val); - this._setQuery(val, silent); - }, - hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() { - return this.query !== this.queryWhenFocused; - }, - getInputValue: function getInputValue() { - return this.$input.val(); - }, - setInputValue: function setInputValue(value) { - this.$input.val(value); - this.clearHintIfInvalid(); - this._checkLanguageDirection(); - }, - resetInputValue: function resetInputValue() { - this.setInputValue(this.query); - }, - getHint: function getHint() { - return this.$hint.val(); - }, - setHint: function setHint(value) { - this.$hint.val(value); - }, - clearHint: function clearHint() { - this.setHint(""); - }, - clearHintIfInvalid: function clearHintIfInvalid() { - var val, hint, valIsPrefixOfHint, isValid; - val = this.getInputValue(); - hint = this.getHint(); - valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; - isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow(); - !isValid && this.clearHint(); - }, - hasFocus: function hasFocus() { - return this.$input.is(":focus"); - }, - hasOverflow: function hasOverflow() { - var constraint = this.$input.width() - 2; - this.$overflowHelper.text(this.getInputValue()); - return this.$overflowHelper.width() >= constraint; - }, - isCursorAtEnd: function() { - var valueLength, selectionStart, range; - valueLength = this.$input.val().length; - selectionStart = this.$input[0].selectionStart; - if (_.isNumber(selectionStart)) { - return selectionStart === valueLength; - } else if (document.selection) { - range = document.selection.createRange(); - range.moveStart("character", -valueLength); - return valueLength === range.text.length; - } - return true; - }, - destroy: function destroy() { - this.$hint.off(".tt"); - this.$input.off(".tt"); - this.$overflowHelper.remove(); - this.$hint = this.$input = this.$overflowHelper = $("
"); - } - }); - return Input; - function buildOverflowHelper($input) { - return $('').css({ - position: "absolute", - visibility: "hidden", - whiteSpace: "pre", - fontFamily: $input.css("font-family"), - fontSize: $input.css("font-size"), - fontStyle: $input.css("font-style"), - fontVariant: $input.css("font-variant"), - fontWeight: $input.css("font-weight"), - wordSpacing: $input.css("word-spacing"), - letterSpacing: $input.css("letter-spacing"), - textIndent: $input.css("text-indent"), - textRendering: $input.css("text-rendering"), - textTransform: $input.css("text-transform") - }).insertAfter($input); - } - function areQueriesEquivalent(a, b) { - return Input.normalizeQuery(a) === Input.normalizeQuery(b); - } - function withModifier($e) { - return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; - } - }(); - var Dataset = function() { - "use strict"; - var keys, nameGenerator; - keys = { - dataset: "tt-selectable-dataset", - val: "tt-selectable-display", - obj: "tt-selectable-object" - }; - nameGenerator = _.getIdGenerator(); - function Dataset(o, www) { - o = o || {}; - o.templates = o.templates || {}; - o.templates.notFound = o.templates.notFound || o.templates.empty; - if (!o.source) { - $.error("missing source"); - } - if (!o.node) { - $.error("missing node"); - } - if (o.name && !isValidName(o.name)) { - $.error("invalid dataset name: " + o.name); - } - www.mixin(this); - this.highlight = !!o.highlight; - this.name = _.toStr(o.name || nameGenerator()); - this.limit = o.limit || 5; - this.displayFn = getDisplayFn(o.display || o.displayKey); - this.templates = getTemplates(o.templates, this.displayFn); - this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source; - this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async; - this._resetLastSuggestion(); - this.$el = $(o.node).attr("role", "presentation").addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name); - } - Dataset.extractData = function extractData(el) { - var $el = $(el); - if ($el.data(keys.obj)) { - return { - dataset: $el.data(keys.dataset) || "", - val: $el.data(keys.val) || "", - obj: $el.data(keys.obj) || null - }; - } - return null; - }; - _.mixin(Dataset.prototype, EventEmitter, { - _overwrite: function overwrite(query, suggestions) { - suggestions = suggestions || []; - if (suggestions.length) { - this._renderSuggestions(query, suggestions); - } else if (this.async && this.templates.pending) { - this._renderPending(query); - } else if (!this.async && this.templates.notFound) { - this._renderNotFound(query); - } else { - this._empty(); - } - this.trigger("rendered", suggestions, false, this.name); - }, - _append: function append(query, suggestions) { - suggestions = suggestions || []; - if (suggestions.length && this.$lastSuggestion.length) { - this._appendSuggestions(query, suggestions); - } else if (suggestions.length) { - this._renderSuggestions(query, suggestions); - } else if (!this.$lastSuggestion.length && this.templates.notFound) { - this._renderNotFound(query); - } - this.trigger("rendered", suggestions, true, this.name); - }, - _renderSuggestions: function renderSuggestions(query, suggestions) { - var $fragment; - $fragment = this._getSuggestionsFragment(query, suggestions); - this.$lastSuggestion = $fragment.children().last(); - this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions)); - }, - _appendSuggestions: function appendSuggestions(query, suggestions) { - var $fragment, $lastSuggestion; - $fragment = this._getSuggestionsFragment(query, suggestions); - $lastSuggestion = $fragment.children().last(); - this.$lastSuggestion.after($fragment); - this.$lastSuggestion = $lastSuggestion; - }, - _renderPending: function renderPending(query) { - var template = this.templates.pending; - this._resetLastSuggestion(); - template && this.$el.html(template({ - query: query, - dataset: this.name - })); - }, - _renderNotFound: function renderNotFound(query) { - var template = this.templates.notFound; - this._resetLastSuggestion(); - template && this.$el.html(template({ - query: query, - dataset: this.name - })); - }, - _empty: function empty() { - this.$el.empty(); - this._resetLastSuggestion(); - }, - _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) { - var that = this, fragment; - fragment = document.createDocumentFragment(); - _.each(suggestions, function getSuggestionNode(suggestion) { - var $el, context; - context = that._injectQuery(query, suggestion); - $el = $(that.templates.suggestion(context)).data(keys.dataset, that.name).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable); - fragment.appendChild($el[0]); - }); - this.highlight && highlight({ - className: this.classes.highlight, - node: fragment, - pattern: query - }); - return $(fragment); - }, - _getFooter: function getFooter(query, suggestions) { - return this.templates.footer ? this.templates.footer({ - query: query, - suggestions: suggestions, - dataset: this.name - }) : null; - }, - _getHeader: function getHeader(query, suggestions) { - return this.templates.header ? this.templates.header({ - query: query, - suggestions: suggestions, - dataset: this.name - }) : null; - }, - _resetLastSuggestion: function resetLastSuggestion() { - this.$lastSuggestion = $(); - }, - _injectQuery: function injectQuery(query, obj) { - return _.isObject(obj) ? _.mixin({ - _query: query - }, obj) : obj; - }, - update: function update(query) { - var that = this, canceled = false, syncCalled = false, rendered = 0; - this.cancel(); - this.cancel = function cancel() { - canceled = true; - that.cancel = $.noop; - that.async && that.trigger("asyncCanceled", query, that.name); - }; - this.source(query, sync, async); - !syncCalled && sync([]); - function sync(suggestions) { - if (syncCalled) { - return; - } - syncCalled = true; - suggestions = (suggestions || []).slice(0, that.limit); - rendered = suggestions.length; - that._overwrite(query, suggestions); - if (rendered < that.limit && that.async) { - that.trigger("asyncRequested", query, that.name); - } - } - function async(suggestions) { - suggestions = suggestions || []; - if (!canceled && rendered < that.limit) { - that.cancel = $.noop; - var idx = Math.abs(rendered - that.limit); - rendered += idx; - that._append(query, suggestions.slice(0, idx)); - that.async && that.trigger("asyncReceived", query, that.name); - } - } - }, - cancel: $.noop, - clear: function clear() { - this._empty(); - this.cancel(); - this.trigger("cleared"); - }, - isEmpty: function isEmpty() { - return this.$el.is(":empty"); - }, - destroy: function destroy() { - this.$el = $("
"); - } - }); - return Dataset; - function getDisplayFn(display) { - display = display || _.stringify; - return _.isFunction(display) ? display : displayFn; - function displayFn(obj) { - return obj[display]; - } - } - function getTemplates(templates, displayFn) { - return { - notFound: templates.notFound && _.templatify(templates.notFound), - pending: templates.pending && _.templatify(templates.pending), - header: templates.header && _.templatify(templates.header), - footer: templates.footer && _.templatify(templates.footer), - suggestion: templates.suggestion || suggestionTemplate - }; - function suggestionTemplate(context) { - return $('
').attr("id", _.guid()).text(displayFn(context)); - } - } - function isValidName(str) { - return /^[_a-zA-Z0-9-]+$/.test(str); - } - }(); - var Menu = function() { - "use strict"; - function Menu(o, www) { - var that = this; - o = o || {}; - if (!o.node) { - $.error("node is required"); - } - www.mixin(this); - this.$node = $(o.node); - this.query = null; - this.datasets = _.map(o.datasets, initializeDataset); - function initializeDataset(oDataset) { - var node = that.$node.find(oDataset.node).first(); - oDataset.node = node.length ? node : $("
").appendTo(that.$node); - return new Dataset(oDataset, www); - } - } - _.mixin(Menu.prototype, EventEmitter, { - _onSelectableClick: function onSelectableClick($e) { - this.trigger("selectableClicked", $($e.currentTarget)); - }, - _onRendered: function onRendered(type, dataset, suggestions, async) { - this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); - this.trigger("datasetRendered", dataset, suggestions, async); - }, - _onCleared: function onCleared() { - this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty()); - this.trigger("datasetCleared"); - }, - _propagate: function propagate() { - this.trigger.apply(this, arguments); - }, - _allDatasetsEmpty: function allDatasetsEmpty() { - return _.every(this.datasets, _.bind(function isDatasetEmpty(dataset) { - var isEmpty = dataset.isEmpty(); - this.$node.attr("aria-expanded", !isEmpty); - return isEmpty; - }, this)); - }, - _getSelectables: function getSelectables() { - return this.$node.find(this.selectors.selectable); - }, - _removeCursor: function _removeCursor() { - var $selectable = this.getActiveSelectable(); - $selectable && $selectable.removeClass(this.classes.cursor); - }, - _ensureVisible: function ensureVisible($el) { - var elTop, elBottom, nodeScrollTop, nodeHeight; - elTop = $el.position().top; - elBottom = elTop + $el.outerHeight(true); - nodeScrollTop = this.$node.scrollTop(); - nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10); - if (elTop < 0) { - this.$node.scrollTop(nodeScrollTop + elTop); - } else if (nodeHeight < elBottom) { - this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight)); - } - }, - bind: function() { - var that = this, onSelectableClick; - onSelectableClick = _.bind(this._onSelectableClick, this); - this.$node.on("click.tt", this.selectors.selectable, onSelectableClick); - this.$node.on("mouseover", this.selectors.selectable, function() { - that.setCursor($(this)); - }); - this.$node.on("mouseleave", function() { - that._removeCursor(); - }); - _.each(this.datasets, function(dataset) { - dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that); - }); - return this; - }, - isOpen: function isOpen() { - return this.$node.hasClass(this.classes.open); - }, - open: function open() { - this.$node.scrollTop(0); - this.$node.addClass(this.classes.open); - }, - close: function close() { - this.$node.attr("aria-expanded", false); - this.$node.removeClass(this.classes.open); - this._removeCursor(); - }, - setLanguageDirection: function setLanguageDirection(dir) { - this.$node.attr("dir", dir); - }, - selectableRelativeToCursor: function selectableRelativeToCursor(delta) { - var $selectables, $oldCursor, oldIndex, newIndex; - $oldCursor = this.getActiveSelectable(); - $selectables = this._getSelectables(); - oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1; - newIndex = oldIndex + delta; - newIndex = (newIndex + 1) % ($selectables.length + 1) - 1; - newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex; - return newIndex === -1 ? null : $selectables.eq(newIndex); - }, - setCursor: function setCursor($selectable) { - this._removeCursor(); - if ($selectable = $selectable && $selectable.first()) { - $selectable.addClass(this.classes.cursor); - this._ensureVisible($selectable); - } - }, - getSelectableData: function getSelectableData($el) { - return $el && $el.length ? Dataset.extractData($el) : null; - }, - getActiveSelectable: function getActiveSelectable() { - var $selectable = this._getSelectables().filter(this.selectors.cursor).first(); - return $selectable.length ? $selectable : null; - }, - getTopSelectable: function getTopSelectable() { - var $selectable = this._getSelectables().first(); - return $selectable.length ? $selectable : null; - }, - update: function update(query) { - var isValidUpdate = query !== this.query; - if (isValidUpdate) { - this.query = query; - _.each(this.datasets, updateDataset); - } - return isValidUpdate; - function updateDataset(dataset) { - dataset.update(query); - } - }, - empty: function empty() { - _.each(this.datasets, clearDataset); - this.query = null; - this.$node.addClass(this.classes.empty); - function clearDataset(dataset) { - dataset.clear(); - } - }, - destroy: function destroy() { - this.$node.off(".tt"); - this.$node = $("
"); - _.each(this.datasets, destroyDataset); - function destroyDataset(dataset) { - dataset.destroy(); - } - } - }); - return Menu; - }(); - var Status = function() { - "use strict"; - function Status(options) { - this.$el = $("", { - role: "status", - "aria-live": "polite" - }).css({ - position: "absolute", - padding: "0", - border: "0", - height: "1px", - width: "1px", - "margin-bottom": "-1px", - "margin-right": "-1px", - overflow: "hidden", - clip: "rect(0 0 0 0)", - "white-space": "nowrap" - }); - options.$input.after(this.$el); - _.each(options.menu.datasets, _.bind(function(dataset) { - if (dataset.onSync) { - dataset.onSync("rendered", _.bind(this.update, this)); - dataset.onSync("cleared", _.bind(this.cleared, this)); - } - }, this)); - } - _.mixin(Status.prototype, { - update: function update(event, suggestions) { - var length = suggestions.length; - var words; - if (length === 1) { - words = { - result: "result", - is: "is" - }; - } else { - words = { - result: "results", - is: "are" - }; - } - this.$el.text(length + " " + words.result + " " + words.is + " available, use up and down arrow keys to navigate."); - }, - cleared: function() { - this.$el.text(""); - } - }); - return Status; - }(); - var DefaultMenu = function() { - "use strict"; - var s = Menu.prototype; - function DefaultMenu() { - Menu.apply(this, [].slice.call(arguments, 0)); - } - _.mixin(DefaultMenu.prototype, Menu.prototype, { - open: function open() { - !this._allDatasetsEmpty() && this._show(); - return s.open.apply(this, [].slice.call(arguments, 0)); - }, - close: function close() { - this._hide(); - return s.close.apply(this, [].slice.call(arguments, 0)); - }, - _onRendered: function onRendered() { - if (this._allDatasetsEmpty()) { - this._hide(); - } else { - this.isOpen() && this._show(); - } - return s._onRendered.apply(this, [].slice.call(arguments, 0)); - }, - _onCleared: function onCleared() { - if (this._allDatasetsEmpty()) { - this._hide(); - } else { - this.isOpen() && this._show(); - } - return s._onCleared.apply(this, [].slice.call(arguments, 0)); - }, - setLanguageDirection: function setLanguageDirection(dir) { - this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl); - return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0)); - }, - _hide: function hide() { - this.$node.hide(); - }, - _show: function show() { - this.$node.css("display", "block"); - } - }); - return DefaultMenu; - }(); - var Typeahead = function() { - "use strict"; - function Typeahead(o, www) { - var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged; - o = o || {}; - if (!o.input) { - $.error("missing input"); - } - if (!o.menu) { - $.error("missing menu"); - } - if (!o.eventBus) { - $.error("missing event bus"); - } - www.mixin(this); - this.eventBus = o.eventBus; - this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; - this.input = o.input; - this.menu = o.menu; - this.enabled = true; - this.autoselect = !!o.autoselect; - this.active = false; - this.input.hasFocus() && this.activate(); - this.dir = this.input.getLangDir(); - this._hacks(); - this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this); - onFocused = c(this, "activate", "open", "_onFocused"); - onBlurred = c(this, "deactivate", "_onBlurred"); - onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed"); - onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed"); - onEscKeyed = c(this, "isActive", "_onEscKeyed"); - onUpKeyed = c(this, "isActive", "open", "_onUpKeyed"); - onDownKeyed = c(this, "isActive", "open", "_onDownKeyed"); - onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed"); - onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed"); - onQueryChanged = c(this, "_openIfActive", "_onQueryChanged"); - onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged"); - this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this); - } - _.mixin(Typeahead.prototype, { - _hacks: function hacks() { - var $input, $menu; - $input = this.input.$input || $("
"); - $menu = this.menu.$node || $("
"); - $input.on("blur.tt", function($e) { - var active, isActive, hasActive; - active = document.activeElement; - isActive = $menu.is(active); - hasActive = $menu.has(active).length > 0; - if (_.isMsie() && (isActive || hasActive)) { - $e.preventDefault(); - $e.stopImmediatePropagation(); - _.defer(function() { - $input.focus(); - }); - } - }); - $menu.on("mousedown.tt", function($e) { - $e.preventDefault(); - }); - }, - _onSelectableClicked: function onSelectableClicked(type, $el) { - this.select($el); - }, - _onDatasetCleared: function onDatasetCleared() { - this._updateHint(); - }, - _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) { - this._updateHint(); - if (this.autoselect) { - var cursorClass = this.selectors.cursor.substr(1); - this.menu.$node.find(this.selectors.suggestion).first().addClass(cursorClass); - } - this.eventBus.trigger("render", suggestions, async, dataset); - }, - _onAsyncRequested: function onAsyncRequested(type, dataset, query) { - this.eventBus.trigger("asyncrequest", query, dataset); - }, - _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) { - this.eventBus.trigger("asynccancel", query, dataset); - }, - _onAsyncReceived: function onAsyncReceived(type, dataset, query) { - this.eventBus.trigger("asyncreceive", query, dataset); - }, - _onFocused: function onFocused() { - this._minLengthMet() && this.menu.update(this.input.getQuery()); - }, - _onBlurred: function onBlurred() { - if (this.input.hasQueryChangedSinceLastFocus()) { - this.eventBus.trigger("change", this.input.getQuery()); - } - }, - _onEnterKeyed: function onEnterKeyed(type, $e) { - var $selectable; - if ($selectable = this.menu.getActiveSelectable()) { - if (this.select($selectable)) { - $e.preventDefault(); - $e.stopPropagation(); - } - } else if (this.autoselect) { - if (this.select(this.menu.getTopSelectable())) { - $e.preventDefault(); - $e.stopPropagation(); - } - } - }, - _onTabKeyed: function onTabKeyed(type, $e) { - var $selectable; - if ($selectable = this.menu.getActiveSelectable()) { - this.select($selectable) && $e.preventDefault(); - } else if ($selectable = this.menu.getTopSelectable()) { - this.autocomplete($selectable) && $e.preventDefault(); - } - }, - _onEscKeyed: function onEscKeyed() { - this.close(); - }, - _onUpKeyed: function onUpKeyed() { - this.moveCursor(-1); - }, - _onDownKeyed: function onDownKeyed() { - this.moveCursor(+1); - }, - _onLeftKeyed: function onLeftKeyed() { - if (this.dir === "rtl" && this.input.isCursorAtEnd()) { - this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); - } - }, - _onRightKeyed: function onRightKeyed() { - if (this.dir === "ltr" && this.input.isCursorAtEnd()) { - this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable()); - } - }, - _onQueryChanged: function onQueryChanged(e, query) { - this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty(); - }, - _onWhitespaceChanged: function onWhitespaceChanged() { - this._updateHint(); - }, - _onLangDirChanged: function onLangDirChanged(e, dir) { - if (this.dir !== dir) { - this.dir = dir; - this.menu.setLanguageDirection(dir); - } - }, - _openIfActive: function openIfActive() { - this.isActive() && this.open(); - }, - _minLengthMet: function minLengthMet(query) { - query = _.isString(query) ? query : this.input.getQuery() || ""; - return query.length >= this.minLength; - }, - _updateHint: function updateHint() { - var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match; - $selectable = this.menu.getTopSelectable(); - data = this.menu.getSelectableData($selectable); - val = this.input.getInputValue(); - if (data && !_.isBlankString(val) && !this.input.hasOverflow()) { - query = Input.normalizeQuery(val); - escapedQuery = _.escapeRegExChars(query); - frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i"); - match = frontMatchRegEx.exec(data.val); - match && this.input.setHint(val + match[1]); - } else { - this.input.clearHint(); - } - }, - isEnabled: function isEnabled() { - return this.enabled; - }, - enable: function enable() { - this.enabled = true; - }, - disable: function disable() { - this.enabled = false; - }, - isActive: function isActive() { - return this.active; - }, - activate: function activate() { - if (this.isActive()) { - return true; - } else if (!this.isEnabled() || this.eventBus.before("active")) { - return false; - } else { - this.active = true; - this.eventBus.trigger("active"); - return true; - } - }, - deactivate: function deactivate() { - if (!this.isActive()) { - return true; - } else if (this.eventBus.before("idle")) { - return false; - } else { - this.active = false; - this.close(); - this.eventBus.trigger("idle"); - return true; - } - }, - isOpen: function isOpen() { - return this.menu.isOpen(); - }, - open: function open() { - if (!this.isOpen() && !this.eventBus.before("open")) { - this.menu.open(); - this._updateHint(); - this.eventBus.trigger("open"); - } - return this.isOpen(); - }, - close: function close() { - if (this.isOpen() && !this.eventBus.before("close")) { - this.menu.close(); - this.input.clearHint(); - this.input.resetInputValue(); - this.eventBus.trigger("close"); - } - return !this.isOpen(); - }, - setVal: function setVal(val) { - this.input.setQuery(_.toStr(val)); - }, - getVal: function getVal() { - return this.input.getQuery(); - }, - select: function select($selectable) { - var data = this.menu.getSelectableData($selectable); - if (data && !this.eventBus.before("select", data.obj, data.dataset)) { - this.input.setQuery(data.val, true); - this.eventBus.trigger("select", data.obj, data.dataset); - this.close(); - return true; - } - return false; - }, - autocomplete: function autocomplete($selectable) { - var query, data, isValid; - query = this.input.getQuery(); - data = this.menu.getSelectableData($selectable); - isValid = data && query !== data.val; - if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) { - this.input.setQuery(data.val); - this.eventBus.trigger("autocomplete", data.obj, data.dataset); - return true; - } - return false; - }, - moveCursor: function moveCursor(delta) { - var query, $candidate, data, suggestion, datasetName, cancelMove, id; - query = this.input.getQuery(); - $candidate = this.menu.selectableRelativeToCursor(delta); - data = this.menu.getSelectableData($candidate); - suggestion = data ? data.obj : null; - datasetName = data ? data.dataset : null; - id = $candidate ? $candidate.attr("id") : null; - this.input.trigger("cursorchange", id); - cancelMove = this._minLengthMet() && this.menu.update(query); - if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) { - this.menu.setCursor($candidate); - if (data) { - this.input.setInputValue(data.val); - } else { - this.input.resetInputValue(); - this._updateHint(); - } - this.eventBus.trigger("cursorchange", suggestion, datasetName); - return true; - } - return false; - }, - destroy: function destroy() { - this.input.destroy(); - this.menu.destroy(); - } - }); - return Typeahead; - function c(ctx) { - var methods = [].slice.call(arguments, 1); - return function() { - var args = [].slice.call(arguments); - _.each(methods, function(method) { - return ctx[method].apply(ctx, args); - }); - }; - } - }(); - (function() { - "use strict"; - var old, keys, methods; - old = $.fn.typeahead; - keys = { - www: "tt-www", - attrs: "tt-attrs", - typeahead: "tt-typeahead" - }; - methods = { - initialize: function initialize(o, datasets) { - var www; - datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1); - o = o || {}; - www = WWW(o.classNames); - return this.each(attach); - function attach() { - var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, status, typeahead, MenuConstructor; - _.each(datasets, function(d) { - d.highlight = !!o.highlight; - }); - $input = $(this); - $wrapper = $(www.html.wrapper); - $hint = $elOrNull(o.hint); - $menu = $elOrNull(o.menu); - defaultHint = o.hint !== false && !$hint; - defaultMenu = o.menu !== false && !$menu; - defaultHint && ($hint = buildHintFromInput($input, www)); - defaultMenu && ($menu = $(www.html.menu).css(www.css.menu)); - $hint && $hint.val(""); - $input = prepInput($input, www); - if (defaultHint || defaultMenu) { - $wrapper.css(www.css.wrapper); - $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint); - $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null); - } - MenuConstructor = defaultMenu ? DefaultMenu : Menu; - eventBus = new EventBus({ - el: $input - }); - input = new Input({ - hint: $hint, - input: $input - }, www); - menu = new MenuConstructor({ - node: $menu, - datasets: datasets - }, www); - status = new Status({ - $input: $input, - menu: menu - }); - typeahead = new Typeahead({ - input: input, - menu: menu, - eventBus: eventBus, - minLength: o.minLength, - autoselect: o.autoselect - }, www); - $input.data(keys.www, www); - $input.data(keys.typeahead, typeahead); - } - }, - isEnabled: function isEnabled() { - var enabled; - ttEach(this.first(), function(t) { - enabled = t.isEnabled(); - }); - return enabled; - }, - enable: function enable() { - ttEach(this, function(t) { - t.enable(); - }); - return this; - }, - disable: function disable() { - ttEach(this, function(t) { - t.disable(); - }); - return this; - }, - isActive: function isActive() { - var active; - ttEach(this.first(), function(t) { - active = t.isActive(); - }); - return active; - }, - activate: function activate() { - ttEach(this, function(t) { - t.activate(); - }); - return this; - }, - deactivate: function deactivate() { - ttEach(this, function(t) { - t.deactivate(); - }); - return this; - }, - isOpen: function isOpen() { - var open; - ttEach(this.first(), function(t) { - open = t.isOpen(); - }); - return open; - }, - open: function open() { - ttEach(this, function(t) { - t.open(); - }); - return this; - }, - close: function close() { - ttEach(this, function(t) { - t.close(); - }); - return this; - }, - select: function select(el) { - var success = false, $el = $(el); - ttEach(this.first(), function(t) { - success = t.select($el); - }); - return success; - }, - autocomplete: function autocomplete(el) { - var success = false, $el = $(el); - ttEach(this.first(), function(t) { - success = t.autocomplete($el); - }); - return success; - }, - moveCursor: function moveCursoe(delta) { - var success = false; - ttEach(this.first(), function(t) { - success = t.moveCursor(delta); - }); - return success; - }, - val: function val(newVal) { - var query; - if (!arguments.length) { - ttEach(this.first(), function(t) { - query = t.getVal(); - }); - return query; - } else { - ttEach(this, function(t) { - t.setVal(_.toStr(newVal)); - }); - return this; - } - }, - destroy: function destroy() { - ttEach(this, function(typeahead, $input) { - revert($input); - typeahead.destroy(); - }); - return this; - } - }; - $.fn.typeahead = function(method) { - if (methods[method]) { - return methods[method].apply(this, [].slice.call(arguments, 1)); - } else { - return methods.initialize.apply(this, arguments); - } - }; - $.fn.typeahead.noConflict = function noConflict() { - $.fn.typeahead = old; - return this; - }; - function ttEach($els, fn) { - $els.each(function() { - var $input = $(this), typeahead; - (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input); - }); - } - function buildHintFromInput($input, www) { - return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop({ - readonly: true, - required: false - }).removeAttr("id name placeholder").removeClass("required").attr({ - spellcheck: "false", - tabindex: -1 - }); - } - function prepInput($input, www) { - $input.data(keys.attrs, { - dir: $input.attr("dir"), - autocomplete: $input.attr("autocomplete"), - spellcheck: $input.attr("spellcheck"), - style: $input.attr("style") - }); - $input.addClass(www.classes.input).attr({ - spellcheck: false - }); - try { - !$input.attr("dir") && $input.attr("dir", "auto"); - } catch (e) {} - return $input; - } - function getBackgroundStyles($el) { - return { - backgroundAttachment: $el.css("background-attachment"), - backgroundClip: $el.css("background-clip"), - backgroundColor: $el.css("background-color"), - backgroundImage: $el.css("background-image"), - backgroundOrigin: $el.css("background-origin"), - backgroundPosition: $el.css("background-position"), - backgroundRepeat: $el.css("background-repeat"), - backgroundSize: $el.css("background-size") - }; - } - function revert($input) { - var www, $wrapper; - www = $input.data(keys.www); - $wrapper = $input.parent().filter(www.selectors.wrapper); - _.each($input.data(keys.attrs), function(val, key) { - _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); - }); - $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input); - if ($wrapper.length) { - $input.detach().insertAfter($wrapper); - $wrapper.remove(); - } - } - function $elOrNull(obj) { - var isValid, $el; - isValid = _.isJQuery(obj) || _.isElement(obj); - $el = isValid ? $(obj).first() : []; - return $el.length ? $el : null; - } - })(); -}); \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/search.json b/Lesson12/Carthage/Checkouts/Alamofire/docs/search.json deleted file mode 100644 index b2282cd..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/search.json +++ /dev/null @@ -1 +0,0 @@ -{"Typealiases.html#/s:9Alamofire10Parametersa":{"name":"Parameters","abstract":"

A dictionary of parameters to apply to a URLRequest.

"},"Typealiases.html#/s:9Alamofire12AdaptHandlera":{"name":"AdaptHandler","abstract":"

RequestAdapter closure definition.

"},"Typealiases.html#/s:9Alamofire12RetryHandlera":{"name":"RetryHandler","abstract":"

RequestRetrier closure definition.

"},"Typealiases.html#/s:9Alamofire14AFDataResponsea":{"name":"AFDataResponse","abstract":"

Default type of DataResponse returned by Alamofire, with an AFError Failure type.

"},"Typealiases.html#/s:9Alamofire18AFDownloadResponsea":{"name":"AFDownloadResponse","abstract":"

Default type of DownloadResponse returned by Alamofire, with an AFError Failure type.

"},"Typealiases.html#/s:9Alamofire8AFResulta":{"name":"AFResult","abstract":"

Default type of Result returned by Alamofire, with an AFError Failure type.

"},"Structs/Empty.html#/s:9Alamofire5EmptyV5valueACvpZ":{"name":"value","abstract":"

Static Empty instance used for all Empty responses.

","parent_name":"Empty"},"Structs/Empty.html#/s:9Alamofire13EmptyResponseP10emptyValuexyFZ":{"name":"emptyValue()","parent_name":"Empty"},"Structs/GoogleXSSIPreprocessor.html#/s:9Alamofire22GoogleXSSIPreprocessorVACycfc":{"name":"init()","abstract":"

Undocumented

","parent_name":"GoogleXSSIPreprocessor"},"Structs/GoogleXSSIPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","parent_name":"GoogleXSSIPreprocessor"},"Structs/PassthroughPreprocessor.html#/s:9Alamofire23PassthroughPreprocessorVACycfc":{"name":"init()","abstract":"

Undocumented

","parent_name":"PassthroughPreprocessor"},"Structs/PassthroughPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","parent_name":"PassthroughPreprocessor"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

The URL request sent to the server.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

The server’s response to the URL request.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7fileURL10Foundation0E0VSgvp":{"name":"fileURL","abstract":"

The final destination URL of the data returned from the server after it is moved.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV10resumeData10Foundation0E0VSgvp":{"name":"resumeData","abstract":"

The resume data generated if the request was cancelled.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

The final metrics of the response.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV21serializationDurationSdvp":{"name":"serializationDuration","abstract":"

The time taken to serialize the response.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV6results6ResultOyxq_Gvp":{"name":"result","abstract":"

The result of response serialization.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV5valuexSgvp":{"name":"value","abstract":"

Returns the associated value of the result if it is a success, nil otherwise.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV5errorq_Sgvp":{"name":"error","abstract":"

Returns the associated error value if the result if it is a failure, nil otherwise.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV7request8response7fileURL10resumeData7metrics21serializationDuration6resultACyxq_G10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAL0G0VSgAL0I0VSgSo23NSURLSessionTaskMetricsCSgSds6ResultOyxq_Gtcfc":{"name":"init(request:response:fileURL:resumeData:metrics:serializationDuration:result:)","abstract":"

Creates a DownloadResponse instance with the specified parameters derived from response serialization.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV11descriptionSSvp":{"name":"description","abstract":"

The textual representation used when written to an output stream, which includes whether the result was a","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV16debugDescriptionSSvp":{"name":"debugDescription","abstract":"

The debug textual representation used when written to an output stream, which includes the URL request, the URL","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV3mapyACyqd__q_Gqd__xXElF":{"name":"map(_:)","abstract":"

Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV6tryMapyACyqd__s5Error_pGqd__xKXElF":{"name":"tryMap(_:)","abstract":"

Evaluates the given closure when the result of this DownloadResponse is a success, passing the unwrapped","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV8mapErroryACyxqd__Gqd__q_XEs0E0Rd__lF":{"name":"mapError(_:)","abstract":"

Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DownloadResponse"},"Structs/DownloadResponse.html#/s:9Alamofire16DownloadResponseV11tryMapErroryACyxs0F0_pGqd__q_KXEsAERd__lF":{"name":"tryMapError(_:)","abstract":"

Evaluates the specified closure when the DownloadResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DownloadResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

The URL request sent to the server.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

The server’s response to the URL request.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV4data10Foundation0B0VSgvp":{"name":"data","abstract":"

The data returned by the server.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

The final metrics of the response.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV21serializationDurationSdvp":{"name":"serializationDuration","abstract":"

The time taken to serialize the response.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV6results6ResultOyxq_Gvp":{"name":"result","abstract":"

The result of response serialization.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV5valuexSgvp":{"name":"value","abstract":"

Returns the associated value of the result if it is a success, nil otherwise.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV5errorq_Sgvp":{"name":"error","abstract":"

Returns the associated error value if the result if it is a failure, nil otherwise.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV7request8response4data7metrics21serializationDuration6resultACyxq_G10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgSo23NSURLSessionTaskMetricsCSgSds6ResultOyxq_Gtcfc":{"name":"init(request:response:data:metrics:serializationDuration:result:)","abstract":"

Creates a DataResponse instance with the specified parameters derived from the response serialization.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV11descriptionSSvp":{"name":"description","abstract":"

The textual representation used when written to an output stream, which includes whether the result was a","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV16debugDescriptionSSvp":{"name":"debugDescription","abstract":"

The debug textual representation used when written to an output stream, which includes the URL request, the URL","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV3mapyACyqd__q_Gqd__xXElF":{"name":"map(_:)","abstract":"

Evaluates the specified closure when the result of this DataResponse is a success, passing the unwrapped","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV6tryMapyACyqd__s5Error_pGqd__xKXElF":{"name":"tryMap(_:)","abstract":"

Evaluates the given closure when the result of this DataResponse is a success, passing the unwrapped result","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV8mapErroryACyxqd__Gqd__q_XEs0E0Rd__lF":{"name":"mapError(_:)","abstract":"

Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DataResponse"},"Structs/DataResponse.html#/s:9Alamofire12DataResponseV11tryMapErroryACyxs0F0_pGqd__q_KXEsAERd__lF":{"name":"tryMapError(_:)","abstract":"

Evaluates the specified closure when the DataResponse is a failure, passing the unwrapped error as a parameter.

","parent_name":"DataResponse"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO6followyA2EmF":{"name":"follow","abstract":"

Follow the redirect as defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO11doNotFollowyA2EmF":{"name":"doNotFollow","abstract":"

Do not follow the redirect defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html#/s:9Alamofire10RedirectorV8BehaviorO6modifyyAE10Foundation10URLRequestVSgSo16NSURLSessionTaskC_AISo17NSHTTPURLResponseCtccAEmF":{"name":"modify(_:)","abstract":"

Modify the redirect request defined in the response.

","parent_name":"Behavior"},"Structs/Redirector/Behavior.html":{"name":"Behavior","abstract":"

Defines the behavior of the Redirector type.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV6followACvpZ":{"name":"follow","abstract":"

Returns a Redirector with a .follow Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV11doNotFollowACvpZ":{"name":"doNotFollow","abstract":"

Returns a Redirector with a .doNotFollow Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV8behaviorAC8BehaviorOvp":{"name":"behavior","abstract":"

The Behavior of the Redirector.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire10RedirectorV8behaviorA2C8BehaviorO_tcfc":{"name":"init(behavior:)","abstract":"

Creates a Redirector instance from the Behavior.

","parent_name":"Redirector"},"Structs/Redirector.html#/s:9Alamofire15RedirectHandlerP4task_18willBeRedirectedTo3for10completionySo16NSURLSessionTaskC_10Foundation10URLRequestVSo17NSHTTPURLResponseCyALSgctF":{"name":"task(_:willBeRedirectedTo:for:completion:)","parent_name":"Redirector"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7defaultACvpZ":{"name":"default","abstract":"

Returns a JSONEncoding instance with default writing options.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV13prettyPrintedACvpZ":{"name":"prettyPrinted","abstract":"

Returns a JSONEncoding instance with .prettyPrinted writing options.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7optionsSo20NSJSONWritingOptionsVvp":{"name":"options","abstract":"

The options for writing the parameters as JSON data.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV7optionsACSo20NSJSONWritingOptionsV_tcfc":{"name":"init(options:)","abstract":"

Creates an instance using the specified WritingOptions.

","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","parent_name":"JSONEncoding"},"Structs/JSONEncoding.html#/s:9Alamofire12JSONEncodingV6encode_14withJSONObject10Foundation10URLRequestVAA0G11Convertible_p_ypSgtKF":{"name":"encode(_:withJSONObject:)","abstract":"

Encodes any JSON compatible object into a URLRequest.

","parent_name":"JSONEncoding"},"Structs/URLEncoding/BoolEncoding.html#/s:9Alamofire11URLEncodingV12BoolEncodingO7numericyA2EmF":{"name":"numeric","abstract":"

Encode true as 1 and false as 0. This is the default behavior.

","parent_name":"BoolEncoding"},"Structs/URLEncoding/BoolEncoding.html#/s:9Alamofire11URLEncodingV12BoolEncodingO7literalyA2EmF":{"name":"literal","abstract":"

Encode true and false as string literals.

","parent_name":"BoolEncoding"},"Structs/URLEncoding/ArrayEncoding.html#/s:9Alamofire11URLEncodingV13ArrayEncodingO8bracketsyA2EmF":{"name":"brackets","abstract":"

An empty set of square brackets is appended to the key for every value. This is the default behavior.

","parent_name":"ArrayEncoding"},"Structs/URLEncoding/ArrayEncoding.html#/s:9Alamofire11URLEncodingV13ArrayEncodingO10noBracketsyA2EmF":{"name":"noBrackets","abstract":"

No brackets are appended. The key is encoded as is.

","parent_name":"ArrayEncoding"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO15methodDependentyA2EmF":{"name":"methodDependent","abstract":"

Applies encoded query string result to existing query string for GET, HEAD and DELETE requests and","parent_name":"Destination"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO11queryStringyA2EmF":{"name":"queryString","abstract":"

Sets or appends encoded query string result to existing query string.

","parent_name":"Destination"},"Structs/URLEncoding/Destination.html#/s:9Alamofire11URLEncodingV11DestinationO8httpBodyyA2EmF":{"name":"httpBody","abstract":"

Sets encoded query string result as the HTTP body of the URL request.

","parent_name":"Destination"},"Structs/URLEncoding/Destination.html":{"name":"Destination","abstract":"

Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the","parent_name":"URLEncoding"},"Structs/URLEncoding/ArrayEncoding.html":{"name":"ArrayEncoding","abstract":"

Configures how Array parameters are encoded.

","parent_name":"URLEncoding"},"Structs/URLEncoding/BoolEncoding.html":{"name":"BoolEncoding","abstract":"

Configures how Bool parameters are encoded.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV7defaultACvpZ":{"name":"default","abstract":"

Returns a default URLEncoding instance with a .methodDependent destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11queryStringACvpZ":{"name":"queryString","abstract":"

Returns a URLEncoding instance with a .queryString destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV8httpBodyACvpZ":{"name":"httpBody","abstract":"

Returns a URLEncoding instance with an .httpBody destination.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11destinationAC11DestinationOvp":{"name":"destination","abstract":"

The destination defining where the encoded query string is to be applied to the URL request.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV13arrayEncodingAC05ArrayD0Ovp":{"name":"arrayEncoding","abstract":"

The encoding to use for Array parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV12boolEncodingAC04BoolD0Ovp":{"name":"boolEncoding","abstract":"

The encoding to use for Bool parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV11destination13arrayEncoding04boolE0A2C11DestinationO_AC05ArrayE0OAC04BoolE0Otcfc":{"name":"init(destination:arrayEncoding:boolEncoding:)","abstract":"

Creates an instance using the specified parameters.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV15queryComponents7fromKey5valueSaySS_SStGSS_yptF":{"name":"queryComponents(fromKey:value:)","abstract":"

Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.

","parent_name":"URLEncoding"},"Structs/URLEncoding.html#/s:9Alamofire11URLEncodingV6escapeyS2SF":{"name":"escape(_:)","abstract":"

Creates a percent-escaped string following RFC 3986 for a query string key or value.

","parent_name":"URLEncoding"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV7connectACvpZ":{"name":"connect","abstract":"

CONNECT method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV6deleteACvpZ":{"name":"delete","abstract":"

DELETE method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV3getACvpZ":{"name":"get","abstract":"

GET method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV4headACvpZ":{"name":"head","abstract":"

HEAD method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV7optionsACvpZ":{"name":"options","abstract":"

OPTIONS method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV5patchACvpZ":{"name":"patch","abstract":"

PATCH method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV4postACvpZ":{"name":"post","abstract":"

POST method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV3putACvpZ":{"name":"put","abstract":"

PUT method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:9Alamofire10HTTPMethodV5traceACvpZ":{"name":"trace","abstract":"

TRACE method.

","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:SY8rawValue03RawB0Qzvp":{"name":"rawValue","parent_name":"HTTPMethod"},"Structs/HTTPMethod.html#/s:SY8rawValuexSg03RawB0Qz_tcfc":{"name":"init(rawValue:)","parent_name":"HTTPMethod"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV4nameSSvp":{"name":"name","abstract":"

Name of the header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV5valueSSvp":{"name":"value","abstract":"

Value of the header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV4name5valueACSS_SStcfc":{"name":"init(name:value:)","abstract":"

Creates an instance from the given name and value.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV6acceptyACSSFZ":{"name":"accept(_:)","abstract":"

Returns an Accept header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13acceptCharsetyACSSFZ":{"name":"acceptCharset(_:)","abstract":"

Returns an Accept-Charset header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV14acceptLanguageyACSSFZ":{"name":"acceptLanguage(_:)","abstract":"

Returns an Accept-Language header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV14acceptEncodingyACSSFZ":{"name":"acceptEncoding(_:)","abstract":"

Returns an Accept-Encoding header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorization8username8passwordACSS_SStFZ":{"name":"authorization(username:password:)","abstract":"

Returns a Basic Authorization header using the username and password provided.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorization11bearerTokenACSS_tFZ":{"name":"authorization(bearerToken:)","abstract":"

Returns a Bearer Authorization header using the bearerToken provided

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV13authorizationyACSSFZ":{"name":"authorization(_:)","abstract":"

Returns an Authorization header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV18contentDispositionyACSSFZ":{"name":"contentDisposition(_:)","abstract":"

Returns a Content-Disposition header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV11contentTypeyACSSFZ":{"name":"contentType(_:)","abstract":"

Returns a Content-Type header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV9userAgentyACSSFZ":{"name":"userAgent(_:)","abstract":"

Returns a User-Agent header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV21defaultAcceptEncodingACvpZ":{"name":"defaultAcceptEncoding","abstract":"

Returns Alamofire’s default Accept-Encoding header, appropriate for the encodings supported by particular OS","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV21defaultAcceptLanguageACvpZ":{"name":"defaultAcceptLanguage","abstract":"

Returns Alamofire’s default Accept-Language header, generated by querying Locale for the user’s","parent_name":"HTTPHeader"},"Structs/HTTPHeader.html#/s:9Alamofire10HTTPHeaderV16defaultUserAgentACvpZ":{"name":"defaultUserAgent","abstract":"

Returns Alamofire’s default User-Agent header.

","parent_name":"HTTPHeader"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVACycfc":{"name":"init()","abstract":"

Creates an empty instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVyACSayAA10HTTPHeaderVGcfc":{"name":"init(_:)","abstract":"

Creates an instance from an array of HTTPHeaders. Duplicate case-insensitive names are collapsed into the last","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVyACSDyS2SGcfc":{"name":"init(_:)","abstract":"

Creates an instance from a [String: String]. Duplicate case-insensitive names are collapsed into the last name","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV3add4name5valueySS_SStF":{"name":"add(name:value:)","abstract":"

Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV3addyyAA10HTTPHeaderVF":{"name":"add(_:)","abstract":"

Case-insensitively updates or appends the provided HTTPHeader into the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6update4name5valueySS_SStF":{"name":"update(name:value:)","abstract":"

Case-insensitively updates or appends an HTTPHeader into the instance using the provided name and value.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6updateyyAA10HTTPHeaderVF":{"name":"update(_:)","abstract":"

Case-insensitively updates or appends the provided HTTPHeader into the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6remove4nameySS_tF":{"name":"remove(name:)","abstract":"

Case-insensitively removes an HTTPHeader, if it exists, from the instance.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV4sortyyF":{"name":"sort()","abstract":"

Sort the current instance by header name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV6sortedACyF":{"name":"sorted()","abstract":"

Returns an instance sorted by header name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV5value3forSSSgSS_tF":{"name":"value(for:)","abstract":"

Case-insensitively find a header’s value by name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersVySSSgSScip":{"name":"subscript(_:)","abstract":"

Case-insensitively access the header with the given name.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV10dictionarySDyS2SGvp":{"name":"dictionary","abstract":"

The dictionary representation of all headers.

","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s30ExpressibleByDictionaryLiteralP010dictionaryD0x3KeyQz_5ValueQztd_tcfc":{"name":"init(dictionaryLiteral:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s25ExpressibleByArrayLiteralP05arrayD0x0cD7ElementQzd_tcfc":{"name":"init(arrayLiteral:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:ST12makeIterator0B0QzyF":{"name":"makeIterator()","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl10startIndex0B0Qzvp":{"name":"startIndex","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl8endIndex0B0Qzvp":{"name":"endIndex","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sly7ElementQz5IndexQzcip":{"name":"subscript(_:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:Sl5index5after5IndexQzAD_tF":{"name":"index(after:)","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"HTTPHeaders"},"Structs/HTTPHeaders.html#/s:9Alamofire11HTTPHeadersV7defaultACvpZ":{"name":"default","abstract":"

The default set of HTTPHeaders used by Alamofire. Includes Accept-Encoding, Accept-Language, and","parent_name":"HTTPHeaders"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO5cacheyA2EmF":{"name":"cache","abstract":"

Stores the cached response in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO10doNotCacheyA2EmF":{"name":"doNotCache","abstract":"

Prevents the cached response from being stored in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html#/s:9Alamofire14ResponseCacherV8BehaviorO6modifyyAESo19NSCachedURLResponseCSgSo20NSURLSessionDataTaskC_AHtccAEmF":{"name":"modify(_:)","abstract":"

Modifies the cached response before storing it in the cache.

","parent_name":"Behavior"},"Structs/ResponseCacher/Behavior.html":{"name":"Behavior","abstract":"

Defines the behavior of the ResponseCacher type.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV5cacheACvpZ":{"name":"cache","abstract":"

Returns a ResponseCacher with a follow Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV10doNotCacheACvpZ":{"name":"doNotCache","abstract":"

Returns a ResponseCacher with a do not follow Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV8behaviorAC8BehaviorOvp":{"name":"behavior","abstract":"

The Behavior of the ResponseCacher.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire14ResponseCacherV8behaviorA2C8BehaviorO_tcfc":{"name":"init(behavior:)","abstract":"

Creates a ResponseCacher instance from the Behavior.

","parent_name":"ResponseCacher"},"Structs/ResponseCacher.html#/s:9Alamofire21CachedResponseHandlerP8dataTask_09willCacheC010completionySo016NSURLSessionDataF0C_So19NSCachedURLResponseCyAJSgctF":{"name":"dataTask(_:willCacheResponse:completion:)","parent_name":"ResponseCacher"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE12certificatesSaySo17SecCertificateRefaGvp":{"name":"certificates","abstract":"

Returns all valid cer, crt, and der certificates in the bundle.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE10publicKeysSaySo9SecKeyRefaGvp":{"name":"publicKeys","abstract":"

Returns all public keys for the valid certificates in the bundle.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo8NSBundleCRbzlE5paths19forResourcesOfTypesSaySSGAH_tF":{"name":"paths(forResourcesOfTypes:)","abstract":"

Returns all pathnames for the resources identified by the provided file extensions.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8evaluate13afterApplyingySo0c6PolicyE0a_tKF":{"name":"evaluate(afterApplying:)","abstract":"

Evaluates self after applying the SecPolicy value provided.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8validate6policy13errorProducerySo0c6PolicyE0a_s5Error_ps5Int32V_So0cD10ResultTypeVtXEtKF":{"name":"validate(policy:errorProducer:)","abstract":"

Attempts to validate self using the SecPolicy provided and transforming any error produced using the closure passed.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE5apply6policyAESo0c6PolicyE0a_tKF":{"name":"apply(policy:)","abstract":"

Applies a SecPolicy to self, throwing if it fails.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8evaluateyyKF":{"name":"evaluate()","abstract":"

Evaluate self, throwing an Error if evaluation fails.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE8validate13errorProducerys5Error_ps5Int32V_So0cD10ResultTypeVtXE_tKF":{"name":"validate(errorProducer:)","abstract":"

Validate self, passing any failure values through errorProducer.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE21setAnchorCertificatesyySaySo0c11CertificateE0aGKF":{"name":"setAnchorCertificates(_:)","abstract":"

Sets a custom certificate chain on self, allowing full validation of a self-signed certificate and its chain.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE10publicKeysSaySo0c3KeyE0aGvp":{"name":"publicKeys","abstract":"

The public keys contained in self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE12certificatesSaySo0c11CertificateE0aGvp":{"name":"certificates","abstract":"

The SecCertificates contained i self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE15certificateDataSay10Foundation0G0VGvp":{"name":"certificateData","abstract":"

The Data values for all certificates contained in self.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE24performDefaultValidation7forHostySS_tKF":{"name":"performDefaultValidation(forHost:)","abstract":"

Validates self after applying SecPolicy.af.default. This evaluation does not validate the hostname.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo11SecTrustRefaRszlE17performValidation7forHostySS_tKF":{"name":"performValidation(forHost:)","abstract":"

Validates self after applying SecPolicy.af.hostname(host), which performs the default validation as well as","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE7defaultAEvpZ":{"name":"default","abstract":"

Creates a SecPolicy instance which will validate server certificates but not require a host name match.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE8hostnameyAESSFZ":{"name":"hostname(_:)","abstract":"

Creates a SecPolicy instance which will validate server certificates and much match the provided hostname.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo12SecPolicyRefaRszlE10revocation7optionsAeA24RevocationTrustEvaluatorC7OptionsV_tKFZ":{"name":"revocation(options:)","abstract":"

Creates a SecPolicy which checks the revocation of certificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASaySo17SecCertificateRefaGRszlE4dataSay10Foundation4DataVGvp":{"name":"data","abstract":"

All Data values for the contained SecCertificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASaySo17SecCertificateRefaGRszlE10publicKeysSaySo0c3KeyE0aGvp":{"name":"publicKeys","abstract":"

All public SecKey values for the contained SecCertificates.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo17SecCertificateRefaRszlE9publicKeySo0cgE0aSgvp":{"name":"publicKey","abstract":"

The public key for self, if it can be extracted.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAAs5Int32VRszlE9isSuccessSbvp":{"name":"isSuccess","abstract":"

Returns whether self is errSecSuccess.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo18SecTrustResultTypeVRszlE9isSuccessSbvp":{"name":"isSuccess","abstract":"

Returns whether self is.unspecifiedor.proceed`.

","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html#/s:9Alamofire0A9ExtensionVAASo25NSURLSessionConfigurationCRbzlE7defaultAEvpZ":{"name":"default","abstract":"

Alamofire’s default configuration. Same as URLSessionConfiguration.default but adds Alamofire default","parent_name":"AlamofireExtension"},"Structs/AlamofireExtension.html":{"name":"AlamofireExtension","abstract":"

Type that acts as a generic extension point for all AlamofireExtended types.

"},"Structs/ResponseCacher.html":{"name":"ResponseCacher","abstract":"

ResponseCacher is a convenience CachedResponseHandler making it easy to cache, not cache, or modify a cached"},"Structs/HTTPHeaders.html":{"name":"HTTPHeaders","abstract":"

An order-preserving and case-insensitive representation of HTTP headers.

"},"Structs/HTTPHeader.html":{"name":"HTTPHeader","abstract":"

A representation of a single HTTP header’s name / value pair.

"},"Structs/HTTPMethod.html":{"name":"HTTPMethod","abstract":"

Type representing HTTP methods. Raw String value is stored and compared case-sensitively, so"},"Structs/URLEncoding.html":{"name":"URLEncoding","abstract":"

Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP"},"Structs/JSONEncoding.html":{"name":"JSONEncoding","abstract":"

Uses JSONSerialization to create a JSON representation of the parameters object, which is set as the body of the"},"Structs/Redirector.html":{"name":"Redirector","abstract":"

Redirector is a convenience RedirectHandler making it easy to follow, not follow, or modify a redirect.

"},"Structs/DataResponse.html":{"name":"DataResponse","abstract":"

Type used to store all values associated with a serialized response of a DataRequest or UploadRequest.

"},"Structs/DownloadResponse.html":{"name":"DownloadResponse","abstract":"

Used to store all data associated with a serialized response of a download request.

"},"Structs/PassthroughPreprocessor.html":{"name":"PassthroughPreprocessor","abstract":"

DataPreprocessor that returns passed Data without any transform.

"},"Structs/GoogleXSSIPreprocessor.html":{"name":"GoogleXSSIPreprocessor","abstract":"

DataPreprocessor that trims Google’s typical )]}',\\n XSSI JSON header.

"},"Structs/Empty.html":{"name":"Empty","abstract":"

Type representing an empty response. Use Empty.value to get the static instance.

"},"Protocols/URLRequestConvertible.html#/s:9Alamofire21URLRequestConvertibleP02asB010Foundation0B0VyKF":{"name":"asURLRequest()","abstract":"

Returns a URLRequest or throws if an Error was encountered.

","parent_name":"URLRequestConvertible"},"Protocols/URLRequestConvertible.html#/s:9Alamofire21URLRequestConvertiblePAAE10urlRequest10Foundation0B0VSgvp":{"name":"urlRequest","abstract":"

The URLRequest returned by discarding any Error encountered.

","parent_name":"URLRequestConvertible"},"Protocols/URLConvertible.html#/s:9Alamofire14URLConvertibleP5asURL10Foundation0D0VyKF":{"name":"asURL()","abstract":"

Returns a URL from the conforming instance or throws.

","parent_name":"URLConvertible"},"Protocols/ServerTrustEvaluating.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","abstract":"

Evaluates the given SecTrust value for the given host.

","parent_name":"ServerTrustEvaluating"},"Protocols/DataDecoder.html#/s:9Alamofire11DataDecoderP6decode_4fromqd__qd__m_10Foundation0B0VtKSeRd__lF":{"name":"decode(_:from:)","abstract":"

Decode Data into the provided type.

","parent_name":"DataDecoder"},"Protocols/EmptyResponse.html#/s:9Alamofire13EmptyResponseP10emptyValuexyFZ":{"name":"emptyValue()","abstract":"

Empty value for the conforming type.

","parent_name":"EmptyResponse"},"Protocols/DataPreprocessor.html#/s:9Alamofire16DataPreprocessorP10preprocessy10Foundation0B0VAGKF":{"name":"preprocess(_:)","abstract":"

Process Data before it’s handled by a serializer.

","parent_name":"DataPreprocessor"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","abstract":"

DataPreprocessor used to prepare incoming Data for serialization.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","abstract":"

HTTPMethods for which empty response bodies are considered appropriate.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","abstract":"

HTTP response codes for which empty response bodies are considered appropriate.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE23defaultDataPreprocessorAA0eF0_pvpZ":{"name":"defaultDataPreprocessor","abstract":"

Default DataPreprocessor. PassthroughPreprocessor by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE26defaultEmptyRequestMethodsShyAA10HTTPMethodVGvpZ":{"name":"defaultEmptyRequestMethods","abstract":"

Default HTTPMethods for which empty response bodies are considered appropriate. [.head] by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE012defaultEmptyB5CodesShySiGvpZ":{"name":"defaultEmptyResponseCodes","abstract":"

HTTP response codes for which empty response bodies are considered appropriate. [204, 205] by default.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE018requestAllowsEmptyB4DataySbSg10Foundation10URLRequestVSgF":{"name":"requestAllowsEmptyResponseData(_:)","abstract":"

Determines whether the request allows empty response bodies, if request exists.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE019responseAllowsEmptyB4DataySbSgSo17NSHTTPURLResponseCSgF":{"name":"responseAllowsEmptyResponseData(_:)","abstract":"

Determines whether the response allows empty response bodies, if response exists`.

","parent_name":"ResponseSerializer"},"Protocols/ResponseSerializer.html#/s:9Alamofire18ResponseSerializerPAAE05emptyB7Allowed10forRequest8responseSb10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgtF":{"name":"emptyResponseAllowed(forRequest:response:)","abstract":"

Determines whether request and response allow empty response bodies.

","parent_name":"ResponseSerializer"},"Protocols/DownloadResponseSerializerProtocol.html#/s:9Alamofire34DownloadResponseSerializerProtocolP16SerializedObjectQa":{"name":"SerializedObject","abstract":"

The type of serialized object to be created.

","parent_name":"DownloadResponseSerializerProtocol"},"Protocols/DownloadResponseSerializerProtocol.html#/s:9Alamofire34DownloadResponseSerializerProtocolP09serializeB07request8response7fileURL5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0J0VSgs5Error_pSgtKF":{"name":"serializeDownload(request:response:fileURL:error:)","abstract":"

Serialize the downloaded response Data from disk into the provided type..

","parent_name":"DownloadResponseSerializerProtocol"},"Protocols/DataResponseSerializerProtocol.html#/s:9Alamofire30DataResponseSerializerProtocolP16SerializedObjectQa":{"name":"SerializedObject","abstract":"

The type of serialized object to be created.

","parent_name":"DataResponseSerializerProtocol"},"Protocols/DataResponseSerializerProtocol.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","abstract":"

Serialize the response Data into the provided type..

","parent_name":"DataResponseSerializerProtocol"},"Protocols/RequestInterceptor.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"RequestInterceptor"},"Protocols/RequestInterceptor.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"RequestInterceptor"},"Protocols/RequestRetrier.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","abstract":"

Determines whether the Request should be retried by calling the completion closure.

","parent_name":"RequestRetrier"},"Protocols/RequestAdapter.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","abstract":"

Inspects and adapts the specified URLRequest in some manner and calls the completion handler with the Result.

","parent_name":"RequestAdapter"},"Protocols/UploadableConvertible.html#/s:9Alamofire21UploadableConvertibleP06createB0AA13UploadRequestC0B0OyKF":{"name":"createUploadable()","abstract":"

Produces an UploadRequest.Uploadable value from the instance.

","parent_name":"UploadableConvertible"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP20sessionConfigurationSo012NSURLSessionE0Cvp":{"name":"sessionConfiguration","abstract":"

URLSessionConfiguration used to create the underlying URLSessionTasks.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP16startImmediatelySbvp":{"name":"startImmediately","abstract":"

Determines whether the Request should automatically call resume() when adding the first response handler.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP7cleanup5afteryAA0B0C_tF":{"name":"cleanup(after:)","abstract":"

Notifies the delegate the Request has reached a point where it needs cleanup.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP11retryResult3for5dueTo10completionyAA0B0C_AA7AFErrorOyAA05RetryE0OctF":{"name":"retryResult(for:dueTo:completion:)","abstract":"

Asynchronously ask the delegate whether a Request will be retried.

","parent_name":"RequestDelegate"},"Protocols/RequestDelegate.html#/s:9Alamofire15RequestDelegateP05retryB0_9withDelayyAA0B0C_SdSgtF":{"name":"retryRequest(_:withDelay:)","abstract":"

Asynchronously retry the Request.

","parent_name":"RequestDelegate"},"Protocols/RedirectHandler.html#/s:9Alamofire15RedirectHandlerP4task_18willBeRedirectedTo3for10completionySo16NSURLSessionTaskC_10Foundation10URLRequestVSo17NSHTTPURLResponseCyALSgctF":{"name":"task(_:willBeRedirectedTo:for:completion:)","abstract":"

Determines how the HTTP redirect response should be redirected to the new request.

","parent_name":"RedirectHandler"},"Protocols/ParameterEncoding.html#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF":{"name":"encode(_:with:)","abstract":"

Creates a URLRequest by encoding parameters and applying them on the passed request.

","parent_name":"ParameterEncoding"},"Protocols/ParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","abstract":"

Encode the provided Encodable parameters into request.

","parent_name":"ParameterEncoder"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","abstract":"

The DispatchQueue onto which Alamofire’s root CompositeEventMonitor will dispatch events. .main by default.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","abstract":"

Event called during URLSessionDelegate‘s urlSession(_:didBecomeInvalidWithError:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didReceive:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:needNewBodyStream:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didFinishCollecting:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:task:didCompleteWithError:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","abstract":"

Event called during URLSessionTaskDelegate‘s urlSession(_:taskIsWaitingForConnectivity:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","abstract":"

Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:didReceive:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","abstract":"

Event called during URLSessionDataDelegate‘s urlSession(_:dataTask:willCacheResponse:completionHandler:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","abstract":"

Event called during URLSessionDownloadDelegate‘s urlSession(_:downloadTask:didFinishDownloadingTo:) method.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","abstract":"

Event called when a URLRequest is first created for a Request. If a RequestAdapter is active, the","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","abstract":"

Event called when the attempt to create a URLRequest from a Request‘s original URLRequestConvertible value fails.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","abstract":"

Event called when a RequestAdapter adapts the Request‘s initial URLRequest.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","abstract":"

Event called when a RequestAdapter fails to adapt the Request‘s initial URLRequest.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","abstract":"

Event called when a final URLRequest is created for a Request.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","abstract":"

Event called when a URLSessionTask subclass instance is created for a Request.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","abstract":"

Event called when a Request receives a URLSessionTaskMetrics value.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","abstract":"

Event called when a Request fails due to an error created by Alamofire. e.g. When certificate pinning fails.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","abstract":"

Event called when a Request‘s task completes, possibly with an error. A Request may receive this event","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","abstract":"

Event called when a Request is about to be retried.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","abstract":"

Event called when a Request finishes and response serializers are being called.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","abstract":"

Event called when a Request receives a resume call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is resumed.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","abstract":"

Event called when a Request receives a suspend call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is suspended.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","abstract":"

Event called when a Request receives a cancel call.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","abstract":"

Event called when a Request‘s associated URLSessionTask is cancelled.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","abstract":"

Event called when a DataRequest calls a Validation.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DataRequest creates a DataResponse<Data?> value without calling a ResponseSerializer.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DataRequest calls a ResponseSerializer and creates a generic DataResponse<Value, AFError>.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","abstract":"

Event called when an UploadRequest creates its Uploadable value, indicating the type of upload it represents.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","abstract":"

Event called when an UploadRequest failed to create its Uploadable value due to an error.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","abstract":"

Event called when an UploadRequest provides the InputStream from its Uploadable value. This only occurs if","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","abstract":"

Event called when a DownloadRequest‘s URLSessionDownloadTask finishes and the temporary file has been moved.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","abstract":"

Event called when a DownloadRequest‘s Destination closure is called and creates the destination URL the","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","abstract":"

Event called when a DownloadRequest calls a Validation.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DownloadRequest creates a DownloadResponse<URL?, AFError> without calling a ResponseSerializer.

","parent_name":"EventMonitor"},"Protocols/EventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","abstract":"

Event called when a DownloadRequest calls a DownloadResponseSerializer and creates a generic DownloadResponse<Value, AFError>

","parent_name":"EventMonitor"},"Protocols/CachedResponseHandler.html#/s:9Alamofire21CachedResponseHandlerP8dataTask_09willCacheC010completionySo016NSURLSessionDataF0C_So19NSCachedURLResponseCyAJSgctF":{"name":"dataTask(_:willCacheResponse:completion:)","abstract":"

Determines whether the HTTP response should be stored in the cache.

","parent_name":"CachedResponseHandler"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP0B4TypeQa":{"name":"ExtendedType","abstract":"

Type being extended.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP2afAA0A9ExtensionVy0B4TypeQzGmvpZ":{"name":"af","abstract":"

Static Alamofire extension point.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html#/s:9Alamofire0A8ExtendedP2afAA0A9ExtensionVy0B4TypeQzGvp":{"name":"af","abstract":"

Instance Alamofire extension point.

","parent_name":"AlamofireExtended"},"Protocols/AlamofireExtended.html":{"name":"AlamofireExtended","abstract":"

Protocol describing the af extension points for Alamofire extended types.

"},"Protocols/CachedResponseHandler.html":{"name":"CachedResponseHandler","abstract":"

A type that handles whether the data task should store the HTTP response in the cache.

"},"Protocols/EventMonitor.html":{"name":"EventMonitor","abstract":"

Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various"},"Protocols/ParameterEncoder.html":{"name":"ParameterEncoder","abstract":"

A type that can encode any Encodable type into a URLRequest.

"},"Protocols/ParameterEncoding.html":{"name":"ParameterEncoding","abstract":"

A type used to define how a set of parameters are applied to a URLRequest.

"},"Protocols/RedirectHandler.html":{"name":"RedirectHandler","abstract":"

A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.

"},"Protocols/RequestDelegate.html":{"name":"RequestDelegate","abstract":"

Protocol abstraction for Request‘s communication back to the SessionDelegate.

"},"Protocols/UploadableConvertible.html":{"name":"UploadableConvertible","abstract":"

A type that can produce an UploadRequest.Uploadable value.

"},"Protocols.html#/s:9Alamofire17UploadConvertibleP":{"name":"UploadConvertible","abstract":"

A type that can be converted to an upload, whether from an UploadRequest.Uploadable or URLRequestConvertible.

"},"Protocols/RequestAdapter.html":{"name":"RequestAdapter","abstract":"

A type that can inspect and optionally adapt a URLRequest in some manner if necessary.

"},"Protocols/RequestRetrier.html":{"name":"RequestRetrier","abstract":"

A type that determines whether a request should be retried after being executed by the specified session manager"},"Protocols/RequestInterceptor.html":{"name":"RequestInterceptor","abstract":"

Type that provides both RequestAdapter and RequestRetrier functionality.

"},"Protocols/DataResponseSerializerProtocol.html":{"name":"DataResponseSerializerProtocol","abstract":"

The type to which all data response serializers must conform in order to serialize a response.

"},"Protocols/DownloadResponseSerializerProtocol.html":{"name":"DownloadResponseSerializerProtocol","abstract":"

The type to which all download response serializers must conform in order to serialize a response.

"},"Protocols/ResponseSerializer.html":{"name":"ResponseSerializer","abstract":"

A serializer that can handle both data and download responses.

"},"Protocols/DataPreprocessor.html":{"name":"DataPreprocessor","abstract":"

Type used to preprocess Data before it handled by a serializer.

"},"Protocols/EmptyResponse.html":{"name":"EmptyResponse","abstract":"

Protocol representing an empty response. Use T.emptyValue() to get an instance.

"},"Protocols/DataDecoder.html":{"name":"DataDecoder","abstract":"

Any type which can decode Data into a Decodable type.

"},"Protocols/ServerTrustEvaluating.html":{"name":"ServerTrustEvaluating","abstract":"

A protocol describing the API used to evaluate server trusts.

"},"Protocols/URLConvertible.html":{"name":"URLConvertible","abstract":"

Types adopting the URLConvertible protocol can be used to construct URLs, which can then be used to construct"},"Protocols/URLRequestConvertible.html":{"name":"URLRequestConvertible","abstract":"

Types adopting the URLRequestConvertible protocol can be used to safely construct URLRequests.

"},"Extensions/CharacterSet.html#/s:10Foundation12CharacterSetV9AlamofireE17afURLQueryAllowedACvpZ":{"name":"afURLQueryAllowed","abstract":"

Creates a CharacterSet from RFC 3986 allowed characters.

","parent_name":"CharacterSet"},"Extensions/URLComponents.html#/s:10Foundation13URLComponentsV9AlamofireE5asURLAA0E0VyKF":{"name":"asURL()","abstract":"

Returns a URL if the self‘s url is not nil, otherwise throws.

","parent_name":"URLComponents"},"Extensions/URL.html#/s:10Foundation3URLV9AlamofireE02asB0ACyKF":{"name":"asURL()","abstract":"

Returns self.

","parent_name":"URL"},"Extensions/String.html#/s:SS9AlamofireE5asURL10Foundation0C0VyKF":{"name":"asURL()","abstract":"

Returns a URL if self can be used to initialize a URL instance, otherwise throws.

","parent_name":"String"},"Extensions/Array.html#/s:Sa9AlamofireAA21ServerTrustEvaluating_pRszlE8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","abstract":"

Evaluates the given SecTrust value for the given host.

","parent_name":"Array"},"Extensions/Notification.html#/s:10Foundation12NotificationV9AlamofireE7requestAD7RequestCSgvp":{"name":"request","abstract":"

The Request contained by the instance’s userInfo, nil otherwise.

","parent_name":"Notification"},"Extensions/URLSessionConfiguration.html#/s:So25NSURLSessionConfigurationC9AlamofireE7headersAC11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns httpAdditionalHeaders as HTTPHeaders.

","parent_name":"URLSessionConfiguration"},"Extensions/HTTPURLResponse.html#/s:So17NSHTTPURLResponseC9AlamofireE7headersAC11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns allHeaderFields as HTTPHeaders.

","parent_name":"HTTPURLResponse"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE7headersAD11HTTPHeadersVvp":{"name":"headers","abstract":"

Returns allHTTPHeaderFields as HTTPHeaders.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE02asB0ACyKF":{"name":"asURLRequest()","abstract":"

Returns self.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE3url6method7headersAcD14URLConvertible_p_AD10HTTPMethodVAD11HTTPHeadersVSgtKcfc":{"name":"init(url:method:headers:)","abstract":"

Creates an instance with the specified url, method, and headers.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE6methodAD10HTTPMethodVSgvp":{"name":"method","abstract":"

Returns the httpMethod as Alamofire’s HTTPMethod type.

","parent_name":"URLRequest"},"Extensions/URLRequest.html#/s:10Foundation10URLRequestV9AlamofireE8validateyyKF":{"name":"validate()","abstract":"

Undocumented

","parent_name":"URLRequest"},"Extensions/Error.html#/s:s5ErrorP9AlamofireE9asAFErrorAC0D0OSgvp":{"name":"asAFError","abstract":"

Returns the instance cast as an AFError.

","parent_name":"Error"},"Extensions/Error.html#/s:s5ErrorP9AlamofireE9asAFError10orFailWith4file4lineAC0D0OSSyXK_s12StaticStringVSutF":{"name":"asAFError(orFailWith:file:line:)","abstract":"

Returns the instance cast as an AFError. If casting fails, a fatalError with the specified message is thrown.

","parent_name":"Error"},"Extensions/Error.html":{"name":"Error"},"Extensions/URLRequest.html":{"name":"URLRequest"},"Extensions/HTTPURLResponse.html":{"name":"HTTPURLResponse"},"Extensions/URLSessionConfiguration.html":{"name":"URLSessionConfiguration"},"Extensions/Notification.html":{"name":"Notification"},"Extensions/Array.html":{"name":"Array"},"Extensions/String.html":{"name":"String"},"Extensions/URL.html":{"name":"URL"},"Extensions/URLComponents.html":{"name":"URLComponents"},"Extensions/CharacterSet.html":{"name":"CharacterSet"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO5retryyA2CmF":{"name":"retry","abstract":"

Retry should be attempted immediately.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO14retryWithDelayyACSdcACmF":{"name":"retryWithDelay(_:)","abstract":"

Retry should be attempted after the associated TimeInterval.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO05doNotB0yA2CmF":{"name":"doNotRetry","abstract":"

Do not retry.

","parent_name":"RetryResult"},"Enums/RetryResult.html#/s:9Alamofire11RetryResultO05doNotB9WithErroryACs0G0_pcACmF":{"name":"doNotRetryWithError(_:)","abstract":"

Do not retry due to the associated AFError.

","parent_name":"RetryResult"},"Enums/AF.html#/s:9Alamofire2AFO7request_6method10parameters8encoding7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtFZ":{"name":"request(_:method:parameters:encoding:headers:interceptor:)","abstract":"

Creates a DataRequest using Session.default to retrieve the contents of the specified url using the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO7request_6method10parameters7encoder7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtSERzlFZ":{"name":"request(_:method:parameters:encoder:headers:interceptor:)","abstract":"

Creates a DataRequest using Session.default to retrieve the contents of the specified url using the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO7request_11interceptorAA11DataRequestCAA21URLRequestConvertible_p_AA0F11Interceptor_pSgtFZ":{"name":"request(_:interceptor:)","abstract":"

Creates a DataRequest using Session.default to execute the specified urlRequest.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_6method10parameters8encoding7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAZ_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(_:method:parameters:encoding:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to download the contents of the specified url to","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_6method10parameters7encoder7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAY_So17NSHTTPURLResponseCtcSgtSERzlFZ":{"name":"download(_:method:parameters:encoder:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to download the contents of the specified url to the","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download_11interceptor2toAA15DownloadRequestCAA21URLRequestConvertible_p_AA0G11Interceptor_pSg10Foundation3URLV011destinationL0_AH7OptionsV7optionstAN_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(_:interceptor:to:)","abstract":"

Creates a DownloadRequest using Session.default to execute the specified urlRequest and download","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO8download12resumingWith11interceptor2toAA15DownloadRequestC10Foundation4DataV_AA0I11Interceptor_pSgAJ3URLV011destinationM0_AI7OptionsV7optionstAP_So17NSHTTPURLResponseCtcSgtFZ":{"name":"download(resumingWith:interceptor:to:)","abstract":"

Creates a DownloadRequest using the Session.default from the resumeData produced from a previous","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data, URLRequest components, and RequestInterceptor.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data using the URLRequestConvertible value and RequestInterceptor.

","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL, using a URLRequest from the provided","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL using the URLRequestConvertible value and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtFZ":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the InputStream provided using a URLRequest from the provided components and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload_4with11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtFZ":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the provided InputStream using the URLRequestConvertible value and","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtFZ":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the multipart form data built using a closure and sent using the provided","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtFZ":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtFZ":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components","parent_name":"AF"},"Enums/AF.html#/s:9Alamofire2AFO6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtFZ":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible","parent_name":"AF"},"Enums/AFError/URLRequestValidationFailureReason.html#/s:9Alamofire7AFErrorO33URLRequestValidationFailureReasonO20bodyDataInGETRequestyAE10Foundation0H0VcAEmF":{"name":"bodyDataInGETRequest(_:)","abstract":"

URLRequest with GET method had body data.

","parent_name":"URLRequestValidationFailureReason"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV4hostSSvp":{"name":"host","abstract":"

The host for which the evaluation was performed.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV5trustSo03SecD3Refavp":{"name":"trust","abstract":"

The SecTrust value which was evaluated.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV6statuss5Int32Vvp":{"name":"status","abstract":"

The OSStatus of evaluation operation.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO6OutputV6resultSo03SecD10ResultTypeVvp":{"name":"result","abstract":"

The result of the evaluation operation.

","parent_name":"Output"},"Enums/AFError/ServerTrustFailureReason/Output.html":{"name":"Output","abstract":"

The output of a server trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO19noRequiredEvaluatoryAESS_tcAEmF":{"name":"noRequiredEvaluator(host:)","abstract":"

No ServerTrustEvaluator was found for the associated host.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO19noCertificatesFoundyA2EmF":{"name":"noCertificatesFound","abstract":"

No certificates were found with which to perform the trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO17noPublicKeysFoundyA2EmF":{"name":"noPublicKeysFound","abstract":"

No public keys were found with which to perform the trust evaluation.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO23policyApplicationFailedyAESo03SecD3Refa_So0j6PolicyK0as5Int32VtcAEmF":{"name":"policyApplicationFailed(trust:policy:status:)","abstract":"

During evaluation, application of the associated SecPolicy failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO31settingAnchorCertificatesFailedyAEs5Int32V_SaySo17SecCertificateRefaGtcAEmF":{"name":"settingAnchorCertificatesFailed(status:certificates:)","abstract":"

During evaluation, setting the associated anchor certificates failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO30revocationPolicyCreationFailedyA2EmF":{"name":"revocationPolicyCreationFailed","abstract":"

During evaluation, creation of the revocation policy failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO21trustEvaluationFailedyAEs5Error_pSg_tcAEmF":{"name":"trustEvaluationFailed(error:)","abstract":"

SecTrust evaluation failed with the associated Error, if one was produced.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO23defaultEvaluationFailedyA2E6OutputV_tcAEmF":{"name":"defaultEvaluationFailed(output:)","abstract":"

Default evaluation failed with the associated Output.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO20hostValidationFailedyA2E6OutputV_tcAEmF":{"name":"hostValidationFailed(output:)","abstract":"

Host validation failed with the associated Output.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO21revocationCheckFailedyA2E6OutputV_AA010RevocationD9EvaluatorC7OptionsVtcAEmF":{"name":"revocationCheckFailed(output:options:)","abstract":"

Revocation check failed with the associated Output and options.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO24certificatePinningFailedyAESS_So03SecD3RefaSaySo0j11CertificateK0aGAKtcAEmF":{"name":"certificatePinningFailed(host:trust:pinnedCertificates:serverCertificates:)","abstract":"

Certificate pinning failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO22publicKeyPinningFailedyAESS_So03SecD3RefaSaySo0khL0aGAKtcAEmF":{"name":"publicKeyPinningFailed(host:trust:pinnedKeys:serverKeys:)","abstract":"

Public key pinning failed.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ServerTrustFailureReason.html#/s:9Alamofire7AFErrorO24ServerTrustFailureReasonO22customEvaluationFailedyAEs5Error_p_tcAEmF":{"name":"customEvaluationFailed(error:)","abstract":"

Custom server trust evaluation failed due to the associated Error.

","parent_name":"ServerTrustFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO24inputDataNilOrZeroLengthyA2EmF":{"name":"inputDataNilOrZeroLength","abstract":"

The server response contained no data or the data was zero length.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO12inputFileNilyA2EmF":{"name":"inputFileNil","abstract":"

The file containing the server response did not exist.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO19inputFileReadFailedyAE10Foundation3URLV_tcAEmF":{"name":"inputFileReadFailed(at:)","abstract":"

The file containing the server response could not be read from the associated URL.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO06stringD6FailedyAESS10FoundationE8EncodingV_tcAEmF":{"name":"stringSerializationFailed(encoding:)","abstract":"

String serialization failed using the provided String.Encoding.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO04jsonD6FailedyAEs5Error_p_tcAEmF":{"name":"jsonSerializationFailed(error:)","abstract":"

JSON serialization failed with an underlying system error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO14decodingFailedyAEs5Error_p_tcAEmF":{"name":"decodingFailed(error:)","abstract":"

A DataDecoder failed to decode the response due to the associated Error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customSerializationFailed(error:)","abstract":"

A custom response serializer failed due to the associated Error.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseSerializationFailureReason.html#/s:9Alamofire7AFErrorO34ResponseSerializationFailureReasonO012invalidEmptyC0yAESS_tcAEmF":{"name":"invalidEmptyResponse(type:)","abstract":"

Generic serialization failed for an empty response that wasn’t type Empty but instead the associated type.

","parent_name":"ResponseSerializationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO11dataFileNilyA2EmF":{"name":"dataFileNil","abstract":"

The data file containing the server response did not exist.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO18dataFileReadFailedyAE10Foundation3URLV_tcAEmF":{"name":"dataFileReadFailed(at:)","abstract":"

The data file containing the server response at the associated URL could not be read.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO18missingContentTypeyAESaySSG_tcAEmF":{"name":"missingContentType(acceptableContentTypes:)","abstract":"

The response did not contain a Content-Type and the acceptableContentTypes provided did not contain a","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO23unacceptableContentTypeyAESaySSG_SStcAEmF":{"name":"unacceptableContentType(acceptableContentTypes:responseContentType:)","abstract":"

The response Content-Type did not match any type in the provided acceptableContentTypes.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO22unacceptableStatusCodeyAESi_tcAEmF":{"name":"unacceptableStatusCode(code:)","abstract":"

The response status code was not acceptable.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ResponseValidationFailureReason.html#/s:9Alamofire7AFErrorO31ResponseValidationFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customValidationFailed(error:)","abstract":"

Custom response validation failed due to the associated Error.

","parent_name":"ResponseValidationFailureReason"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO17RequiredComponentO3urlyA2GmF":{"name":"url","abstract":"

The URL was missing or unable to be extracted from the passed URLRequest or during encoding.

","parent_name":"RequiredComponent"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO17RequiredComponentO10httpMethodyAGSS_tcAGmF":{"name":"httpMethod(rawValue:)","abstract":"

The HTTPMethod could not be extracted from the passed URLRequest.

","parent_name":"RequiredComponent"},"Enums/AFError/ParameterEncoderFailureReason/RequiredComponent.html":{"name":"RequiredComponent","abstract":"

Possible missing components.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncoderFailureReason.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO24missingRequiredComponentyA2E0hI0OcAEmF":{"name":"missingRequiredComponent(_:)","abstract":"

A RequiredComponent was missing during encoding.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncoderFailureReason.html#/s:9Alamofire7AFErrorO29ParameterEncoderFailureReasonO13encoderFailedyAEs5Error_p_tcAEmF":{"name":"encoderFailed(error:)","abstract":"

The underlying encoder failed with the associated error.

","parent_name":"ParameterEncoderFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO10missingURLyA2EmF":{"name":"missingURL","abstract":"

The URLRequest did not have a URL to encode.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO04jsonD6FailedyAEs5Error_p_tcAEmF":{"name":"jsonEncodingFailed(error:)","abstract":"

JSON serialization failed with an underlying system error during the encoding process.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/ParameterEncodingFailureReason.html#/s:9Alamofire7AFErrorO30ParameterEncodingFailureReasonO06customD6FailedyAEs5Error_p_tcAEmF":{"name":"customEncodingFailed(error:)","abstract":"

Custom parameter encoding failed due to the associated Error.

","parent_name":"ParameterEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO18bodyPartURLInvalidyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartURLInvalid(url:)","abstract":"

The fileURL provided for reading an encodable body part isn’t a file URL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23bodyPartFilenameInvalidyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFilenameInvalid(in:)","abstract":"

The filename of the fileURL provided has either an empty lastPathComponent or `pathExtension.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO24bodyPartFileNotReachableyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileNotReachable(at:)","abstract":"

The file at the fileURL provided was not reachable.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO33bodyPartFileNotReachableWithErroryAE10Foundation3URLV_s0M0_ptcAEmF":{"name":"bodyPartFileNotReachableWithError(atURL:error:)","abstract":"

Attempting to check the reachability of the fileURL provided threw an error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23bodyPartFileIsDirectoryyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileIsDirectory(at:)","abstract":"

The file at the fileURL provided is actually a directory.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO28bodyPartFileSizeNotAvailableyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartFileSizeNotAvailable(at:)","abstract":"

The size of the file at the fileURL provided was not returned by the system.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO36bodyPartFileSizeQueryFailedWithErroryAE10Foundation3URLV_s0N0_ptcAEmF":{"name":"bodyPartFileSizeQueryFailedWithError(forURL:error:)","abstract":"

The attempt to find the size of the file at the fileURL provided threw an error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO33bodyPartInputStreamCreationFailedyAE10Foundation3URLV_tcAEmF":{"name":"bodyPartInputStreamCreationFailed(for:)","abstract":"

An InputStream could not be created for the provided fileURL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO26outputStreamCreationFailedyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamCreationFailed(for:)","abstract":"

An OutputStream could not be created when attempting to write the encoded data to disk.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO29outputStreamFileAlreadyExistsyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamFileAlreadyExists(at:)","abstract":"

The encoded body data could not be written to disk because a file already exists at the provided fileURL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO22outputStreamURLInvalidyAE10Foundation3URLV_tcAEmF":{"name":"outputStreamURLInvalid(url:)","abstract":"

The fileURL provided for writing the encoded body data to disk is not a file URL.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO23outputStreamWriteFailedyAEs5Error_p_tcAEmF":{"name":"outputStreamWriteFailed(error:)","abstract":"

The attempt to write the encoded body data to disk failed with an underlying error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html#/s:9Alamofire7AFErrorO30MultipartEncodingFailureReasonO21inputStreamReadFailedyAEs5Error_p_tcAEmF":{"name":"inputStreamReadFailed(error:)","abstract":"

The attempt to read an encoded body part InputStream failed with underlying system error.

","parent_name":"MultipartEncodingFailureReason"},"Enums/AFError/MultipartEncodingFailureReason.html":{"name":"MultipartEncodingFailureReason","abstract":"

The underlying reason the .multipartEncodingFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ParameterEncodingFailureReason.html":{"name":"ParameterEncodingFailureReason","abstract":"

The underlying reason the .parameterEncodingFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ParameterEncoderFailureReason.html":{"name":"ParameterEncoderFailureReason","abstract":"

The underlying reason the .parameterEncoderFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ResponseValidationFailureReason.html":{"name":"ResponseValidationFailureReason","abstract":"

The underlying reason the .responseValidationFailed error occurred.

","parent_name":"AFError"},"Enums/AFError/ResponseSerializationFailureReason.html":{"name":"ResponseSerializationFailureReason","abstract":"

The underlying reason the response serialization error occurred.

","parent_name":"AFError"},"Enums/AFError/ServerTrustFailureReason.html":{"name":"ServerTrustFailureReason","abstract":"

Underlying reason a server trust evaluation error occurred.

","parent_name":"AFError"},"Enums/AFError/URLRequestValidationFailureReason.html":{"name":"URLRequestValidationFailureReason","abstract":"

The underlying reason the .urlRequestValidationFailed

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22createUploadableFailedyACs5Error_p_tcACmF":{"name":"createUploadableFailed(error:)","abstract":"

UploadableConvertible threw an error in createUploadable().

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22createURLRequestFailedyACs5Error_p_tcACmF":{"name":"createURLRequestFailed(error:)","abstract":"

URLRequestConvertible threw an error in asURLRequest().

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24downloadedFileMoveFailedyACs5Error_p_10Foundation3URLVAHtcACmF":{"name":"downloadedFileMoveFailed(error:source:destination:)","abstract":"

SessionDelegate threw an error while attempting to move downloaded file to destination URL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19explicitlyCancelledyA2CmF":{"name":"explicitlyCancelled","abstract":"

Request was explicitly cancelled.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO10invalidURLyAcA14URLConvertible_p_tcACmF":{"name":"invalidURL(url:)","abstract":"

URLConvertible type failed to create a valid URL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23multipartEncodingFailedyA2C09MultipartD13FailureReasonO_tcACmF":{"name":"multipartEncodingFailed(reason:)","abstract":"

Multipart form encoding failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23parameterEncodingFailedyA2C09ParameterD13FailureReasonO_tcACmF":{"name":"parameterEncodingFailed(reason:)","abstract":"

ParameterEncoding threw an error during the encoding process.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22parameterEncoderFailedyA2C09ParameterD13FailureReasonO_tcACmF":{"name":"parameterEncoderFailed(reason:)","abstract":"

ParameterEncoder threw an error while running the encoder.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23requestAdaptationFailedyACs5Error_p_tcACmF":{"name":"requestAdaptationFailed(error:)","abstract":"

RequestAdapter threw an error during adaptation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18requestRetryFailedyACs5Error_p_sAE_ptcACmF":{"name":"requestRetryFailed(retryError:originalError:)","abstract":"

RequestRetrier threw an error during the request retry process.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24responseValidationFailedyA2C08ResponseD13FailureReasonO_tcACmF":{"name":"responseValidationFailed(reason:)","abstract":"

Response validation failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27responseSerializationFailedyA2C08ResponseD13FailureReasonO_tcACmF":{"name":"responseSerializationFailed(reason:)","abstract":"

Response serialization failed.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27serverTrustEvaluationFailedyA2C06ServerD13FailureReasonO_tcACmF":{"name":"serverTrustEvaluationFailed(reason:)","abstract":"

ServerTrustEvaluating instance threw an error during trust evaluation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO20sessionDeinitializedyA2CmF":{"name":"sessionDeinitialized","abstract":"

Session which issued the Request was deinitialized, most likely because its reference went out of scope.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18sessionInvalidatedyACs5Error_pSg_tcACmF":{"name":"sessionInvalidated(error:)","abstract":"

Session was explicitly invalidated, possibly with the Error produced by the underlying URLSession.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO17sessionTaskFailedyACs5Error_p_tcACmF":{"name":"sessionTaskFailed(error:)","abstract":"

URLSessionTask completed with error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO26urlRequestValidationFailedyA2C010URLRequestE13FailureReasonO_tcACmF":{"name":"urlRequestValidationFailed(reason:)","abstract":"

URLRequest failed validation.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO27isSessionDeinitializedErrorSbvp":{"name":"isSessionDeinitializedError","abstract":"

Returns whether the instance is .sessionDeinitialized.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isSessionInvalidatedErrorSbvp":{"name":"isSessionInvalidatedError","abstract":"

Returns whether the instance is .sessionInvalidated.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO26isExplicitlyCancelledErrorSbvp":{"name":"isExplicitlyCancelledError","abstract":"

Returns whether the instance is .explicitlyCancelled.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO17isInvalidURLErrorSbvp":{"name":"isInvalidURLError","abstract":"

Returns whether the instance is .invalidURL.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isParameterEncodingErrorSbvp":{"name":"isParameterEncodingError","abstract":"

Returns whether the instance is .parameterEncodingFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isParameterEncoderErrorSbvp":{"name":"isParameterEncoderError","abstract":"

Returns whether the instance is .parameterEncoderFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isMultipartEncodingErrorSbvp":{"name":"isMultipartEncodingError","abstract":"

Returns whether the instance is .multipartEncodingFailed. When true, the url and underlyingError","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO24isRequestAdaptationErrorSbvp":{"name":"isRequestAdaptationError","abstract":"

Returns whether the instance is .requestAdaptationFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isResponseValidationErrorSbvp":{"name":"isResponseValidationError","abstract":"

Returns whether the instance is .responseValidationFailed. When true, the acceptableContentTypes,","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO28isResponseSerializationErrorSbvp":{"name":"isResponseSerializationError","abstract":"

Returns whether the instance is .responseSerializationFailed. When true, the failedStringEncoding and","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO28isServerTrustEvaluationErrorSbvp":{"name":"isServerTrustEvaluationError","abstract":"

Returns whether the instance is .serverTrustEvaluationFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19isRequestRetryErrorSbvp":{"name":"isRequestRetryError","abstract":"

Returns whether the instance is requestRetryFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isCreateUploadableErrorSbvp":{"name":"isCreateUploadableError","abstract":"

Returns whether the instance is createUploadableFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO23isCreateURLRequestErrorSbvp":{"name":"isCreateURLRequestError","abstract":"

Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO25isDownloadedFileMoveErrorSbvp":{"name":"isDownloadedFileMoveError","abstract":"

Returns whether the instance is downloadedFileMoveFailed. When true, the destination and underlyingError properties will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO18isSessionTaskErrorSbvp":{"name":"isSessionTaskError","abstract":"

Returns whether the instance is createURLRequestFailed. When true, the underlyingError property will","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO14urlConvertibleAA14URLConvertible_pSgvp":{"name":"urlConvertible","abstract":"

The URLConvertible associated with the error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO3url10Foundation3URLVSgvp":{"name":"url","abstract":"

The URL associated with the error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO15underlyingErrors0D0_pSgvp":{"name":"underlyingError","abstract":"

The underlying Error responsible for generating the failure associated with .sessionInvalidated,","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO22acceptableContentTypesSaySSGSgvp":{"name":"acceptableContentTypes","abstract":"

The acceptable Content-Types of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO19responseContentTypeSSSgvp":{"name":"responseContentType","abstract":"

The response Content-Type of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO12responseCodeSiSgvp":{"name":"responseCode","abstract":"

The response code of a .responseValidationFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO20failedStringEncodingSS10FoundationE0E0VSgvp":{"name":"failedStringEncoding","abstract":"

The String.Encoding associated with a failed .stringResponse() call.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO9sourceURL10Foundation0D0VSgvp":{"name":"sourceURL","abstract":"

The source URL of a .downloadedFileMoveFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:9Alamofire7AFErrorO14destinationURL10Foundation0D0VSgvp":{"name":"destinationURL","abstract":"

The destination URL of a .downloadedFileMoveFailed error.

","parent_name":"AFError"},"Enums/AFError.html#/s:10Foundation14LocalizedErrorP16errorDescriptionSSSgvp":{"name":"errorDescription","parent_name":"AFError"},"Enums/AFError.html":{"name":"AFError","abstract":"

AFError is the error type returned by Alamofire. It encompasses a few different types of errors, each with"},"Enums/AF.html":{"name":"AF","abstract":"

Global namespace containing API for the default Session instance.

"},"Enums/RetryResult.html":{"name":"RetryResult","abstract":"

Outcome of determination whether retry is necessary.

"},"Classes/URLEncodedFormEncoder/Error.html#/s:9Alamofire21URLEncodedFormEncoderC5ErrorO17invalidRootObjectyAESScAEmF":{"name":"invalidRootObject(_:)","abstract":"

An invalid root object was created by the encoder. Only keyed values are valid.

","parent_name":"Error"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13SpaceEncodingO14percentEscapedyA2EmF":{"name":"percentEscaped","abstract":"

Encodes spaces according to normal percent escaping rules (%20).

","parent_name":"SpaceEncoding"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13SpaceEncodingO12plusReplacedyA2EmF":{"name":"plusReplaced","abstract":"

Encodes spaces as +,

","parent_name":"SpaceEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO14useDefaultKeysyA2EmF":{"name":"useDefaultKeys","abstract":"

Use the keys specified by each type. This is the default encoding.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO18convertToSnakeCaseyA2EmF":{"name":"convertToSnakeCase","abstract":"

Convert from camelCaseKeys to snake_case_keys before writing a key.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO18convertToKebabCaseyA2EmF":{"name":"convertToKebabCase","abstract":"

Same as convertToSnakeCase, but using - instead of _.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO11capitalizedyA2EmF":{"name":"capitalized","abstract":"

Capitalize the first letter only.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO10uppercasedyA2EmF":{"name":"uppercased","abstract":"

Uppercase all letters.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO10lowercasedyA2EmF":{"name":"lowercased","abstract":"

Lowercase all letters.","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/KeyEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC11KeyEncodingO6customyAES2SccAEmF":{"name":"custom(_:)","abstract":"

A custom encoding using the provided closure.

","parent_name":"KeyEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO010deferredToE0yA2EmF":{"name":"deferredToDate","abstract":"

Defers encoding to the Date type. This is the default encoding.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO16secondsSince1970yA2EmF":{"name":"secondsSince1970","abstract":"

Encodes Dates as seconds since midnight UTC on January 1, 1970.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO21millisecondsSince1970yA2EmF":{"name":"millisecondsSince1970","abstract":"

Encodes Dates as milliseconds since midnight UTC on January 1, 1970.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO7iso8601yA2EmF":{"name":"iso8601","abstract":"

Encodes Dates according to the ISO8601 and RFC3339 standards.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO9formattedyAESo15NSDateFormatterCcAEmF":{"name":"formatted(_:)","abstract":"

Encodes Dates using the given DateFormatter.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DateEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DateEncodingO6customyAESS10Foundation0E0VKccAEmF":{"name":"custom(_:)","abstract":"

Encodes Dates using the given closure.

","parent_name":"DateEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO010deferredToE0yA2EmF":{"name":"deferredToData","abstract":"

Defers encoding to the Data type.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO6base64yA2EmF":{"name":"base64","abstract":"

Encodes Data as a Base64-encoded string. This is the default encoding.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/DataEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12DataEncodingO6customyAESS10Foundation0E0VKccAEmF":{"name":"custom(_:)","abstract":"

Encode the Data as a custom value encoded by the given closure.

","parent_name":"DataEncoding"},"Classes/URLEncodedFormEncoder/BoolEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12BoolEncodingO7numericyA2EmF":{"name":"numeric","abstract":"

Encodes true as 1, false as 0.

","parent_name":"BoolEncoding"},"Classes/URLEncodedFormEncoder/BoolEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC12BoolEncodingO7literalyA2EmF":{"name":"literal","abstract":"

Encodes true as true, false as false. This is the default encoding.

","parent_name":"BoolEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13ArrayEncodingO8bracketsyA2EmF":{"name":"brackets","abstract":"

An empty set of square brackets ([]) are appended to the key for every value. This is the default encoding.

","parent_name":"ArrayEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html#/s:9Alamofire21URLEncodedFormEncoderC13ArrayEncodingO10noBracketsyA2EmF":{"name":"noBrackets","abstract":"

No brackets are appended to the key and the key is encoded as is.

","parent_name":"ArrayEncoding"},"Classes/URLEncodedFormEncoder/ArrayEncoding.html":{"name":"ArrayEncoding","abstract":"

Encoding to use for Array values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/BoolEncoding.html":{"name":"BoolEncoding","abstract":"

Encoding to use for Bool values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/DataEncoding.html":{"name":"DataEncoding","abstract":"

Encoding to use for Data values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/DateEncoding.html":{"name":"DateEncoding","abstract":"

Encoding to use for Date values.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/KeyEncoding.html":{"name":"KeyEncoding","abstract":"

Encoding to use for keys.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/SpaceEncoding.html":{"name":"SpaceEncoding","abstract":"

Encoding to use for spaces.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder/Error.html":{"name":"Error","abstract":"

URLEncodedFormEncoder error.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC24alphabetizeKeyValuePairsSbvp":{"name":"alphabetizeKeyValuePairs","abstract":"

Whether or not to sort the encoded key value pairs.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC13arrayEncodingAC05ArrayF0Ovp":{"name":"arrayEncoding","abstract":"

The ArrayEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12boolEncodingAC04BoolF0Ovp":{"name":"boolEncoding","abstract":"

The BoolEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12dataEncodingAC04DataF0Ovp":{"name":"dataEncoding","abstract":"

THe DataEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC12dateEncodingAC04DateF0Ovp":{"name":"dateEncoding","abstract":"

The DateEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC11keyEncodingAC03KeyF0Ovp":{"name":"keyEncoding","abstract":"

The KeyEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC13spaceEncodingAC05SpaceF0Ovp":{"name":"spaceEncoding","abstract":"

The SpaceEncoding to use.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC17allowedCharacters10Foundation12CharacterSetVvp":{"name":"allowedCharacters","abstract":"

The CharacterSet of allowed (non-escaped) characters.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC24alphabetizeKeyValuePairs13arrayEncoding04boolJ004dataJ004dateJ003keyJ005spaceJ017allowedCharactersACSb_AC05ArrayJ0OAC04BoolJ0OAC04DataJ0OAC04DateJ0OAC0fJ0OAC05SpaceJ0O10Foundation12CharacterSetVtcfc":{"name":"init(alphabetizeKeyValuePairs:arrayEncoding:boolEncoding:dataEncoding:dateEncoding:keyEncoding:spaceEncoding:allowedCharacters:)","abstract":"

Creates an instance from the supplied parameters.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC6encodeySSSE_pKF":{"name":"encode(_:)","abstract":"

Encodes the value as a URL form encoded String.

","parent_name":"URLEncodedFormEncoder"},"Classes/URLEncodedFormEncoder.html#/s:9Alamofire21URLEncodedFormEncoderC6encodey10Foundation4DataVSE_pKF":{"name":"encode(_:)","abstract":"

Encodes the value as Data. This is performed by first creating an encoded String and then returning the","parent_name":"URLEncodedFormEncoder"},"Classes/SessionDelegate.html#/s:9Alamofire15SessionDelegateC11fileManagerACSo06NSFileE0C_tcfc":{"name":"init(fileManager:)","abstract":"

Creates an instance from the given FileManager.

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:didBecomeInvalidWithError:":{"name":"urlSession(_:didBecomeInvalidWithError:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didReceiveChallenge:completionHandler:":{"name":"urlSession(_:task:didReceive:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:needNewBodyStream:":{"name":"urlSession(_:task:needNewBodyStream:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didFinishCollectingMetrics:":{"name":"urlSession(_:task:didFinishCollecting:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:task:didCompleteWithError:":{"name":"urlSession(_:task:didCompleteWithError:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:taskIsWaitingForConnectivity:":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:dataTask:didReceiveData:":{"name":"urlSession(_:dataTask:didReceive:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:dataTask:willCacheResponse:completionHandler:":{"name":"urlSession(_:dataTask:willCacheResponse:completionHandler:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/SessionDelegate.html#/c:@CM@Alamofire@objc(cs)SessionDelegate(im)URLSession:downloadTask:didFinishDownloadingToURL:":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","abstract":"

Undocumented

","parent_name":"SessionDelegate"},"Classes/Session.html#/s:9Alamofire7SessionC7defaultACvpZ":{"name":"default","abstract":"

Shared singleton instance used by all AF.request APIs. Cannot be modified.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7sessionSo12NSURLSessionCvp":{"name":"session","abstract":"

Underlying URLSession used to create URLSessionTasks for this instance, and for which this instance’s","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8delegateAA0B8DelegateCvp":{"name":"delegate","abstract":"

Instance’s SessionDelegate, which handles the URLSessionDelegate methods and Request interaction.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC9rootQueueSo17OS_dispatch_queueCvp":{"name":"rootQueue","abstract":"

Root DispatchQueue for all internal callbacks and state update. MUST be a serial queue.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC24startRequestsImmediatelySbvp":{"name":"startRequestsImmediately","abstract":"

Value determining whether this instance automatically calls resume() on all created Requests.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC12requestQueueSo17OS_dispatch_queueCvp":{"name":"requestQueue","abstract":"

DispatchQueue on which URLRequests are created asynchronously. By default this queue uses rootQueue as its","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC18serializationQueueSo17OS_dispatch_queueCvp":{"name":"serializationQueue","abstract":"

DispatchQueue passed to all Requests on which they perform their response serialization. By default this","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC11interceptorAA18RequestInterceptor_pSgvp":{"name":"interceptor","abstract":"

RequestInterceptor used for all Request created by the instance. RequestInterceptors can also be set on a","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC18serverTrustManagerAA06ServerdE0CSgvp":{"name":"serverTrustManager","abstract":"

ServerTrustManager instance used to evaluate all trust challenges and provide certificate and key pinning.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC15redirectHandlerAA08RedirectD0_pSgvp":{"name":"redirectHandler","abstract":"

RedirectHandler instance used to provide customization for request redirection.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC21cachedResponseHandlerAA06CacheddE0_pSgvp":{"name":"cachedResponseHandler","abstract":"

CachedResponseHandler instance used to provide customization of cached response handling.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC12eventMonitorAA014CompositeEventD0Cvp":{"name":"eventMonitor","abstract":"

CompositeEventMonitor used to compose Alamofire’s defaultEventMonitors and any passed EventMonitors.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC20defaultEventMonitorsSayAA0D7Monitor_pGvp":{"name":"defaultEventMonitors","abstract":"

EventMonitors included in all instances. [AlamofireNotifications()] by default.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7session8delegate9rootQueue24startRequestsImmediately07requestF0013serializationF011interceptor18serverTrustManager15redirectHandler014cachedResponseQ013eventMonitorsACSo12NSURLSessionC_AA0B8DelegateCSo17OS_dispatch_queueCSbATSgAuA18RequestInterceptor_pSgAA06ServernO0CSgAA08RedirectQ0_pSgAA06CachedsQ0_pSgSayAA12EventMonitor_pGtcfc":{"name":"init(session:delegate:rootQueue:startRequestsImmediately:requestQueue:serializationQueue:interceptor:serverTrustManager:redirectHandler:cachedResponseHandler:eventMonitors:)","abstract":"

Creates a Session from a URLSession and other parameters.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC13configuration8delegate9rootQueue24startRequestsImmediately07requestF0013serializationF011interceptor18serverTrustManager15redirectHandler014cachedResponseQ013eventMonitorsACSo25NSURLSessionConfigurationC_AA0B8DelegateCSo17OS_dispatch_queueCSbATSgAuA18RequestInterceptor_pSgAA06ServernO0CSgAA08RedirectQ0_pSgAA06CachedsQ0_pSgSayAA12EventMonitor_pGtcfc":{"name":"init(configuration:delegate:rootQueue:startRequestsImmediately:requestQueue:serializationQueue:interceptor:serverTrustManager:redirectHandler:cachedResponseHandler:eventMonitors:)","abstract":"

Creates a Session from a URLSessionConfiguration.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC17cancelAllRequests17completingOnQueue10completionySo17OS_dispatch_queueC_yycSgtF":{"name":"cancelAllRequests(completingOnQueue:completion:)","abstract":"

Cancel all active Requests, optionally calling a completion handler when complete.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_6method10parameters8encoding7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtF":{"name":"request(_:method:parameters:encoding:headers:interceptor:)","abstract":"

Creates a DataRequest from a URLRequest created using the passed components and a RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_6method10parameters7encoder7headers11interceptorAA11DataRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0J11Interceptor_pSgtSERzlF":{"name":"request(_:method:parameters:encoder:headers:interceptor:)","abstract":"

Creates a DataRequest from a URLRequest created using the passed components, Encodable parameters, and a","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC7request_11interceptorAA11DataRequestCAA21URLRequestConvertible_p_AA0F11Interceptor_pSgtF":{"name":"request(_:interceptor:)","abstract":"

Creates a DataRequest from a URLRequestConvertible value and a RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_6method10parameters8encoding7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVSDySSypGSgAA17ParameterEncoding_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAZ_So17NSHTTPURLResponseCtcSgtF":{"name":"download(_:method:parameters:encoding:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest using a URLRequest created using the passed components, RequestInterceptor, and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_6method10parameters7encoder7headers11interceptor2toAA15DownloadRequestCAA14URLConvertible_p_AA10HTTPMethodVxSgAA16ParameterEncoder_pAA11HTTPHeadersVSgAA0K11Interceptor_pSg10Foundation3URLV011destinationS0_AL7OptionsV7optionstAY_So17NSHTTPURLResponseCtcSgtSERzlF":{"name":"download(_:method:parameters:encoder:headers:interceptor:to:)","abstract":"

Creates a DownloadRequest from a URLRequest created using the passed components, Encodable parameters, and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download_11interceptor2toAA15DownloadRequestCAA21URLRequestConvertible_p_AA0G11Interceptor_pSg10Foundation3URLV011destinationL0_AH7OptionsV7optionstAN_So17NSHTTPURLResponseCtcSgtF":{"name":"download(_:interceptor:to:)","abstract":"

Creates a DownloadRequest from a URLRequestConvertible value, a RequestInterceptor, and a Destination.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC8download12resumingWith11interceptor2toAA15DownloadRequestC10Foundation4DataV_AA0I11Interceptor_pSgAJ3URLV011destinationM0_AI7OptionsV7optionstAP_So17NSHTTPURLResponseCtcSgtF":{"name":"download(resumingWith:interceptor:to:)","abstract":"

Creates a DownloadRequest from the resumeData produced from a previously cancelled DownloadRequest, as","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data, URLRequest components, and RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation4DataV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the given Data using the URLRequestConvertible value and RequestInterceptor.

","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL, using a URLRequest from the provided","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestC10Foundation3URLV_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the file at the given file URL using the URLRequestConvertible value and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_2to6method7headers11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA14URLConvertible_pAA10HTTPMethodVAA11HTTPHeadersVSgAA0K11Interceptor_pSgSo06NSFileI0CtF":{"name":"upload(_:to:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the InputStream provided using a URLRequest from the provided components and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload_4with11interceptor11fileManagerAA13UploadRequestCSo13NSInputStreamC_AA21URLRequestConvertible_pAA0I11Interceptor_pSgSo06NSFileG0CtF":{"name":"upload(_:with:interceptor:fileManager:)","abstract":"

Creates an UploadRequest from the provided InputStream using the URLRequestConvertible value and","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtF":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the multipart form data built using a closure and sent using the provided","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCyAA09MultiparteF0Cc_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtF":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest using a MultipartFormData building closure, the provided URLRequestConvertible","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData2to14usingThreshold6method7headers11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA14URLConvertible_ps6UInt64VAA10HTTPMethodVAA11HTTPHeadersVSgAA0P11Interceptor_pSgSo06NSFileN0CtF":{"name":"upload(multipartFormData:to:usingThreshold:method:headers:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the provided URLRequest components","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire7SessionC6upload17multipartFormData4with14usingThreshold11interceptor11fileManagerAA13UploadRequestCAA09MultiparteF0C_AA21URLRequestConvertible_ps6UInt64VAA0N11Interceptor_pSgSo06NSFileL0CtF":{"name":"upload(multipartFormData:with:usingThreshold:interceptor:fileManager:)","abstract":"

Creates an UploadRequest for the prebuilt MultipartFormData value using the providing URLRequestConvertible","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP20sessionConfigurationSo012NSURLSessionE0Cvp":{"name":"sessionConfiguration","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP16startImmediatelySbvp":{"name":"startImmediately","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP7cleanup5afteryAA0B0C_tF":{"name":"cleanup(after:)","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP11retryResult3for5dueTo10completionyAA0B0C_AA7AFErrorOyAA05RetryE0OctF":{"name":"retryResult(for:dueTo:completion:)","parent_name":"Session"},"Classes/Session.html#/s:9Alamofire15RequestDelegateP05retryB0_9withDelayyAA0B0C_SdSgtF":{"name":"retryRequest(_:withDelay:)","parent_name":"Session"},"Classes/DisabledEvaluator.html#/s:9Alamofire17DisabledEvaluatorCACycfc":{"name":"init()","abstract":"

Creates an instance.

","parent_name":"DisabledEvaluator"},"Classes/DisabledEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"DisabledEvaluator"},"Classes/CompositeTrustEvaluator.html#/s:9Alamofire23CompositeTrustEvaluatorC10evaluatorsACSayAA06ServerC10Evaluating_pG_tcfc":{"name":"init(evaluators:)","abstract":"

Creates a CompositeTrustEvaluator.

","parent_name":"CompositeTrustEvaluator"},"Classes/CompositeTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"CompositeTrustEvaluator"},"Classes/PublicKeysTrustEvaluator.html#/s:9Alamofire24PublicKeysTrustEvaluatorC4keys24performDefaultValidation12validateHostACSaySo9SecKeyRefaG_S2btcfc":{"name":"init(keys:performDefaultValidation:validateHost:)","abstract":"

Creates a PublicKeysTrustEvaluator.

","parent_name":"PublicKeysTrustEvaluator"},"Classes/PublicKeysTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"PublicKeysTrustEvaluator"},"Classes/PinnedCertificatesTrustEvaluator.html#/s:9Alamofire32PinnedCertificatesTrustEvaluatorC12certificates016acceptSelfSignedC024performDefaultValidation12validateHostACSaySo17SecCertificateRefaG_S3btcfc":{"name":"init(certificates:acceptSelfSignedCertificates:performDefaultValidation:validateHost:)","abstract":"

Creates a PinnedCertificatesTrustEvaluator.

","parent_name":"PinnedCertificatesTrustEvaluator"},"Classes/PinnedCertificatesTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"PinnedCertificatesTrustEvaluator"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV3crlAEvpZ":{"name":"crl","abstract":"

Perform revocation checking using the CRL (Certification Revocation List) method.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV21networkAccessDisabledAEvpZ":{"name":"networkAccessDisabled","abstract":"

Consult only locally cached replies; do not use network access.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV4ocspAEvpZ":{"name":"ocsp","abstract":"

Perform revocation checking using OCSP (Online Certificate Status Protocol).

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV9preferCRLAEvpZ":{"name":"preferCRL","abstract":"

Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV23requirePositiveResponseAEvpZ":{"name":"requirePositiveResponse","abstract":"

Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV3anyAEvpZ":{"name":"any","abstract":"

Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV8rawValueSuvp":{"name":"rawValue","abstract":"

The raw value of the option.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html#/s:9Alamofire24RevocationTrustEvaluatorC7OptionsV8rawValueAESu_tcfc":{"name":"init(rawValue:)","abstract":"

Creates an Options value with the given CFOptionFlags.

","parent_name":"Options"},"Classes/RevocationTrustEvaluator/Options.html":{"name":"Options","abstract":"

Represents the options to be use when evaluating the status of a certificate.","parent_name":"RevocationTrustEvaluator"},"Classes/RevocationTrustEvaluator.html#/s:9Alamofire24RevocationTrustEvaluatorC24performDefaultValidation12validateHost7optionsACSb_SbAC7OptionsVtcfc":{"name":"init(performDefaultValidation:validateHost:options:)","abstract":"

Creates a RevocationTrustEvaluator.

","parent_name":"RevocationTrustEvaluator"},"Classes/RevocationTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"RevocationTrustEvaluator"},"Classes/DefaultTrustEvaluator.html#/s:9Alamofire21DefaultTrustEvaluatorC12validateHostACSb_tcfc":{"name":"init(validateHost:)","abstract":"

Creates a DefaultTrustEvaluator.

","parent_name":"DefaultTrustEvaluator"},"Classes/DefaultTrustEvaluator.html#/s:9Alamofire21ServerTrustEvaluatingP8evaluate_7forHostySo03SecC3Refa_SStKF":{"name":"evaluate(_:forHost:)","parent_name":"DefaultTrustEvaluator"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC23allHostsMustBeEvaluatedSbvp":{"name":"allHostsMustBeEvaluated","abstract":"

Determines whether all hosts for this ServerTrustManager must be evaluated. true by default.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC10evaluatorsSDySSAA0bC10Evaluating_pGvp":{"name":"evaluators","abstract":"

The dictionary of policies mapped to a particular host.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC23allHostsMustBeEvaluated10evaluatorsACSb_SDySSAA0bC10Evaluating_pGtcfc":{"name":"init(allHostsMustBeEvaluated:evaluators:)","abstract":"

Initializes the ServerTrustManager instance with the given evaluators.

","parent_name":"ServerTrustManager"},"Classes/ServerTrustManager.html#/s:9Alamofire18ServerTrustManagerC06serverC9Evaluator7forHostAA0bC10Evaluating_pSgSS_tKF":{"name":"serverTrustEvaluator(forHost:)","abstract":"

Returns the ServerTrustEvaluating value for the given host, if one is set.

","parent_name":"ServerTrustManager"},"Classes/ConnectionLostRetryPolicy.html#/s:9Alamofire25ConnectionLostRetryPolicyC10retryLimit22exponentialBackoffBase0hI5Scale20retryableHTTPMethodsACSu_SuSdShyAA10HTTPMethodVGtcfc":{"name":"init(retryLimit:exponentialBackoffBase:exponentialBackoffScale:retryableHTTPMethods:)","abstract":"

Creates a ConnectionLostRetryPolicy instance from the specified parameters.

","parent_name":"ConnectionLostRetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC07defaultB5LimitSuvpZ":{"name":"defaultRetryLimit","abstract":"

The default retry limit for retry policies.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC29defaultExponentialBackoffBaseSuvpZ":{"name":"defaultExponentialBackoffBase","abstract":"

The default exponential backoff base for retry policies (must be a minimum of 2).

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC30defaultExponentialBackoffScaleSdvpZ":{"name":"defaultExponentialBackoffScale","abstract":"

The default exponential backoff scale for retry policies.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC27defaultRetryableHTTPMethodsShyAA10HTTPMethodVGvpZ":{"name":"defaultRetryableHTTPMethods","abstract":"

The default HTTP methods to retry.","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC31defaultRetryableHTTPStatusCodesShySiGvpZ":{"name":"defaultRetryableHTTPStatusCodes","abstract":"

The default HTTP status codes to retry.","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC29defaultRetryableURLErrorCodesShy10Foundation0F0V4CodeVGvpZ":{"name":"defaultRetryableURLErrorCodes","abstract":"

The default URL error codes to retry.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC10retryLimitSuvp":{"name":"retryLimit","abstract":"

The total number of times the request is allowed to be retried.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC22exponentialBackoffBaseSuvp":{"name":"exponentialBackoffBase","abstract":"

The base of the exponential backoff policy (should always be greater than or equal to 2).

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC23exponentialBackoffScaleSdvp":{"name":"exponentialBackoffScale","abstract":"

The scale of the exponential backoff.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC20retryableHTTPMethodsShyAA10HTTPMethodVGvp":{"name":"retryableHTTPMethods","abstract":"

The HTTP methods that are allowed to be retried.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC24retryableHTTPStatusCodesShySiGvp":{"name":"retryableHTTPStatusCodes","abstract":"

The HTTP status codes that are automatically retried by the policy.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC22retryableURLErrorCodesShy10Foundation0E0V4CodeVGvp":{"name":"retryableURLErrorCodes","abstract":"

The URL error codes that are automatically retried by the policy.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire11RetryPolicyC10retryLimit22exponentialBackoffBase0fG5Scale20retryableHTTPMethods0J15HTTPStatusCodes0j8URLErrorM0ACSu_SuSdShyAA10HTTPMethodVGShySiGShy10Foundation0N0V4CodeVGtcfc":{"name":"init(retryLimit:exponentialBackoffBase:exponentialBackoffScale:retryableHTTPMethods:retryableHTTPStatusCodes:retryableURLErrorCodes:)","abstract":"

Creates an ExponentialBackoffRetryPolicy from the specified parameters.

","parent_name":"RetryPolicy"},"Classes/RetryPolicy.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"RetryPolicy"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire27DecodableResponseSerializerC7decoderAA11DataDecoder_pvp":{"name":"decoder","abstract":"

The DataDecoder instance used to decode responses.

","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire27DecodableResponseSerializerC16dataPreprocessor7decoder05emptyC5Codes0H14RequestMethodsACyxGAA04DataF0_p_AA0L7Decoder_pShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:decoder:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance using the values provided.

","parent_name":"DecodableResponseSerializer"},"Classes/DecodableResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"DecodableResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire22JSONResponseSerializerC7optionsSo20NSJSONReadingOptionsVvp":{"name":"options","abstract":"

JSONSerialization.ReadingOptions used when serializing a response.

","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire22JSONResponseSerializerC16dataPreprocessor18emptyResponseCodes0F14RequestMethods7optionsAcA04DataE0_p_ShySiGShyAA10HTTPMethodVGSo20NSJSONReadingOptionsVtcfc":{"name":"init(dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:)","abstract":"

Creates an instance with the provided values.

","parent_name":"JSONResponseSerializer"},"Classes/JSONResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"JSONResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire24StringResponseSerializerC8encodingSS10FoundationE8EncodingVSgvp":{"name":"encoding","abstract":"

Optional string encoding used to validate the response.

","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire24StringResponseSerializerC16dataPreprocessor8encoding05emptyC5Codes0H14RequestMethodsAcA04DataF0_p_SS10FoundationE8EncodingVSgShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:encoding:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance with the provided values.

","parent_name":"StringResponseSerializer"},"Classes/StringResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"StringResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP16dataPreprocessorAA04DataE0_pvp":{"name":"dataPreprocessor","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP05emptyB5CodesShySiGvp":{"name":"emptyResponseCodes","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire18ResponseSerializerP19emptyRequestMethodsShyAA10HTTPMethodVGvp":{"name":"emptyRequestMethods","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire22DataResponseSerializerC16dataPreprocessor05emptyC5Codes0G14RequestMethodsAcA0bF0_p_ShySiGShyAA10HTTPMethodVGtcfc":{"name":"init(dataPreprocessor:emptyResponseCodes:emptyRequestMethods:)","abstract":"

Creates an instance using the provided values.

","parent_name":"DataResponseSerializer"},"Classes/DataResponseSerializer.html#/s:9Alamofire30DataResponseSerializerProtocolP9serialize7request8response4data5error16SerializedObjectQz10Foundation10URLRequestVSg_So17NSHTTPURLResponseCSgAK0B0VSgs5Error_pSgtKF":{"name":"serialize(request:response:data:error:)","parent_name":"DataResponseSerializer"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8adaptersSayAA14RequestAdapter_pGvp":{"name":"adapters","abstract":"

All RequestAdapters associated with the instance. These adapters will be run until one fails.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8retriersSayAA14RequestRetrier_pGvp":{"name":"retriers","abstract":"

All RequestRetriers associated with the instance. These retriers will be run one at a time until one triggers retry.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC12adaptHandler05retryD0ACy10Foundation10URLRequestV_AA7SessionCys6ResultOyAHs5Error_pGctc_yAA7RequestC_AJsAM_pyAA05RetryI0Octctcfc":{"name":"init(adaptHandler:retryHandler:)","abstract":"

Creates an instance from AdaptHandler and RetryHandler closures.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC7adapter7retrierAcA14RequestAdapter_p_AA0E7Retrier_ptcfc":{"name":"init(adapter:retrier:)","abstract":"

Creates an instance from RequestAdapter and RequestRetrier values.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire11InterceptorC8adapters8retriersACSayAA14RequestAdapter_pG_SayAA0E7Retrier_pGtcfc":{"name":"init(adapters:retriers:)","abstract":"

Creates an instance from the arrays of RequestAdapter and RequestRetrier values.

","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"Interceptor"},"Classes/Interceptor.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"Interceptor"},"Classes/Retrier.html#/s:9Alamofire7RetrierCyACyAA7RequestC_AA7SessionCs5Error_pyAA11RetryResultOctccfc":{"name":"init(_:)","abstract":"

Creates an instance using the provided closure.

","parent_name":"Retrier"},"Classes/Retrier.html#/s:9Alamofire14RequestRetrierP5retry_3for5dueTo10completionyAA0B0C_AA7SessionCs5Error_pyAA11RetryResultOctF":{"name":"retry(_:for:dueTo:completion:)","parent_name":"Retrier"},"Classes/Adapter.html#/s:9Alamofire7AdapterCyACy10Foundation10URLRequestV_AA7SessionCys6ResultOyAFs5Error_pGctccfc":{"name":"init(_:)","abstract":"

Creates an instance using the provided closure.

","parent_name":"Adapter"},"Classes/Adapter.html#/s:9Alamofire14RequestAdapterP5adapt_3for10completiony10Foundation10URLRequestV_AA7SessionCys6ResultOyAIs5Error_pGctF":{"name":"adapt(_:for:completion:)","parent_name":"Adapter"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO4datayAE10Foundation4DataVcAEmF":{"name":"data(_:)","abstract":"

Upload from the provided Data value.

","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO4fileyAE10Foundation3URLV_SbtcAEmF":{"name":"file(_:shouldRemove:)","abstract":"

Upload from the provided file URL, as well as a Bool determining whether the source file should be","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire13UploadRequestC10UploadableO6streamyAESo13NSInputStreamCcAEmF":{"name":"stream(_:)","abstract":"

Upload from the provided InputStream.

","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html#/s:9Alamofire21UploadableConvertibleP06createB0AA13UploadRequestC0B0OyKF":{"name":"createUploadable()","parent_name":"Uploadable"},"Classes/UploadRequest/Uploadable.html":{"name":"Uploadable","abstract":"

Type describing the origin of the upload, whether Data, file, or stream.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC6uploadAA21UploadableConvertible_pvp":{"name":"upload","abstract":"

The UploadableConvertible value used to produce the Uploadable value for this instance.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC11fileManagerSo06NSFileE0Cvp":{"name":"fileManager","abstract":"

FileManager used to perform cleanup tasks, including the removal of multipart form encoded payloads written","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC10uploadableAC10UploadableOSgvp":{"name":"uploadable","abstract":"

Uploadable value used by the instance.

","parent_name":"UploadRequest"},"Classes/UploadRequest.html#/s:9Alamofire13UploadRequestC7cleanupyyF":{"name":"cleanup()","parent_name":"UploadRequest"},"Classes/DownloadRequest/Downloadable.html#/s:9Alamofire15DownloadRequestC12DownloadableO7requestyAeA21URLRequestConvertible_pcAEmF":{"name":"request(_:)","abstract":"

Download should be started from the URLRequest produced by the associated URLRequestConvertible value.

","parent_name":"Downloadable"},"Classes/DownloadRequest/Downloadable.html#/s:9Alamofire15DownloadRequestC12DownloadableO10resumeDatayAE10Foundation0F0VcAEmF":{"name":"resumeData(_:)","abstract":"

Download should be started from the associated resume Data value.

","parent_name":"Downloadable"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV29createIntermediateDirectoriesAEvpZ":{"name":"createIntermediateDirectories","abstract":"

Specifies that intermediate directories for the destination URL should be created.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV18removePreviousFileAEvpZ":{"name":"removePreviousFile","abstract":"

Specifies that any previous file at the destination URL should be removed.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:9Alamofire15DownloadRequestC7OptionsV8rawValueSivp":{"name":"rawValue","abstract":"

Returns the raw bitmask value of the option and satisfies the RawRepresentable protocol.

","parent_name":"Options"},"Classes/DownloadRequest/Options.html#/s:s9OptionSetP8rawValuex03RawD0Qz_tcfc":{"name":"init(rawValue:)","parent_name":"Options"},"Classes/DownloadRequest/Options.html":{"name":"Options","abstract":"

A set of options to be executed prior to moving a downloaded file from the temporary URL to the destination","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC11Destinationa":{"name":"Destination","abstract":"

A closure executed once a download request has successfully completed in order to determine where to move the","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC09suggestedB11Destination3for2in7options10Foundation3URLV011destinationJ0_AC7OptionsVAGtAJ_So17NSHTTPURLResponseCtcSo21NSSearchPathDirectoryV_So0nO10DomainMaskVAMtFZ":{"name":"suggestedDownloadDestination(for:in:options:)","abstract":"

Creates a download file destination closure which uses the default file manager to move the temporary file to a","parent_name":"DownloadRequest"},"Classes/DownloadRequest/Downloadable.html":{"name":"Downloadable","abstract":"

Type describing the source used to create the underlying URLSessionDownloadTask.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC10resumeData10Foundation0E0VSgvp":{"name":"resumeData","abstract":"

If the download is resumable and eventually cancelled, this value may be used to resume the download using the","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC7fileURL10Foundation0E0VSgvp":{"name":"fileURL","abstract":"

If the download is successful, the URL where the file was downloaded.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12downloadableAC12DownloadableOvp":{"name":"downloadable","abstract":"

Downloadable value used for this instance.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC4task13forResumeData5usingSo16NSURLSessionTaskC10Foundation0G0V_So0I0CtF":{"name":"task(forResumeData:using:)","abstract":"

Creates a URLSessionTask from the provided resume data.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancelACXDyF":{"name":"cancel()","abstract":"

Cancels the instance. Once cancelled, a DownloadRequest can no longer be resumed or suspended.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancel19producingResumeDataACXDSb_tF":{"name":"cancel(producingResumeData:)","abstract":"

Cancels the instance, optionally producing resume data. Once cancelled, a DownloadRequest can no longer be","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC6cancel21byProducingResumeDataACXDy10Foundation0H0VSgc_tF":{"name":"cancel(byProducingResumeData:)","abstract":"

Cancels the instance while producing resume data. Once cancelled, a DownloadRequest can no longer be resumed","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validateyACXDs6ResultOyyts5Error_pG10Foundation10URLRequestVSg_So17NSHTTPURLResponseCAI3URLVSgtcF":{"name":"validate(_:)","abstract":"

Validates the request, using the specified closure.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8response5queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation3URLVSgAA7AFErrorOGctF":{"name":"response(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0C_xyAA0B8ResponseVy16SerializedObjectQzAA7AFErrorOGctAA0bkF8ProtocolRzlF":{"name":"response(queue:responseSerializer:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12responseData5queue17completionHandlerACXDSo012OS_dispatch_F0C_yAA0B8ResponseVy10Foundation0E0VAA7AFErrorOGctF":{"name":"responseData(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC14responseString5queue8encoding17completionHandlerACXDSo012OS_dispatch_F0C_SS10FoundationE8EncodingVSgyAA0B8ResponseVySSAA7AFErrorOGctF":{"name":"responseString(queue:encoding:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC12responseJSON5queue7options17completionHandlerACXDSo012OS_dispatch_F0C_So20NSJSONReadingOptionsVyAA0B8ResponseVyypAA7AFErrorOGctF":{"name":"responseJSON(queue:options:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC10Validationa":{"name":"Validation","abstract":"

A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validate10statusCodeACXDx_tSTRzSi7ElementRtzlF":{"name":"validate(statusCode:)","abstract":"

Validates that the response has a status code in the specified sequence.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validate11contentTypeACXDxyXA_tSTRzSS7ElementRtzlF":{"name":"validate(contentType:)","abstract":"

Validates that the response has a content type in the specified sequence.

","parent_name":"DownloadRequest"},"Classes/DownloadRequest.html#/s:9Alamofire15DownloadRequestC8validateACXDyF":{"name":"validate()","abstract":"

Validates that the response has a status code in the default acceptable range of 200…299, and that the content","parent_name":"DownloadRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC11convertibleAA21URLRequestConvertible_pvp":{"name":"convertible","abstract":"

URLRequestConvertible value used to create URLRequests for this instance.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC4data10Foundation0B0VSgvp":{"name":"data","abstract":"

Data read from the server so far.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validateyACXDs6ResultOyyts5Error_pG10Foundation10URLRequestVSg_So17NSHTTPURLResponseCAI0B0VSgtcF":{"name":"validate(_:)","abstract":"

Validates the request, using the specified closure.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8response5queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation0B0VSgAA7AFErrorOGctF":{"name":"response(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8response5queue0D10Serializer17completionHandlerACXDSo012OS_dispatch_E0C_xyAA0B8ResponseVy16SerializedObjectQzAA7AFErrorOGctAA0bkF8ProtocolRzlF":{"name":"response(queue:responseSerializer:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC08responseB05queue17completionHandlerACXDSo012OS_dispatch_E0C_yAA0B8ResponseVy10Foundation0B0VAA7AFErrorOGctF":{"name":"responseData(queue:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC14responseString5queue8encoding17completionHandlerACXDSo012OS_dispatch_F0C_SS10FoundationE8EncodingVSgyAA0B8ResponseVySSAA7AFErrorOGctF":{"name":"responseString(queue:encoding:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC12responseJSON5queue7options17completionHandlerACXDSo012OS_dispatch_F0C_So20NSJSONReadingOptionsVyAA0B8ResponseVyypAA7AFErrorOGctF":{"name":"responseJSON(queue:options:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC17responseDecodable2of5queue7decoder17completionHandlerACXDxm_So012OS_dispatch_G0CAA0B7Decoder_pyAA0B8ResponseVyxAA7AFErrorOGctSeRzlF":{"name":"responseDecodable(of:queue:decoder:completionHandler:)","abstract":"

Adds a handler to be called once the request has finished.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC10Validationa":{"name":"Validation","abstract":"

A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validate10statusCodeACXDx_tSTRzSi7ElementRtzlF":{"name":"validate(statusCode:)","abstract":"

Validates that the response has a status code in the specified sequence.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validate11contentTypeACXDxyXA_tSTRzSS7ElementRtzlF":{"name":"validate(contentType:)","abstract":"

Validates that the response has a content type in the specified sequence.

","parent_name":"DataRequest"},"Classes/DataRequest.html#/s:9Alamofire11DataRequestC8validateACXDyF":{"name":"validate()","abstract":"

Validates that the response has a status code in the default acceptable range of 200…299, and that the content","parent_name":"DataRequest"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO15methodDependentyA2EmF":{"name":"methodDependent","abstract":"

Applies the encoded query string to any existing query string for .get, .head, and .delete request.","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO11queryStringyA2EmF":{"name":"queryString","abstract":"

Applies the encoded query string to any existing query string from the URLRequest.

","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11DestinationO8httpBodyyA2EmF":{"name":"httpBody","abstract":"

Applies the encoded query string to the httpBody of the URLRequest.

","parent_name":"Destination"},"Classes/URLEncodedFormParameterEncoder/Destination.html":{"name":"Destination","abstract":"

Defines where the URL-encoded string should be set for each URLRequest.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7defaultACvpZ":{"name":"default","abstract":"

Returns an encoder with default parameters.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7encoderAA0bcE0Cvp":{"name":"encoder","abstract":"

The URLEncodedFormEncoder to use.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC11destinationAC11DestinationOvp":{"name":"destination","abstract":"

The Destination for the URL-encoded string.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire30URLEncodedFormParameterEncoderC7encoder11destinationAcA0bcE0C_AC11DestinationOtcfc":{"name":"init(encoder:destination:)","abstract":"

Creates an instance with the provided URLEncodedFormEncoder instance and Destination value.

","parent_name":"URLEncodedFormParameterEncoder"},"Classes/URLEncodedFormParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","parent_name":"URLEncodedFormParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7defaultACvpZ":{"name":"default","abstract":"

Returns an encoder with default parameters.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC13prettyPrintedACvpZ":{"name":"prettyPrinted","abstract":"

Returns an encoder with JSONEncoder.outputFormatting set to .prettyPrinted.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC10sortedKeysACvpZ":{"name":"sortedKeys","abstract":"

Returns an encoder with JSONEncoder.outputFormatting set to .sortedKeys.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7encoder10Foundation11JSONEncoderCvp":{"name":"encoder","abstract":"

JSONEncoder used to encode parameters.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire20JSONParameterEncoderC7encoderAC10Foundation11JSONEncoderC_tcfc":{"name":"init(encoder:)","abstract":"

Creates an instance with the provided JSONEncoder.

","parent_name":"JSONParameterEncoder"},"Classes/JSONParameterEncoder.html#/s:9Alamofire16ParameterEncoderP6encode_4into10Foundation10URLRequestVqd__Sg_AHtKSERd__lF":{"name":"encode(_:into:)","parent_name":"JSONParameterEncoder"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"AlamofireNotifications"},"Classes/AlamofireNotifications.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"AlamofireNotifications"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO11initializedyA2EmF":{"name":"initialized","abstract":"

Initial state of the Request.

","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO7resumedyA2EmF":{"name":"resumed","abstract":"

State set when resume() is called. Any tasks created for the Request will have resume() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO9suspendedyA2EmF":{"name":"suspended","abstract":"

State set when suspend() is called. Any tasks created for the Request will have suspend() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO9cancelledyA2EmF":{"name":"cancelled","abstract":"

State set when cancel() is called. Any tasks created for the Request will have cancel() called on","parent_name":"State"},"Classes/Request/State.html#/s:9Alamofire7RequestC5StateO8finishedyA2EmF":{"name":"finished","abstract":"

State set when all response serialization completion closures have been cleared on the Request and","parent_name":"State"},"Classes/Request/State.html":{"name":"State","abstract":"

State of the Request, with managed transitions between states set when calling resume(), suspend(), or","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC2id10Foundation4UUIDVvp":{"name":"id","abstract":"

UUID providing a unique identifier for the Request, used in the Hashable and Equatable conformances.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15underlyingQueueSo17OS_dispatch_queueCvp":{"name":"underlyingQueue","abstract":"

The serial queue for all internal async actions.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC18serializationQueueSo17OS_dispatch_queueCvp":{"name":"serializationQueue","abstract":"

The queue used for all serialization actions. By default it’s a serial queue that targets underlyingQueue.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12eventMonitorAA05EventD0_pSgvp":{"name":"eventMonitor","abstract":"

EventMonitor used for event callbacks.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11interceptorAA0B11Interceptor_pSgvp":{"name":"interceptor","abstract":"

The Request‘s interceptor.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8delegateAA0B8Delegate_pSgvp":{"name":"delegate","abstract":"

The Request‘s delegate.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5stateAC5StateOvp":{"name":"state","abstract":"

State of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC13isInitializedSbvp":{"name":"isInitialized","abstract":"

Returns whether state is .initialized.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC9isResumedSbvp":{"name":"isResumed","abstract":"

Returns whether state is.resumed`.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11isSuspendedSbvp":{"name":"isSuspended","abstract":"

Returns whether state is .suspended.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11isCancelledSbvp":{"name":"isCancelled","abstract":"

Returns whether state is .cancelled.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10isFinishedSbvp":{"name":"isFinished","abstract":"

Returns whether state is .finished.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15ProgressHandlera":{"name":"ProgressHandler","abstract":"

Closure type executed when monitoring the upload or download progress of a request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC14uploadProgressSo10NSProgressCvp":{"name":"uploadProgress","abstract":"

Progress of the upload of the body of the executed URLRequest. Reset to 0 if the Request is retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16downloadProgressSo10NSProgressCvp":{"name":"downloadProgress","abstract":"

Progress of the download of any response data. Reset to 0 if the Request is retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15redirectHandlerAA08RedirectD0_pSgvp":{"name":"redirectHandler","abstract":"

RedirectHandler set on the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21cachedResponseHandlerAA06CacheddE0_pSgvp":{"name":"cachedResponseHandler","abstract":"

CachedResponseHandler set on the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10credentialSo15NSURLCredentialCSgvp":{"name":"credential","abstract":"

URLCredential used for authentication challenges. Created by calling one of the authenticate methods.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8requestsSay10Foundation10URLRequestVGvp":{"name":"requests","abstract":"

All URLRequests created on behalf of the Request, including original and adapted requests.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC05firstB010Foundation10URLRequestVSgvp":{"name":"firstRequest","abstract":"

First URLRequest created on behalf of the Request. May not be the first one actually executed.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC04lastB010Foundation10URLRequestVSgvp":{"name":"lastRequest","abstract":"

Last URLRequest created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7request10Foundation10URLRequestVSgvp":{"name":"request","abstract":"

Current URLRequest created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC17performedRequestsSay10Foundation10URLRequestVGvp":{"name":"performedRequests","abstract":"

URLRequests from all of the URLSessionTasks executed on behalf of the Request. May be different from","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8responseSo17NSHTTPURLResponseCSgvp":{"name":"response","abstract":"

HTTPURLResponse received from the server, if any. If the Request was retried, this is the response of the","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5tasksSaySo16NSURLSessionTaskCGvp":{"name":"tasks","abstract":"

All URLSessionTasks created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC9firstTaskSo012NSURLSessionD0CSgvp":{"name":"firstTask","abstract":"

First URLSessionTask created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8lastTaskSo012NSURLSessionD0CSgvp":{"name":"lastTask","abstract":"

Last URLSessionTask crated on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC4taskSo16NSURLSessionTaskCSgvp":{"name":"task","abstract":"

Current URLSessionTask created on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10allMetricsSaySo016NSURLSessionTaskD0CGvp":{"name":"allMetrics","abstract":"

All URLSessionTaskMetrics gathered on behalf of the Request. Should correspond to the tasks created.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12firstMetricsSo016NSURLSessionTaskD0CSgvp":{"name":"firstMetrics","abstract":"

First URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11lastMetricsSo016NSURLSessionTaskD0CSgvp":{"name":"lastMetrics","abstract":"

Last URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7metricsSo23NSURLSessionTaskMetricsCSgvp":{"name":"metrics","abstract":"

Current URLSessionTaskMetrics gathered on behalf of the Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC10retryCountSivp":{"name":"retryCount","abstract":"

Number of times the Request has been retried.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC5errorAA7AFErrorOSgvp":{"name":"error","abstract":"

Error returned from Alamofire internally, from the network request directly, or any validators executed.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC6cancelACXDyF":{"name":"cancel()","abstract":"

Cancels the instance. Once cancelled, a Request can no longer be resumed or suspended.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC7suspendACXDyF":{"name":"suspend()","abstract":"

Suspends the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC6resumeACXDyF":{"name":"resume()","abstract":"

Resumes the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12authenticate8username8password11persistenceACXDSS_SSSo26NSURLCredentialPersistenceVtF":{"name":"authenticate(username:password:persistence:)","abstract":"

Associates a credential using the provided values with the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC12authenticate4withACXDSo15NSURLCredentialC_tF":{"name":"authenticate(with:)","abstract":"

Associates the provided credential with the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16downloadProgress5queue7closureACXDSo012OS_dispatch_E0C_ySo10NSProgressCctF":{"name":"downloadProgress(queue:closure:)","abstract":"

Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC14uploadProgress5queue7closureACXDSo012OS_dispatch_E0C_ySo10NSProgressCctF":{"name":"uploadProgress(queue:closure:)","abstract":"

Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC8redirect5usingACXDAA15RedirectHandler_p_tF":{"name":"redirect(using:)","abstract":"

Sets the redirect handler for the instance which will be used if a redirect response is encountered.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC13cacheResponse5usingACXDAA06CachedD7Handler_p_tF":{"name":"cacheResponse(using:)","abstract":"

Sets the cached response handler for the Request which will be used when attempting to cache a response.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15cURLDescription7callingACXDySSc_tF":{"name":"cURLDescription(calling:)","abstract":"

Sets a handler to be called when the cURL description of the request is available.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didResumeNotificationSo18NSNotificationNameavpZ":{"name":"didResumeNotification","abstract":"

Posted when a Request is resumed. The Notification contains the resumed Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC22didSuspendNotificationSo18NSNotificationNameavpZ":{"name":"didSuspendNotification","abstract":"

Posted when a Request is suspended. The Notification contains the suspended Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didCancelNotificationSo18NSNotificationNameavpZ":{"name":"didCancelNotification","abstract":"

Posted when a Request is cancelled. The Notification contains the cancelled Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC21didFinishNotificationSo18NSNotificationNameavpZ":{"name":"didFinishNotification","abstract":"

Posted when a Request is finished. The Notification contains the completed Request.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC25didResumeTaskNotificationSo18NSNotificationNameavpZ":{"name":"didResumeTaskNotification","abstract":"

Posted when a URLSessionTask is resumed. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC26didSuspendTaskNotificationSo18NSNotificationNameavpZ":{"name":"didSuspendTaskNotification","abstract":"

Posted when a URLSessionTask is suspended. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC25didCancelTaskNotificationSo18NSNotificationNameavpZ":{"name":"didCancelTaskNotification","abstract":"

Posted when a URLSessionTask is cancelled. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC27didCompleteTaskNotificationSo18NSNotificationNameavpZ":{"name":"didCompleteTaskNotification","abstract":"

Posted when a URLSessionTask is completed. The Notification contains the Request associated with the URLSessionTask.

","parent_name":"Request"},"Classes/Request.html#/s:SQ2eeoiySbx_xtFZ":{"name":"==(_:_:)","parent_name":"Request"},"Classes/Request.html#/s:SH4hash4intoys6HasherVz_tF":{"name":"hash(into:)","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC11descriptionSSvp":{"name":"description","abstract":"

A textual representation of this instance, including the HTTPMethod and URL if the URLRequest has been","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC15cURLDescriptionSSyF":{"name":"cURLDescription()","abstract":"

cURL representation of the instance.

","parent_name":"Request"},"Classes/Request.html#/s:9Alamofire7RequestC16ValidationResulta":{"name":"ValidationResult","abstract":"

Used to represent whether a validation succeeded or failed.

","parent_name":"Request"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO14ConnectionTypeO14ethernetOrWiFiyA2GmF":{"name":"ethernetOrWiFi","abstract":"

The connection type is either over Ethernet or WiFi.

","parent_name":"ConnectionType"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO14ConnectionTypeO8cellularyA2GmF":{"name":"cellular","abstract":"

The connection type is a cellular connection.

","parent_name":"ConnectionType"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO7unknownyA2EmF":{"name":"unknown","abstract":"

It is unknown whether the network is reachable.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO12notReachableyA2EmF":{"name":"notReachable","abstract":"

The network is not reachable.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html#/s:9Alamofire26NetworkReachabilityManagerC0bC6StatusO9reachableyA2E14ConnectionTypeOcAEmF":{"name":"reachable(_:)","abstract":"

The network is reachable on the associated ConnectionType.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus/ConnectionType.html":{"name":"ConnectionType","abstract":"

Defines the various connection types detected by reachability flags.

","parent_name":"NetworkReachabilityStatus"},"Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html":{"name":"NetworkReachabilityStatus","abstract":"

Defines the various states of network reachability.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC8Listenera":{"name":"Listener","abstract":"

A closure executed when the network reachability status changes. The closure takes a single argument: the","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC7defaultACSgvpZ":{"name":"default","abstract":"

Default NetworkReachabilityManager for the zero address and a listenerQueue of .main.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC11isReachableSbvp":{"name":"isReachable","abstract":"

Whether the network is currently reachable.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC21isReachableOnCellularSbvp":{"name":"isReachableOnCellular","abstract":"

Whether the network is currently reachable over the cellular interface.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC27isReachableOnEthernetOrWiFiSbvp":{"name":"isReachableOnEthernetOrWiFi","abstract":"

Whether the network is currently reachable over Ethernet or WiFi interface.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC17reachabilityQueueSo17OS_dispatch_queueCvp":{"name":"reachabilityQueue","abstract":"

DispatchQueue on which reachability will update.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC5flagsSo09SCNetworkC5FlagsVSgvp":{"name":"flags","abstract":"

Flags of the current reachability type, if any.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC6statusAC0bC6StatusOvp":{"name":"status","abstract":"

The current network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC4hostACSgSS_tcfc":{"name":"init(host:)","abstract":"

Creates an instance with the specified host.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerCACSgycfc":{"name":"init()","abstract":"

Creates an instance that monitors the address 0.0.0.0.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC14startListening7onQueue0G16UpdatePerformingSbSo17OS_dispatch_queueC_yAC0bC6StatusOctF":{"name":"startListening(onQueue:onUpdatePerforming:)","abstract":"

Starts listening for changes in network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/NetworkReachabilityManager.html#/s:9Alamofire26NetworkReachabilityManagerC13stopListeningyyF":{"name":"stopListening()","abstract":"

Stops listening for changes in network reachability status.

","parent_name":"NetworkReachabilityManager"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC23encodingMemoryThresholds6UInt64VvpZ":{"name":"encodingMemoryThreshold","abstract":"

Default memory threshold used when encoding MultipartFormData, in bytes.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC11contentTypeSSvp":{"name":"contentType","abstract":"

The Content-Type header value containing the boundary used to generate the multipart/form-data.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC13contentLengths6UInt64Vvp":{"name":"contentLength","abstract":"

The content length of all body parts used to generate the multipart/form-data not including the boundaries.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC8boundarySSvp":{"name":"boundary","abstract":"

The boundary used to separate the body parts in the encoded form data.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC11fileManager8boundaryACSo06NSFileF0C_SSSgtcfc":{"name":"init(fileManager:boundary:)","abstract":"

Creates an instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withName04fileG08mimeTypey10Foundation0D0V_S2SSgAKtF":{"name":"append(_:withName:fileName:mimeType:)","abstract":"

Creates a body part from the data and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withNamey10Foundation3URLV_SStF":{"name":"append(_:withName:)","abstract":"

Creates a body part from the file and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_8withName04fileG08mimeTypey10Foundation3URLV_S3StF":{"name":"append(_:withName:fileName:mimeType:)","abstract":"

Creates a body part from the file and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_10withLength4name8fileName8mimeTypeySo13NSInputStreamC_s6UInt64VS3StF":{"name":"append(_:withLength:name:fileName:mimeType:)","abstract":"

Creates a body part from the stream and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6append_10withLength7headersySo13NSInputStreamC_s6UInt64VAA11HTTPHeadersVtF":{"name":"append(_:withLength:headers:)","abstract":"

Creates a body part with the stream, length, and headers and appends it to the instance.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC6encode10Foundation0D0VyKF":{"name":"encode()","abstract":"

Encodes all appended body parts into a single Data value.

","parent_name":"MultipartFormData"},"Classes/MultipartFormData.html#/s:9Alamofire17MultipartFormDataC012writeEncodedD02toy10Foundation3URLV_tKF":{"name":"writeEncodedData(to:)","abstract":"

Writes all appended body parts to the given file URL.

","parent_name":"MultipartFormData"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC32sessionDidBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtcSgvp":{"name":"sessionDidBecomeInvalidWithError","abstract":"

Closure called on the urlSession(_:didBecomeInvalidWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23taskDidReceiveChallengeySo12NSURLSessionC_So0I4TaskCSo019NSURLAuthenticationH0CtcSgvp":{"name":"taskDidReceiveChallenge","abstract":"

Closure called on the urlSession(_:task:didReceive:completionHandler:).

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC19taskDidSendBodyDataySo12NSURLSessionC_So0J4TaskCs5Int64VA2JtcSgvp":{"name":"taskDidSendBodyData","abstract":"

Closure that receives urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC21taskNeedNewBodyStreamySo12NSURLSessionC_So0J4TaskCtcSgvp":{"name":"taskNeedNewBodyStream","abstract":"

Closure called on the urlSession(_:task:needNewBodyStream:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30taskWillPerformHTTPRedirectionySo12NSURLSessionC_So0I4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtcSgvp":{"name":"taskWillPerformHTTPRedirection","abstract":"

Closure called on the urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30taskDidFinishCollectingMetricsySo12NSURLSessionC_So0J4TaskCSo0jkI0CtcSgvp":{"name":"taskDidFinishCollectingMetrics","abstract":"

Closure called on the urlSession(_:task:didFinishCollecting:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC15taskDidCompleteySo12NSURLSessionC_So0H4TaskCs5Error_pSgtcSgvp":{"name":"taskDidComplete","abstract":"

Closure called on the urlSession(_:task:didCompleteWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC28taskIsWaitingForConnectivityySo12NSURLSessionC_So0J4TaskCtcSgvp":{"name":"taskIsWaitingForConnectivity","abstract":"

Closure called on the urlSession(_:taskIsWaitingForConnectivity:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC22dataTaskDidReceiveDataySo12NSURLSessionC_So0jiF0C10Foundation0I0VtcSgvp":{"name":"dataTaskDidReceiveData","abstract":"

Closure that receives the urlSession(_:dataTask:didReceive:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC25dataTaskWillCacheResponseySo12NSURLSessionC_So0j4DataF0CSo19NSCachedURLResponseCtcSgvp":{"name":"dataTaskWillCacheResponse","abstract":"

Closure called on the urlSession(_:dataTask:willCacheResponse:completionHandler:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC37downloadTaskDidFinishDownloadingToURLySo12NSURLSessionC_So0l8DownloadF0C10Foundation0K0VtcSgvp":{"name":"downloadTaskDidFinishDownloadingToURL","abstract":"

Closure called on the urlSession(_:downloadTask:didFinishDownloadingTo:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC24downloadTaskDidWriteDataySo12NSURLSessionC_So0j8DownloadF0Cs5Int64VA2JtcSgvp":{"name":"downloadTaskDidWriteData","abstract":"

Closure called on the urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC29downloadTaskDidResumeAtOffsetySo12NSURLSessionC_So0k8DownloadF0Cs5Int64VAJtcSgvp":{"name":"downloadTaskDidResumeAtOffset","abstract":"

Closure called on the urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC33requestDidCreateInitialURLRequestyAA7RequestC_10Foundation0I0VtcSgvp":{"name":"requestDidCreateInitialURLRequest","abstract":"

Closure called on the request(_:didCreateInitialURLRequest:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC41requestDidFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtcSgvp":{"name":"requestDidFailToCreateURLRequestWithError","abstract":"

Closure called on the request(_:didFailToCreateURLRequestWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC038requestDidAdaptInitialRequestToAdaptedI0yAA0I0C_10Foundation10URLRequestVAItcSgvp":{"name":"requestDidAdaptInitialRequestToAdaptedRequest","abstract":"

Closure called on the request(_:didAdaptInitialRequest:to:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC40requestDidFailToAdaptURLRequestWithErroryAA7RequestC_10Foundation0J0VAA7AFErrorOtcSgvp":{"name":"requestDidFailToAdaptURLRequestWithError","abstract":"

Closure called on the request(_:didFailToAdaptURLRequest:withError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC26requestDidCreateURLRequestyAA7RequestC_10Foundation0H0VtcSgvp":{"name":"requestDidCreateURLRequest","abstract":"

Closure called on the request(_:didCreateURLRequest:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidCreateTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidCreateTask","abstract":"

Closure called on the request(_:didCreateTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23requestDidGatherMetricsyAA7RequestC_So016NSURLSessionTaskH0CtcSgvp":{"name":"requestDidGatherMetrics","abstract":"

Closure called on the request(_:didGatherMetrics:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC32requestDidFailTaskEarlyWithErroryAA7RequestC_So012NSURLSessionH0CAA7AFErrorOtcSgvp":{"name":"requestDidFailTaskEarlyWithError","abstract":"

Closure called on the request(_:didFailTask:earlyWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC31requestDidCompleteTaskWithErroryAA7RequestC_So012NSURLSessionH0CAA7AFErrorOSgtcSgvp":{"name":"requestDidCompleteTaskWithError","abstract":"

Closure called on the request(_:didCompleteTask:with:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC17requestIsRetryingyAA7RequestCcSgvp":{"name":"requestIsRetrying","abstract":"

Closure called on the requestIsRetrying(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidFinishyAA7RequestCcSgvp":{"name":"requestDidFinish","abstract":"

Closure called on the requestDidFinish(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidResumeyAA7RequestCcSgvp":{"name":"requestDidResume","abstract":"

Closure called on the requestDidResume(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidResumeTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidResumeTask","abstract":"

Closure called on the request(_:didResumeTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC17requestDidSuspendyAA7RequestCcSgvp":{"name":"requestDidSuspend","abstract":"

Closure called on the requestDidSuspend(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC21requestDidSuspendTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidSuspendTask","abstract":"

Closure called on the request(_:didSuspendTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC16requestDidCancelyAA7RequestCcSgvp":{"name":"requestDidCancel","abstract":"

Closure called on the requestDidCancel(_:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC20requestDidCancelTaskyAA7RequestC_So012NSURLSessionH0CtcSgvp":{"name":"requestDidCancelTask","abstract":"

Closure called on the request(_:didCancelTask:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC47requestDidValidateRequestResponseDataWithResultyAA0jH0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAG0J0VSgs0L0Oyyts5Error_pGtcSgvp":{"name":"requestDidValidateRequestResponseDataWithResult","abstract":"

Closure called on the request(_:didValidateRequest:response:data:withResult:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC23requestDidParseResponseyAA11DataRequestC_AA0iH0Vy10Foundation0I0VSgAA7AFErrorOGtcSgvp":{"name":"requestDidParseResponse","abstract":"

Closure called on the request(_:didParseResponse:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC26requestDidCreateUploadableyAA13UploadRequestC_AF0H0OtcSgvp":{"name":"requestDidCreateUploadable","abstract":"

Closure called on the request(_:didCreateUploadable:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC41requestDidFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtcSgvp":{"name":"requestDidFailToCreateUploadableWithError","abstract":"

Closure called on the request(_:didFailToCreateUploadableWithError:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC28requestDidProvideInputStreamyAA13UploadRequestC_So07NSInputI0CtcSgvp":{"name":"requestDidProvideInputStream","abstract":"

Closure called on the request(_:didProvideInputStream:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC46requestDidFinishDownloadingUsingTaskWithResultyAA15DownloadRequestC_So012NSURLSessionJ0Cs0L0Oy10Foundation3URLVAA7AFErrorOGtcSgvp":{"name":"requestDidFinishDownloadingUsingTaskWithResult","abstract":"

Closure called on the request(_:didFinishDownloadingUsing:with:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC30requestDidCreateDestinationURLyAA15DownloadRequestC_10Foundation0I0VtcSgvp":{"name":"requestDidCreateDestinationURL","abstract":"

Closure called on the request(_:didCreateDestinationURL:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC50requestDidValidateRequestResponseFileURLWithResultyAA08DownloadH0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAG3URLVSgs0L0Oyyts5Error_pGtcSgvp":{"name":"requestDidValidateRequestResponseFileURLWithResult","abstract":"

Closure called on the request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC31requestDidParseDownloadResponseyAA0H7RequestC_AA0hI0Vy10Foundation3URLVSgAA7AFErrorOGtcSgvp":{"name":"requestDidParseDownloadResponse","abstract":"

Closure called on the request(_:didParseResponse:) event.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire19ClosureEventMonitorC5queueACSo012OS_dispatch_E0C_tcfc":{"name":"init(queue:)","abstract":"

Creates an instance using the provided queue.

","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","parent_name":"ClosureEventMonitor"},"Classes/ClosureEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"ClosureEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP5queueSo012OS_dispatch_D0Cvp":{"name":"queue","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_25didBecomeInvalidWithErrorySo12NSURLSessionC_s0J0_pSgtF":{"name":"urlSession(_:didBecomeInvalidWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task10didReceiveySo12NSURLSessionC_So0I4TaskCSo28NSURLAuthenticationChallengeCtF":{"name":"urlSession(_:task:didReceive:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task15didSendBodyData14totalBytesSent0kl10ExpectedToH0ySo12NSURLSessionC_So0P4TaskCs5Int64VA2NtF":{"name":"urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_22taskNeedsNewBodyStreamySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskNeedsNewBodyStream:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task26willPerformHTTPRedirection10newRequestySo12NSURLSessionC_So0L4TaskCSo17NSHTTPURLResponseC10Foundation10URLRequestVtF":{"name":"urlSession(_:task:willPerformHTTPRedirection:newRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task19didFinishCollectingySo12NSURLSessionC_So0J4TaskCSo0jK7MetricsCtF":{"name":"urlSession(_:task:didFinishCollecting:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_4task20didCompleteWithErrorySo12NSURLSessionC_So0K4TaskCs0J0_pSgtF":{"name":"urlSession(_:task:didCompleteWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_28taskIsWaitingForConnectivityySo12NSURLSessionC_So0K4TaskCtF":{"name":"urlSession(_:taskIsWaitingForConnectivity:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask10didReceiveySo12NSURLSessionC_So0j4DataG0C10Foundation0K0VtF":{"name":"urlSession(_:dataTask:didReceive:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_8dataTask17willCacheResponseySo12NSURLSessionC_So0k4DataG0CSo19NSCachedURLResponseCtF":{"name":"urlSession(_:dataTask:willCacheResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask17didResumeAtOffset18expectedTotalBytesySo12NSURLSessionC_So0o8DownloadG0Cs5Int64VAMtF":{"name":"urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask12didWriteData17totalBytesWritten0kl10ExpectedToI0ySo12NSURLSessionC_So0p8DownloadG0Cs5Int64VA2NtF":{"name":"urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP10urlSession_12downloadTask22didFinishDownloadingToySo12NSURLSessionC_So0l8DownloadG0C10Foundation3URLVtF":{"name":"urlSession(_:downloadTask:didFinishDownloadingTo:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_26didCreateInitialURLRequestyAA7RequestC_10Foundation0H0VtF":{"name":"request(_:didCreateInitialURLRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateURLRequestWithErroryAA7RequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateURLRequestWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_22didAdaptInitialRequest2toyAA0H0C_10Foundation10URLRequestVAKtF":{"name":"request(_:didAdaptInitialRequest:to:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_24didFailToAdaptURLRequest9withErroryAA7RequestC_10Foundation0I0VAA7AFErrorOtF":{"name":"request(_:didFailToAdaptURLRequest:withError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateURLRequestyAA7RequestC_10Foundation0G0VtF":{"name":"request(_:didCreateURLRequest:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCreateTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCreateTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didGatherMetricsyAA7RequestC_So016NSURLSessionTaskG0CtF":{"name":"request(_:didGatherMetrics:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_11didFailTask14earlyWithErroryAA7RequestC_So012NSURLSessionG0CAA7AFErrorOtF":{"name":"request(_:didFailTask:earlyWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_15didCompleteTask4withyAA7RequestC_So012NSURLSessionG0CAA7AFErrorOSgtF":{"name":"request(_:didCompleteTask:with:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP17requestIsRetryingyyAA7RequestCF":{"name":"requestIsRetrying(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidFinishyyAA7RequestCF":{"name":"requestDidFinish(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidResumeyyAA7RequestCF":{"name":"requestDidResume(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didResumeTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didResumeTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP17requestDidSuspendyyAA7RequestCF":{"name":"requestDidSuspend(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_14didSuspendTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didSuspendTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP16requestDidCancelyyAA7RequestCF":{"name":"requestDidCancel(_:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_13didCancelTaskyAA7RequestC_So012NSURLSessionG0CtF":{"name":"request(_:didCancelTask:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response4data10withResultyAA04DataG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0L0VSgs0K0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:data:withResult:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vy10Foundation0H0VSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA11DataRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_19didCreateUploadableyAA13UploadRequestC_AG0G0OtF":{"name":"request(_:didCreateUploadable:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_34didFailToCreateUploadableWithErroryAA13UploadRequestC_AA7AFErrorOtF":{"name":"request(_:didFailToCreateUploadableWithError:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_21didProvideInputStreamyAA13UploadRequestC_So07NSInputH0CtF":{"name":"request(_:didProvideInputStream:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_25didFinishDownloadingUsing4withyAA15DownloadRequestC_So16NSURLSessionTaskCs6ResultOy10Foundation3URLVAA7AFErrorOGtF":{"name":"request(_:didFinishDownloadingUsing:with:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_23didCreateDestinationURLyAA15DownloadRequestC_10Foundation0H0VtF":{"name":"request(_:didCreateDestinationURL:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_18didValidateRequest8response7fileURL10withResultyAA08DownloadG0C_10Foundation10URLRequestVSgSo17NSHTTPURLResponseCAK0J0VSgs0L0Oyyts5Error_pGtF":{"name":"request(_:didValidateRequest:response:fileURL:withResult:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vy10Foundation3URLVSgAA7AFErrorOGtF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html#/s:9Alamofire12EventMonitorP7request_16didParseResponseyAA15DownloadRequestC_AA0hG0Vyqd__AA7AFErrorOGtlF":{"name":"request(_:didParseResponse:)","parent_name":"CompositeEventMonitor"},"Classes/CompositeEventMonitor.html":{"name":"CompositeEventMonitor","abstract":"

An EventMonitor which can contain multiple EventMonitors and calls their methods on their queues.

"},"Classes/ClosureEventMonitor.html":{"name":"ClosureEventMonitor","abstract":"

EventMonitor that allows optional closures to be set to receive events.

"},"Classes/MultipartFormData.html":{"name":"MultipartFormData","abstract":"

Constructs multipart/form-data for uploads within an HTTP or HTTPS body. There are currently two ways to encode"},"Classes/NetworkReachabilityManager.html":{"name":"NetworkReachabilityManager","abstract":"

The NetworkReachabilityManager class listens for reachability changes of hosts and addresses for both cellular and"},"Classes/Request.html":{"name":"Request","abstract":"

Request is the common superclass of all Alamofire request types and provides common state, delegate, and callback"},"Classes/AlamofireNotifications.html":{"name":"AlamofireNotifications","abstract":"

EventMonitor that provides Alamofire’s notifications.

"},"Classes/JSONParameterEncoder.html":{"name":"JSONParameterEncoder","abstract":"

A ParameterEncoder that encodes types as JSON body data.

"},"Classes/URLEncodedFormParameterEncoder.html":{"name":"URLEncodedFormParameterEncoder","abstract":"

A ParameterEncoder that encodes types as URL-encoded query strings to be set on the URL or as body data, depending"},"Classes/DataRequest.html":{"name":"DataRequest","abstract":"

Request subclass which handles in-memory Data download using URLSessionDataTask.

"},"Classes/DownloadRequest.html":{"name":"DownloadRequest","abstract":"

Request subclass which downloads Data to a file on disk using URLSessionDownloadTask.

"},"Classes/UploadRequest.html":{"name":"UploadRequest","abstract":"

DataRequest subclass which handles Data upload from memory, file, or stream using URLSessionUploadTask.

"},"Classes/Adapter.html":{"name":"Adapter","abstract":"

Closure-based RequestAdapter.

"},"Classes/Retrier.html":{"name":"Retrier","abstract":"

Closure-based RequestRetrier.

"},"Classes/Interceptor.html":{"name":"Interceptor","abstract":"

RequestInterceptor which can use multiple RequestAdapter and RequestRetrier values.

"},"Classes/DataResponseSerializer.html":{"name":"DataResponseSerializer","abstract":"

A ResponseSerializer that performs minimal response checking and returns any response data as-is. By default, a"},"Classes/StringResponseSerializer.html":{"name":"StringResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data as a String. By default, a request returning nil or no"},"Classes/JSONResponseSerializer.html":{"name":"JSONResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data using JSONSerialization. By default, a request returning"},"Classes/DecodableResponseSerializer.html":{"name":"DecodableResponseSerializer","abstract":"

A ResponseSerializer that decodes the response data as a generic value using any type that conforms to"},"Classes/RetryPolicy.html":{"name":"RetryPolicy","abstract":"

A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes"},"Classes/ConnectionLostRetryPolicy.html":{"name":"ConnectionLostRetryPolicy","abstract":"

A retry policy that automatically retries idempotent requests for network connection lost errors. For more"},"Classes/ServerTrustManager.html":{"name":"ServerTrustManager","abstract":"

Responsible for managing the mapping of ServerTrustEvaluating values to given hosts.

"},"Classes/DefaultTrustEvaluator.html":{"name":"DefaultTrustEvaluator","abstract":"

An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the"},"Classes/RevocationTrustEvaluator.html":{"name":"RevocationTrustEvaluator","abstract":"

An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate"},"Classes/PinnedCertificatesTrustEvaluator.html":{"name":"PinnedCertificatesTrustEvaluator","abstract":"

Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned"},"Classes/PublicKeysTrustEvaluator.html":{"name":"PublicKeysTrustEvaluator","abstract":"

Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned"},"Classes/CompositeTrustEvaluator.html":{"name":"CompositeTrustEvaluator","abstract":"

Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the"},"Classes/DisabledEvaluator.html":{"name":"DisabledEvaluator","abstract":"

Disables all evaluation which in turn will always consider any server trust as valid.

"},"Classes/Session.html":{"name":"Session","abstract":"

Session creates and manages Alamofire’s Request types during their lifetimes. It also provides common"},"Classes/SessionDelegate.html":{"name":"SessionDelegate","abstract":"

Class which implements the various URLSessionDelegate methods to connect various Alamofire features.

"},"Classes/URLEncodedFormEncoder.html":{"name":"URLEncodedFormEncoder","abstract":"

An object that encodes instances into URL-encoded query strings.

"},"Classes.html":{"name":"Classes","abstract":"

The following classes are available globally.

"},"Enums.html":{"name":"Enumerations","abstract":"

The following enumerations are available globally.

"},"Extensions.html":{"name":"Extensions","abstract":"

The following extensions are available globally.

"},"Protocols.html":{"name":"Protocols","abstract":"

The following protocols are available globally.

"},"Structs.html":{"name":"Structures","abstract":"

The following structures are available globally.

"},"Typealiases.html":{"name":"Type Aliases","abstract":"

The following type aliases are available globally.

"}} \ No newline at end of file diff --git a/Lesson12/Carthage/Checkouts/Alamofire/docs/undocumented.json b/Lesson12/Carthage/Checkouts/Alamofire/docs/undocumented.json deleted file mode 100644 index 11210e8..0000000 --- a/Lesson12/Carthage/Checkouts/Alamofire/docs/undocumented.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "warnings": [ - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 269, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 270, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 281, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/EventMonitor.swift", - "line": 282, - "symbol": "EventMonitor.request(_:didParseResponse:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/ResponseSerialization.swift", - "line": 84, - "symbol": "PassthroughPreprocessor.init()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/ResponseSerialization.swift", - "line": 91, - "symbol": "GoogleXSSIPreprocessor.init()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 59, - "symbol": "SessionDelegate.urlSession(_:didBecomeInvalidWithError:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 72, - "symbol": "SessionDelegate.urlSession(_:task:didReceive:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 144, - "symbol": "SessionDelegate.urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 159, - "symbol": "SessionDelegate.urlSession(_:task:needNewBodyStream:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 171, - "symbol": "SessionDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 185, - "symbol": "SessionDelegate.urlSession(_:task:didFinishCollecting:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 193, - "symbol": "SessionDelegate.urlSession(_:task:didCompleteWithError:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 202, - "symbol": "SessionDelegate.urlSession(_:taskIsWaitingForConnectivity:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 210, - "symbol": "SessionDelegate.urlSession(_:dataTask:didReceive:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 220, - "symbol": "SessionDelegate.urlSession(_:dataTask:willCacheResponse:completionHandler:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 237, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 254, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/SessionDelegate.swift", - "line": 273, - "symbol": "SessionDelegate.urlSession(_:downloadTask:didFinishDownloadingTo:)", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - }, - { - "file": "/Users/jshier/Desktop/Code/Alamofire/Source/URLRequest+Alamofire.swift", - "line": 34, - "symbol": "URLRequest.validate()", - "symbol_kind": "source.lang.swift.decl.function.method.instance", - "warning": "undocumented" - } - ], - "source_directory": "/Users/jshier/Desktop/Code/Alamofire" -} \ No newline at end of file diff --git a/Lesson12/Lesson12.xcodeproj/project.pbxproj b/Lesson12/Lesson12.xcodeproj/project.pbxproj deleted file mode 100644 index 1c3a7a0..0000000 --- a/Lesson12/Lesson12.xcodeproj/project.pbxproj +++ /dev/null @@ -1,467 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 124CFDDDC2BA114F4919EA58 /* Pods_Lesson12.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 91C68B5163A7CA7C1287699C /* Pods_Lesson12.framework */; }; - 3368995E23E4748C0082F091 /* DefaultViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3368995D23E4748C0082F091 /* DefaultViewController.swift */; }; - 3368996023E475FD0082F091 /* WeatherTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3368995F23E475FD0082F091 /* WeatherTableViewCell.swift */; }; - 3396C6AC23E470A400DF9AD8 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3396C6AB23E470A400DF9AD8 /* AppDelegate.swift */; }; - 3396C6AE23E470A400DF9AD8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3396C6AD23E470A400DF9AD8 /* SceneDelegate.swift */; }; - 3396C6B323E470A400DF9AD8 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3396C6B123E470A400DF9AD8 /* Main.storyboard */; }; - 3396C6B523E470A900DF9AD8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3396C6B423E470A900DF9AD8 /* Assets.xcassets */; }; - 3396C6B823E470A900DF9AD8 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3396C6B623E470A900DF9AD8 /* LaunchScreen.storyboard */; }; - 3396C6C123E4720B00DF9AD8 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3396C6C023E4720B00DF9AD8 /* Alamofire.framework */; }; - 3396C6C223E4720B00DF9AD8 /* Alamofire.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3396C6C023E4720B00DF9AD8 /* Alamofire.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 33A7740523E8150F00EB4880 /* WeatherDefaultLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A7740423E8150F00EB4880 /* WeatherDefaultLoader.swift */; }; - 33A7740923E82DC500EB4880 /* WeatherAlamofireLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A7740823E82DC500EB4880 /* WeatherAlamofireLoader.swift */; }; - 33A7740B23E82E7500EB4880 /* AlamofireViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A7740A23E82E7500EB4880 /* AlamofireViewController.swift */; }; - 33BDFEA023E99156003AE604 /* RealmPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDFE9F23E99156003AE604 /* RealmPersistence.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 3396C6C323E4720B00DF9AD8 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - 3396C6C223E4720B00DF9AD8 /* Alamofire.framework in Embed Frameworks */, - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 3368995D23E4748C0082F091 /* DefaultViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultViewController.swift; sourceTree = ""; }; - 3368995F23E475FD0082F091 /* WeatherTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherTableViewCell.swift; sourceTree = ""; }; - 3396C6A823E470A400DF9AD8 /* Lesson12.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lesson12.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 3396C6AB23E470A400DF9AD8 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 3396C6AD23E470A400DF9AD8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 3396C6B223E470A400DF9AD8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 3396C6B423E470A900DF9AD8 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 3396C6B723E470A900DF9AD8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 3396C6B923E470A900DF9AD8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3396C6C023E4720B00DF9AD8 /* Alamofire.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Alamofire.framework; path = Carthage/Build/iOS/Alamofire.framework; sourceTree = ""; }; - 33A7740423E8150F00EB4880 /* WeatherDefaultLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherDefaultLoader.swift; sourceTree = ""; }; - 33A7740823E82DC500EB4880 /* WeatherAlamofireLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherAlamofireLoader.swift; sourceTree = ""; }; - 33A7740A23E82E7500EB4880 /* AlamofireViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlamofireViewController.swift; sourceTree = ""; }; - 33BDFE9F23E99156003AE604 /* RealmPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealmPersistence.swift; sourceTree = ""; }; - 91C68B5163A7CA7C1287699C /* Pods_Lesson12.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Lesson12.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9B7523B53070EB53FD063DD0 /* Pods-Lesson12.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson12.debug.xcconfig"; path = "Target Support Files/Pods-Lesson12/Pods-Lesson12.debug.xcconfig"; sourceTree = ""; }; - C1392FDE9539F4D5F49419A4 /* Pods-Lesson12.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson12.release.xcconfig"; path = "Target Support Files/Pods-Lesson12/Pods-Lesson12.release.xcconfig"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 3396C6A523E470A400DF9AD8 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 3396C6C123E4720B00DF9AD8 /* Alamofire.framework in Frameworks */, - 124CFDDDC2BA114F4919EA58 /* Pods_Lesson12.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 3396C69F23E470A400DF9AD8 = { - isa = PBXGroup; - children = ( - 3396C6AA23E470A400DF9AD8 /* Lesson12 */, - 3396C6A923E470A400DF9AD8 /* Products */, - 3396C6BF23E4720B00DF9AD8 /* Frameworks */, - E3143C76315296002D680EB6 /* Pods */, - ); - sourceTree = ""; - }; - 3396C6A923E470A400DF9AD8 /* Products */ = { - isa = PBXGroup; - children = ( - 3396C6A823E470A400DF9AD8 /* Lesson12.app */, - ); - name = Products; - sourceTree = ""; - }; - 3396C6AA23E470A400DF9AD8 /* Lesson12 */ = { - isa = PBXGroup; - children = ( - 33A7740323E814FE00EB4880 /* Loaders */, - 3396C6AB23E470A400DF9AD8 /* AppDelegate.swift */, - 3396C6AD23E470A400DF9AD8 /* SceneDelegate.swift */, - 3396C6B123E470A400DF9AD8 /* Main.storyboard */, - 3396C6B423E470A900DF9AD8 /* Assets.xcassets */, - 3396C6B623E470A900DF9AD8 /* LaunchScreen.storyboard */, - 3396C6B923E470A900DF9AD8 /* Info.plist */, - 3368995D23E4748C0082F091 /* DefaultViewController.swift */, - 3368995F23E475FD0082F091 /* WeatherTableViewCell.swift */, - 33A7740A23E82E7500EB4880 /* AlamofireViewController.swift */, - 33BDFE9F23E99156003AE604 /* RealmPersistence.swift */, - ); - path = Lesson12; - sourceTree = ""; - }; - 3396C6BF23E4720B00DF9AD8 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 3396C6C023E4720B00DF9AD8 /* Alamofire.framework */, - 91C68B5163A7CA7C1287699C /* Pods_Lesson12.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 33A7740323E814FE00EB4880 /* Loaders */ = { - isa = PBXGroup; - children = ( - 33A7740423E8150F00EB4880 /* WeatherDefaultLoader.swift */, - 33A7740823E82DC500EB4880 /* WeatherAlamofireLoader.swift */, - ); - path = Loaders; - sourceTree = ""; - }; - E3143C76315296002D680EB6 /* Pods */ = { - isa = PBXGroup; - children = ( - 9B7523B53070EB53FD063DD0 /* Pods-Lesson12.debug.xcconfig */, - C1392FDE9539F4D5F49419A4 /* Pods-Lesson12.release.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 3396C6A723E470A400DF9AD8 /* Lesson12 */ = { - isa = PBXNativeTarget; - buildConfigurationList = 3396C6BC23E470A900DF9AD8 /* Build configuration list for PBXNativeTarget "Lesson12" */; - buildPhases = ( - A6697926FFF7D6E646E65552 /* [CP] Check Pods Manifest.lock */, - 3396C6A423E470A400DF9AD8 /* Sources */, - 3396C6A523E470A400DF9AD8 /* Frameworks */, - 3396C6A623E470A400DF9AD8 /* Resources */, - 3396C6C323E4720B00DF9AD8 /* Embed Frameworks */, - D9E1958621582920F0B248C5 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Lesson12; - productName = Lesson12; - productReference = 3396C6A823E470A400DF9AD8 /* Lesson12.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 3396C6A023E470A400DF9AD8 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1130; - LastUpgradeCheck = 1130; - ORGANIZATIONNAME = "Михаил Беленко"; - TargetAttributes = { - 3396C6A723E470A400DF9AD8 = { - CreatedOnToolsVersion = 11.3.1; - }; - }; - }; - buildConfigurationList = 3396C6A323E470A400DF9AD8 /* Build configuration list for PBXProject "Lesson12" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 3396C69F23E470A400DF9AD8; - productRefGroup = 3396C6A923E470A400DF9AD8 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 3396C6A723E470A400DF9AD8 /* Lesson12 */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 3396C6A623E470A400DF9AD8 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3396C6B823E470A900DF9AD8 /* LaunchScreen.storyboard in Resources */, - 3396C6B523E470A900DF9AD8 /* Assets.xcassets in Resources */, - 3396C6B323E470A400DF9AD8 /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - A6697926FFF7D6E646E65552 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Lesson12-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - D9E1958621582920F0B248C5 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 3396C6A423E470A400DF9AD8 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33A7740923E82DC500EB4880 /* WeatherAlamofireLoader.swift in Sources */, - 33A7740523E8150F00EB4880 /* WeatherDefaultLoader.swift in Sources */, - 33A7740B23E82E7500EB4880 /* AlamofireViewController.swift in Sources */, - 3368996023E475FD0082F091 /* WeatherTableViewCell.swift in Sources */, - 3368995E23E4748C0082F091 /* DefaultViewController.swift in Sources */, - 3396C6AC23E470A400DF9AD8 /* AppDelegate.swift in Sources */, - 3396C6AE23E470A400DF9AD8 /* SceneDelegate.swift in Sources */, - 33BDFEA023E99156003AE604 /* RealmPersistence.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 3396C6B123E470A400DF9AD8 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 3396C6B223E470A400DF9AD8 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 3396C6B623E470A900DF9AD8 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 3396C6B723E470A900DF9AD8 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 3396C6BA23E470A900DF9AD8 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 3396C6BB23E470A900DF9AD8 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 3396C6BD23E470A900DF9AD8 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9B7523B53070EB53FD063DD0 /* Pods-Lesson12.debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Carthage/Build/iOS", - ); - INFOPLIST_FILE = Lesson12/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson12; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 3396C6BE23E470A900DF9AD8 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = C1392FDE9539F4D5F49419A4 /* Pods-Lesson12.release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Carthage/Build/iOS", - ); - INFOPLIST_FILE = Lesson12/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson12; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 3396C6A323E470A400DF9AD8 /* Build configuration list for PBXProject "Lesson12" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3396C6BA23E470A900DF9AD8 /* Debug */, - 3396C6BB23E470A900DF9AD8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 3396C6BC23E470A900DF9AD8 /* Build configuration list for PBXNativeTarget "Lesson12" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3396C6BD23E470A900DF9AD8 /* Debug */, - 3396C6BE23E470A900DF9AD8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 3396C6A023E470A400DF9AD8 /* Project object */; -} diff --git a/Lesson12/Lesson12.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson12/Lesson12.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index edd6535..0000000 --- a/Lesson12/Lesson12.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson12/Lesson12.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson12/Lesson12.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson12/Lesson12.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson12/Lesson12.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson12/Lesson12.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson12/Lesson12.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson12/Lesson12/AlamofireViewController.swift b/Lesson12/Lesson12/AlamofireViewController.swift deleted file mode 100644 index f20e42e..0000000 --- a/Lesson12/Lesson12/AlamofireViewController.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// AlamofireViewController.swift -// Lesson12 -// -// Created by Михаил Беленко on 03.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTTableViewManager -import DTModelStorage - -class AlamofireViewController: UIViewController, DTTableViewManageable { - - @IBOutlet weak var nameCityLabel: UILabel! - @IBOutlet weak var tableView: UITableView! - - override func viewDidLoad() { - super.viewDidLoad() - - manager.register(WeatherTableViewCell.self) - nameCityLabel.text = "Loading..." - manager.memoryStorage.setItems(RealmPersistence.storage.getSaveDatabase()) - - WeatherAlamofireLoader().loadWeather { [unowned self] nameCity, weather in - self.nameCityLabel.text = nameCity - self.manager.memoryStorage.setItems(weather) - } - } -} diff --git a/Lesson12/Lesson12/AppDelegate.swift b/Lesson12/Lesson12/AppDelegate.swift deleted file mode 100644 index 1c4a64c..0000000 --- a/Lesson12/Lesson12/AppDelegate.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// AppDelegate.swift -// Lesson12 -// -// Created by Михаил Беленко on 31.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { - - - - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - return true - } - - // MARK: UISceneSession Lifecycle - - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) - } - - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. - } - - -} - diff --git a/Lesson12/Lesson12/Assets.xcassets/AppIcon.appiconset/Contents.json b/Lesson12/Lesson12/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d8db8d6..0000000 --- a/Lesson12/Lesson12/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "83.5x83.5", - "scale" : "2x" - }, - { - "idiom" : "ios-marketing", - "size" : "1024x1024", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson12/Lesson12/Assets.xcassets/Contents.json b/Lesson12/Lesson12/Assets.xcassets/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson12/Lesson12/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson12/Lesson12/Base.lproj/LaunchScreen.storyboard b/Lesson12/Lesson12/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 865e932..0000000 --- a/Lesson12/Lesson12/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Lesson12/Base.lproj/Main.storyboard b/Lesson12/Lesson12/Base.lproj/Main.storyboard deleted file mode 100644 index e52a9c3..0000000 --- a/Lesson12/Lesson12/Base.lproj/Main.storyboard +++ /dev/null @@ -1,89 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson12/Lesson12/DefaultViewController.swift b/Lesson12/Lesson12/DefaultViewController.swift deleted file mode 100644 index 1fc2cb3..0000000 --- a/Lesson12/Lesson12/DefaultViewController.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// DefaultViewController.swift -// Lesson12 -// -// Created by Михаил Беленко on 31.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTTableViewManager -import DTModelStorage - -class DefaultViewController: UIViewController, DTTableViewManageable { - - @IBOutlet weak var nameCityLabel: UILabel! - @IBOutlet weak var tableView: UITableView! - - override func viewDidLoad() { - super.viewDidLoad() - - manager.register(WeatherTableViewCell.self) - nameCityLabel.text = "Loading..." - manager.memoryStorage.setItems(RealmPersistence.storage.getSaveDatabase()) - RealmPersistence.storage.clearDatabase() - - WeatherDefaultLoader().loadWeather { [unowned self] nameCity, weather in - self.nameCityLabel.text = nameCity - self.manager.memoryStorage.setItems(weather) - } - } -} diff --git a/Lesson12/Lesson12/Info.plist b/Lesson12/Lesson12/Info.plist deleted file mode 100644 index d985e11..0000000 --- a/Lesson12/Lesson12/Info.plist +++ /dev/null @@ -1,79 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - UISceneConfigurations - - UIWindowSceneSessionRoleApplication - - - UISceneConfigurationName - Default Configuration - UISceneDelegateClassName - $(PRODUCT_MODULE_NAME).SceneDelegate - UISceneStoryboardFile - Main - - - - - NSAppTransportSecurity - - NSAllowsArbitraryLoads - - NSExceptionDomains - - openweathermap.org - - NSExceptionAllowsInsecureHTTPLoads - - NSIncludesSubdomains - - - - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Lesson12/Lesson12/Loaders/WeatherAlamofireLoader.swift b/Lesson12/Lesson12/Loaders/WeatherAlamofireLoader.swift deleted file mode 100644 index 3aef5b5..0000000 --- a/Lesson12/Lesson12/Loaders/WeatherAlamofireLoader.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// WeatherAlamofireLoader.swift -// Lesson12 -// -// Created by Михаил Беленко on 03.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import Foundation -import Alamofire - -class WeatherAlamofireLoader { - - func loadWeather(completion: @escaping (String, [WeatherTableViewCellModel]) -> Void) { - // для Москвы нужно поменять id на 524901 - AF.request("http://api.openweathermap.org/data/2.5/forecast?id=581049&appid=4cf8b5521e6a43563500b176a76d90c1").responseJSON { responce in - if let objects = try? responce.result.get(), - let jsonDict = objects as? NSDictionary { - var weather: [WeatherTableViewCellModel] = [] - var cityName: String = "" - - if let list = jsonDict["list"] as? [NSDictionary] { - for element in list { - if let weatherDay = WeatherTableViewCellModel(data: element) { - weather.append(weatherDay) - } - } - } - - if let city = jsonDict["city"] as? NSDictionary { - cityName = city["name"] as! String - } - - RealmPersistence.storage.replaceSaveDatabase(database: weather) - - DispatchQueue.main.async { - completion(cityName, weather) - } - } - } - } -} diff --git a/Lesson12/Lesson12/Loaders/WeatherDefaultLoader.swift b/Lesson12/Lesson12/Loaders/WeatherDefaultLoader.swift deleted file mode 100644 index d9f22ff..0000000 --- a/Lesson12/Lesson12/Loaders/WeatherDefaultLoader.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// WeatherDefaultLoader.swift -// Lesson12 -// -// Created by Михаил Беленко on 03.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import Foundation - -class WeatherDefaultLoader { - - func loadWeather(completion: @escaping (String, [WeatherTableViewCellModel]) -> Void) { - let url = URL(string: "http://api.openweathermap.org/data/2.5/forecast?id=581049&appid=4cf8b5521e6a43563500b176a76d90c1")! // для Москвы нужно поменять id на 524901 - let request = URLRequest(url: url) - - let task = URLSession.shared.dataTask(with: request) { data, responce, error in - if let data = data, - let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments), - let jsonDict = json as? NSDictionary { - var weather: [WeatherTableViewCellModel] = [] - var cityName: String = "" - - if let list = jsonDict["list"] as? [NSDictionary] { - for element in list { - if let weatherDay = WeatherTableViewCellModel(data: element) { - weather.append(weatherDay) - } - } - } - - if let city = jsonDict["city"] as? NSDictionary { - cityName = city["name"] as! String - } - - RealmPersistence.storage.replaceSaveDatabase(database: weather) - - DispatchQueue.main.async { - completion(cityName, weather) - } - } - } - task.resume() - } -} diff --git a/Lesson12/Lesson12/RealmPersistence.swift b/Lesson12/Lesson12/RealmPersistence.swift deleted file mode 100644 index 222a259..0000000 --- a/Lesson12/Lesson12/RealmPersistence.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// RealmPersistence.swift -// Lesson12 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import RealmSwift - -class RealmPersistence { - - static var storage = RealmPersistence() - - var realm = try! Realm() - - func addEntry(entry: WeatherTableViewCellModel) { - try! realm.write { - realm.add(entry) - } - } - - func replaceSaveDatabase(database: [WeatherTableViewCellModel]) { - clearDatabase() - for entry in database { - addEntry(entry: entry) - } - } - - func getSaveDatabase() -> [WeatherTableViewCellModel] { - var database: [WeatherTableViewCellModel] = [] - for entry in realm.objects(WeatherTableViewCellModel.self) { - database.append(entry) - } - return database - } - - func clearDatabase() { - let database = realm.objects(WeatherTableViewCellModel.self) - - try! realm.write { - realm.delete(database) - } - } -} diff --git a/Lesson12/Lesson12/WeatherTableViewCell.swift b/Lesson12/Lesson12/WeatherTableViewCell.swift deleted file mode 100644 index 031e95f..0000000 --- a/Lesson12/Lesson12/WeatherTableViewCell.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// WeatherTableViewCell.swift -// Lesson12 -// -// Created by Михаил Беленко on 31.01.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTModelStorage -import SnapKit -import RealmSwift - -class WeatherTableViewCell: UITableViewCell, ModelTransfer { - - private lazy var dtLabel = UILabel() - private lazy var minTempDescriptionLabel: UILabel = { - let label = UILabel() - label.text = "Min:" - return label - }() - private lazy var minTempLabel = UILabel() - private lazy var maxTempDescriptionLabel: UILabel = { - let label = UILabel() - label.text = "Max:" - return label - }() - private lazy var maxTempLabel = UILabel() - - typealias ModelType = WeatherTableViewCellModel - - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { - super.init(style: style, reuseIdentifier: reuseIdentifier) - - contentView.addSubview(dtLabel) - contentView.addSubview(minTempDescriptionLabel) - contentView.addSubview(minTempLabel) - contentView.addSubview(maxTempDescriptionLabel) - contentView.addSubview(maxTempLabel) - setupConstraints() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - - func update(with model: WeatherTableViewCellModel) { - dtLabel.text = model.dt - minTempLabel.text = "\(model.tempMin) °F" - maxTempLabel.text = "\(model.tempMax) °F" - } - - private func setupConstraints() { - dtLabel.snp.makeConstraints { make in - make.centerY.equalToSuperview() - make.leading.equalToSuperview().inset(16) - } - - minTempLabel.snp.makeConstraints { make in - make.top.trailing.equalToSuperview().inset(16) - } - - minTempDescriptionLabel.snp.makeConstraints { make in - make.trailing.equalTo(minTempLabel.snp.leading).offset(-8) - make.top.equalTo(minTempLabel.snp.top) - } - - maxTempLabel.snp.makeConstraints { make in - make.top.greaterThanOrEqualTo(minTempLabel.snp.bottom).offset(8) - make.bottom.trailing.equalToSuperview().inset(16) - } - - maxTempDescriptionLabel.snp.makeConstraints { make in - make.trailing.equalTo(maxTempLabel.snp.leading).offset(-8) - make.top.equalTo(maxTempLabel.snp.top) - } - } - -} - -class WeatherTableViewCellModel: Object { - @objc dynamic var dt: String - @objc dynamic var tempMin: Double - @objc dynamic var tempMax: Double - - init?(data: NSDictionary) { - guard let main = data["main"] as? NSDictionary, - let dt = data["dt_txt"] as? String, - let tempMin = main["temp_min"] as? Double, - let tempMax = main["temp_max"] as? Double - else { - return nil - } - - self.dt = dt - self.tempMin = tempMin - self.tempMax = tempMax - } - - required init() { - self.dt = "" - self.tempMin = 0.0 - self.tempMax = 0.0 - super.init() - } -} diff --git a/Lesson12/Podfile b/Lesson12/Podfile deleted file mode 100644 index 3eb2e81..0000000 --- a/Lesson12/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -# Uncomment the next line to define a global platform for your project -# platform :ios, '9.0' - -target 'Lesson12' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - # Pods for Lesson12 - pod 'DTTableViewManager' - pod 'SnapKit', '~> 5.0.0' - pod 'RealmSwift' - -end diff --git a/Lesson12/Podfile.lock b/Lesson12/Podfile.lock deleted file mode 100644 index fc8d3f0..0000000 --- a/Lesson12/Podfile.lock +++ /dev/null @@ -1,36 +0,0 @@ -PODS: - - DTModelStorage (8.0.0): - - DTModelStorage/Core (= 8.0.0) - - DTModelStorage/Core (8.0.0) - - DTTableViewManager (7.0.0): - - DTModelStorage (~> 8.0.0) - - Realm (4.3.1): - - Realm/Headers (= 4.3.1) - - Realm/Headers (4.3.1) - - RealmSwift (4.3.1): - - Realm (= 4.3.1) - - SnapKit (5.0.1) - -DEPENDENCIES: - - DTTableViewManager - - RealmSwift - - SnapKit (~> 5.0.0) - -SPEC REPOS: - trunk: - - DTModelStorage - - DTTableViewManager - - Realm - - RealmSwift - - SnapKit - -SPEC CHECKSUMS: - DTModelStorage: 3b86a1e37496532bbd74cadc5b9310238d5ba780 - DTTableViewManager: 0ada743292338c2e7b5494f41544afc9d3055fbb - Realm: 31dc40934081ef740f60feedc46d88473cbfeb40 - RealmSwift: b5199e9a41f67b99f51acf6874a6166f5fbe93d1 - SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb - -PODFILE CHECKSUM: 449a2a07f00ced4688fc3cfec25ae2fabb124a77 - -COCOAPODS: 1.8.4 diff --git a/Lesson12/Pods/Manifest.lock b/Lesson12/Pods/Manifest.lock deleted file mode 100644 index fc8d3f0..0000000 --- a/Lesson12/Pods/Manifest.lock +++ /dev/null @@ -1,36 +0,0 @@ -PODS: - - DTModelStorage (8.0.0): - - DTModelStorage/Core (= 8.0.0) - - DTModelStorage/Core (8.0.0) - - DTTableViewManager (7.0.0): - - DTModelStorage (~> 8.0.0) - - Realm (4.3.1): - - Realm/Headers (= 4.3.1) - - Realm/Headers (4.3.1) - - RealmSwift (4.3.1): - - Realm (= 4.3.1) - - SnapKit (5.0.1) - -DEPENDENCIES: - - DTTableViewManager - - RealmSwift - - SnapKit (~> 5.0.0) - -SPEC REPOS: - trunk: - - DTModelStorage - - DTTableViewManager - - Realm - - RealmSwift - - SnapKit - -SPEC CHECKSUMS: - DTModelStorage: 3b86a1e37496532bbd74cadc5b9310238d5ba780 - DTTableViewManager: 0ada743292338c2e7b5494f41544afc9d3055fbb - Realm: 31dc40934081ef740f60feedc46d88473cbfeb40 - RealmSwift: b5199e9a41f67b99f51acf6874a6166f5fbe93d1 - SnapKit: 97b92857e3df3a0c71833cce143274bf6ef8e5eb - -PODFILE CHECKSUM: 449a2a07f00ced4688fc3cfec25ae2fabb124a77 - -COCOAPODS: 1.8.4 diff --git a/Lesson12/Pods/Pods.xcodeproj/project.pbxproj b/Lesson12/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 15e9864..0000000 --- a/Lesson12/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,2367 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 0047B13AE63FA26AAA8DB8F11B430C02 /* work_queue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 147BC758236001BE6BC568B869EB5B6D /* work_queue.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 00FE6361A6938BF20B5CB06A46872D38 /* Pods-Lesson12-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E6F1519F5C5F6C2B02A5BA985B3B40E /* Pods-Lesson12-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0111886BCBA7E203D31D37D93130988C /* RLMSyncSubscription.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 8B7AE71079AFC8D636C516AD4F0761CA /* RLMSyncSubscription.h */; }; - 015A0369EB034ABD53223DCC1697046C /* RLMRealmConfiguration+Sync.h in Headers */ = {isa = PBXBuildFile; fileRef = BC99A40943538DC1761A8F623E480CC9 /* RLMRealmConfiguration+Sync.h */; }; - 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CA3FFE66F25DC21E5B98E8F15E536A3 /* ConstraintLayoutSupportDSL.swift */; }; - 0250F77A3345CB64BCB6492E9D8D3FD3 /* RLMManagedArray.mm in Sources */ = {isa = PBXBuildFile; fileRef = CF192D8F67FA60E5D01C25180A34ED7D /* RLMManagedArray.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52DBA640AED2F6F34036625774076D4D /* LayoutConstraint.swift */; }; - 03EFB7066E10386B323F367BF3376713 /* DTTableViewDragDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A2F892D6FCA6C28ED679E370B18CDE9 /* DTTableViewDragDelegate.swift */; }; - 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - 049F23964BF99F1E034E600749DF4778 /* RLMSyncUtil.mm in Sources */ = {isa = PBXBuildFile; fileRef = DF86A4B189E4AC67FF10D9B507853FA2 /* RLMSyncUtil.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 04E5FEE26799A378F03CDE46F25C5F91 /* Section.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFD0CAAC8C1C696AC1294007FB1D6EA4 /* Section.swift */; }; - 05E537D6954BE54C14B0C2D0BD748B27 /* RLMObjectStore.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A6D3AA87CE10E84A55129189076FA01 /* RLMObjectStore.h */; }; - 05E61A3ADD15D7CB6C969A76E95EAAF9 /* RLMAnalytics.mm in Sources */ = {isa = PBXBuildFile; fileRef = F603994BDE622506612E83CCEA121CB2 /* RLMAnalytics.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 0624DA01ECA96AE03CA4CD86AE0DD698 /* RLMRealm+Sync.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B9A4143194FD94ED0FC12F263C7222B /* RLMRealm+Sync.h */; }; - 066893C78B248DE542B8229D75F2040A /* RLMSyncUser.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 1F2A650980474B09474FBD14355A3EFB /* RLMSyncUser.h */; }; - 069E8403A49DE5921F142696F2518EBF /* thread_safe_reference.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3A905DD29462C9D166D93B5223857DEA /* thread_safe_reference.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 06A9FC6B0E5EB29BFD63F96CB8DFFAE1 /* AnomalyHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 110A8836C3844ECCE172E4B315C14D5C /* AnomalyHandler.swift */; }; - 0ABD1A69D54921D4230DA47F703B47C8 /* RLMCollection_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = F8606ABDC6A34CDF6B0BFFE5569D5B6E /* RLMCollection_Private.h */; }; - 0BFF24D5C16257D168CB59FEAE373808 /* system_configuration.cpp in Sources */ = {isa = PBXBuildFile; fileRef = AA4BB6A5AD4DA3521D25B7A7B31598D2 /* system_configuration.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 0DB86F0299A73422AD89CCF3CEC5BC5A /* TableViewConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAEC53929DBDB1101C311029FB1A5A5A /* TableViewConfiguration.swift */; }; - 0E031C031301B192EA4337E12804CC70 /* binding_callback_thread_observer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9FC166983E5A48BFDE3ABE9112FBDD0E /* binding_callback_thread_observer.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 0E9649E3134E8BC6C9380EC78E376481 /* RLMQueryUtil.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1516938D464E51B0644674C984843905 /* RLMQueryUtil.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 0EC3A2761F6C42CDFC6CAF132CB0B83F /* collection_notifications.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4714D922CCEE7B36C134A0E4C7671DDB /* collection_notifications.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 0FEACBA97148B598AA27162DDE4C7E4F /* RLMRealmUtil.mm in Sources */ = {isa = PBXBuildFile; fileRef = DF0EF208569C6F026D7BF14A7737D674 /* RLMRealmUtil.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 1124DA5AA0690636691F8C16B54BE187 /* RLMRealm_Dynamic.h in Headers */ = {isa = PBXBuildFile; fileRef = DB5FBF630A2A4A790E0AA44490038B22 /* RLMRealm_Dynamic.h */; }; - 12A94B085B960FFF94A98BCF9F6E27E0 /* ObjectiveCSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A7D4E01FFA210388B2222C35DD50FD6 /* ObjectiveCSupport.swift */; }; - 13AA9F89B18BDC2687A40F18CB1CE6C8 /* transact_log_handler.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 76A0680EEF6D60432C0739BA193D8AFB /* transact_log_handler.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 1426E7D4526CCF2C32D559E2B538580B /* schema.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 24520BA6825D00730ED9C7DFF85EB308 /* schema.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 149DFEA17780F138C2D65F734477EC74 /* RLMThreadSafeReference.mm in Sources */ = {isa = PBXBuildFile; fileRef = 32DE6835AFD8DCE99328A08562FC7304 /* RLMThreadSafeReference.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 14E03A84F0AC43960D7EC2D1D222C61A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B437E9E2DD5D50C699667686417A6BDE /* UIKit.framework */; }; - 14F7AFD9FFD7EB0B3CB02DA66BEE976F /* keychain_helper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BD5C19305B180CC0D2D4142A0CDA0DE2 /* keychain_helper.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 1528AD86DB13AF6FD139D29AD8F17999 /* RLMCollection.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F0E2A67636815327AF51E8324AC7DFF /* RLMCollection.h */; }; - 163DF9C4EF2939A35285E5487D8AC718 /* RLMRealmConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 372E3888C543E4F7354D55B652942A31 /* RLMRealmConfiguration.h */; }; - 164553A0AACB1FB27D68230B7439AB7B /* RLMObjectBase_Dynamic.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = EC2BB33A92D7A93B652127EB59489BC9 /* RLMObjectBase_Dynamic.h */; }; - 168480E2A975C77B32F37553CE06B5AC /* DTModelStorage.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73226A3C25999F7DBB805EBC80CC4255 /* DTModelStorage.framework */; }; - 168F5EE58AB4133A14140D47953CE310 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - 17CE12E3F777B243FCE5AC6201AEF303 /* RealmConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A1B167BD2DDEB507724316F8048D06 /* RealmConfiguration.swift */; }; - 17E74A0C302C627A1374F313FA16E7EE /* SwiftVersion.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCB05CE00499B4F9A6549B894AB13DDB /* SwiftVersion.swift */; }; - 1856BEBADAA6691FD5C43D4D737029EA /* RLMObject_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = F7CA0BB82F5F89D00F5037115FC02A38 /* RLMObject_Private.h */; }; - 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FC9128FB437A8E6B3C211DC0C88004E /* Typealiases.swift */; }; - 1A6FAC76E6834F1EDF069FF9FB4A189B /* RLMSyncConfiguration.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4D2B381E2885D444F3F4569560E331A4 /* RLMSyncConfiguration.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 539DD206E6B4E2DE0FC82DF732FC8E76 /* ConstraintLayoutGuide+Extensions.swift */; }; - 1B357C428FB0595C0C71A50B3065C522 /* DTTableViewManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83BBA83C8AD1E1A7BAC41F307D14F669 /* DTTableViewManager.swift */; }; - 1CB5C6760130C03AE56AD4870F1C1457 /* RLMCollection.mm in Sources */ = {isa = PBXBuildFile; fileRef = 33A2DD2812754AECA0F1F9ABAA9139E9 /* RLMCollection.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 1E68DAAF9FA67C987AED67B4DA41F855 /* RLMSchema.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 96820C3C661F733FF50D3B2EBC178AD0 /* RLMSchema.h */; }; - 1F2F06D3F5D78980F67821B553F0883B /* NSError+RLMSync.h in Headers */ = {isa = PBXBuildFile; fileRef = C6EC7AB761B7755F64E1AA0339DD01C5 /* NSError+RLMSync.h */; }; - 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6C0C2966A4A5D3599B61ED5EAE870BF /* ConstraintInsets.swift */; }; - 21F8ECB7A03D833A3932C2AAF943EA86 /* RuntimeHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 273DA2E6224B9EA0181B06B50F8C5B39 /* RuntimeHelper.swift */; }; - 22F963CEA7CC2CA57EBEAEE4DA490029 /* list_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 205924444AE13CD4400A7C8037655DEF /* list_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4825BA092AE4221CD1C2FD69CAA8C577 /* ConstraintPriority.swift */; }; - 23389E314CEF385E4A3C3F0904491D1A /* SingleSectionDiffing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37267A6188287FEB6B93C67DBE9A517A /* SingleSectionDiffing.swift */; }; - 233EDDBD8F4DBB88B88936BF67D38C43 /* DTTableViewDropPlaceholderContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2C7E26B2784AEE83ED67176365A58B /* DTTableViewDropPlaceholderContext.swift */; }; - 2417A9EEC50FA31DD6F764CE4A64762F /* RLMMigration.h in Headers */ = {isa = PBXBuildFile; fileRef = 04A8F2229E09694DEB1FF0F56FAB5DF7 /* RLMMigration.h */; }; - 24F7392348EAB0ED45B6B1DCA4391914 /* RLMSyncSession.mm in Sources */ = {isa = PBXBuildFile; fileRef = 19674D3C9E9AA3C53DA5162DE029918E /* RLMSyncSession.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 2663DC483B1BD5548693365C8F17F7F5 /* DTTableViewManagerAnomalyHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6BB363083C035E6988F54E9A44982FF /* DTTableViewManagerAnomalyHandler.swift */; }; - 268A0739FE706CAD204F61702EEA9CB6 /* RLMRealmConfiguration.mm in Sources */ = {isa = PBXBuildFile; fileRef = E37C9F700248227792DC60FFE6D5F8D8 /* RLMRealmConfiguration.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 26F0BB95414AA62ACBB0983D8385C6A3 /* RLMObjectSchema.h in Headers */ = {isa = PBXBuildFile; fileRef = 3040BA8B8BF3441A8A25C292951EE282 /* RLMObjectSchema.h */; }; - 27426BDEE639040D91F43848108A18D0 /* RLMObjectBase.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = A8285F9C4A29355AF7659A1EBD2E179F /* RLMObjectBase.h */; }; - 286807D3C2B82C0C52156AC968CFA068 /* RLMObject.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 7740C7998C1E0ED03EB9222CC2BE9B64 /* RLMObject.h */; }; - 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F257C890C5BA74E7CF941B82C741C56 /* ConstraintAttributes.swift */; }; - 2B374445507BAC21E6FDCE6318EB1023 /* RealmCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67F84B83E4860C3D13E46A83C6033C47 /* RealmCollection.swift */; }; - 2B3B6A1F3CE5A236CF1B97B26E355E7D /* RLMUtil.mm in Sources */ = {isa = PBXBuildFile; fileRef = 74C1F8612B5FAC29958A3688C854B0D3 /* RLMUtil.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 240AD0928397EDD73DBA6FA830C2F200 /* ConstraintInsetTarget.swift */; }; - 2CEAEFD70CD74376767EA7D85FA8831E /* sync_file.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7C710889361EE8207B98ABA2C4D2A677 /* sync_file.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 2D1E4D34FC706A4C5430B6BCCA61F940 /* EventReactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6F478FC4B97F58B619554CC291ECCF1 /* EventReactions.swift */; }; - 2E638CEA645E715DB0E123AD6A08647D /* RLMArray.mm in Sources */ = {isa = PBXBuildFile; fileRef = B28830DD90409A0543F7F8F82849A7EC /* RLMArray.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 2E6C5B6B0FF9C24A29C82F72B5247E80 /* CoreData.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BAD19CEF1DE12B2691DB29FEC292B840 /* CoreData.framework */; }; - 30AA515CC73339676F3E4AD889BA0BD1 /* DTTableViewManager-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 083618C0629088D7CF458809465AF73A /* DTTableViewManager-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 329FC3E722DE36B8B00674D23CCB031E /* RLMSyncUser.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F2A650980474B09474FBD14355A3EFB /* RLMSyncUser.h */; }; - 33FED9F98332B8339C1D056B51E97B4C /* RLMPredicateUtil.mm in Sources */ = {isa = PBXBuildFile; fileRef = 180EA465872694E44858D9057786BFA5 /* RLMPredicateUtil.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 354BE05906E0CB457569A8E29F9D8532 /* Realm.swift in Sources */ = {isa = PBXBuildFile; fileRef = C40098B8DEB3229D47B663D80E0813D9 /* Realm.swift */; }; - 3820FCCABF659770A7A74440C3001C87 /* RLMSyncUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = AA94BDFD0BC51FFBD31ED2D027E28B63 /* RLMSyncUtil.h */; }; - 3BD063008F14A0D06586F954907110D9 /* Sync.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9368BE5CA3CC81EEFBE9871BA951F4E /* Sync.swift */; }; - 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6913ADD3EBC59D0E9D381BEA66098F50 /* Constraint.swift */; }; - 3C73AB0188912D4205DC2503BA8A27E4 /* Pods-Lesson12-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 911B7D9BFD745E8AA0A37559DB898EBA /* Pods-Lesson12-dummy.m */; }; - 3CAC503A5DAA8D2DFB6895C2F4F46591 /* LinkingObjects.swift in Sources */ = {isa = PBXBuildFile; fileRef = 072B68414DD27FF40271269943D5481E /* LinkingObjects.swift */; }; - 3E05EFB380BB32DD4E9D12038BB6A6C7 /* RLMMigration.mm in Sources */ = {isa = PBXBuildFile; fileRef = D799CECCDA496FD6FC0E4A8E9CF9707C /* RLMMigration.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFC738E414DCDEDDF7D8D2E6C1053446 /* ConstraintView+Extensions.swift */; }; - 4092FC1A7951B5402262D0F4148D3E68 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - 42243F8F8A3A333A3543A3798E0BB9B2 /* ObjectiveCSupport+Sync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 394E9BF21C25ED2E5345E53020A5CC3D /* ObjectiveCSupport+Sync.swift */; }; - 430FBA64DC0FC3E07D39B0DAF4657C81 /* RLMNetworkClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4E45EF266A78A58B8C91A2F04FB0D029 /* RLMNetworkClient.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 436803A8CCC81A15C5EA20B71B444217 /* RealmSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 85B46BBDF4E92F9E14C5B3E25BE55588 /* RealmSwift-dummy.m */; }; - 4516012F99A1A9B2EA4313B79E29A580 /* RLMObjectSchema.mm in Sources */ = {isa = PBXBuildFile; fileRef = 40E517C7A659C9196BE238502EC31611 /* RLMObjectSchema.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 45792F139DDBCE8090EA0D61771C5A9E /* external_commit_helper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8A72F70546CF49ED43127DC915FAB41D /* external_commit_helper.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 45EDE7CCF5471B181EA12B3C8FC66F4D /* Util.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAC764CE511370D9847A2392D1D55C73 /* Util.swift */; }; - 4702C63F91C7967ECD570C5CD8D092E3 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7962661A838C6885CDF1F8012F9D2108 /* Security.framework */; }; - 487D53153D55CE66F0EB58DD50702B51 /* RLMObjectBase_Dynamic.h in Headers */ = {isa = PBXBuildFile; fileRef = EC2BB33A92D7A93B652127EB59489BC9 /* RLMObjectBase_Dynamic.h */; }; - 4A954E1410CC831251D1883F3341A975 /* RLMSyncConfiguration_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 940E4029EA051813FE224A3B6F7B61E6 /* RLMSyncConfiguration_Private.h */; }; - 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 71BF55D66A00B7440DF166FE1DFCCB2B /* SnapKit-dummy.m */; }; - 4C9515430BF0E0C832C3DE8755A2CAF2 /* DTTableViewManager+Drag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1680DE752CFF211598AA28BA23DC0423 /* DTTableViewManager+Drag.swift */; }; - 4FFF5D9D67F39D2CF4D4C016EECACB00 /* RLMPlatform.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = BEA345D3718292AC478C1585AA32958B /* RLMPlatform.h */; }; - 50A8B48A98FC0D65D138AB7D030497AA /* RLMObjectBase_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 6C71F5065524F1657625088FAC3E6808 /* RLMObjectBase_Private.h */; }; - 50B7D08F90D2D6435BBE891E1547332E /* RLMAccessor.mm in Sources */ = {isa = PBXBuildFile; fileRef = CE58AA507A58423CA7B5FEDDE9E23058 /* RLMAccessor.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 5120291734D77494B3D96DFCC2EE9857 /* RLMMigration.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 04A8F2229E09694DEB1FF0F56FAB5DF7 /* RLMMigration.h */; }; - 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91E61A2A30FDB2108A53B95E11B2CCB7 /* ConstraintMaker.swift */; }; - 522243013D8403542D273D29C2062AE9 /* BackwardsCompatibility.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC0D2F818024F7F7CC0A029A727816AA /* BackwardsCompatibility.swift */; }; - 5290BB41346D30D8DAF45533FB141177 /* results.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4B91595DE4A0B5B7F17B4D74DB1ADB8F /* results.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 530EC7E20DB092A84F13DFAF89701619 /* Realm.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8EBFE37C26992B4DD024F56CE87F9AD4 /* Realm.framework */; }; - 5311190402B888CC56C42241BB124F7A /* DTTableViewDelegateWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6C41A5F855BA7C4A3D21CC85CABA10C /* DTTableViewDelegateWrapper.swift */; }; - 56D79D21489B99536E56D11613733DD3 /* RLMSyncManager.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 5BA121DEBDEFE4FE4C6CB10F50CB0C20 /* RLMSyncManager.h */; }; - 57382B29E1A24DE8F2EA76CFECA7F686 /* StorageProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 884F556E058A9DDA81ACB4B57760E082 /* StorageProtocols.swift */; }; - 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 642B46585C61DCCE79A43F69CC13CD53 /* ConstraintLayoutSupport.swift */; }; - 57B3FEF620AA9F256E6DFC810DF30C04 /* RLMArray_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 3D9BC1AB715B9C60E650377023BA6453 /* RLMArray_Private.h */; }; - 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7230E3B4D79A605F74D8C9E619F81F85 /* ConstraintConstantTarget.swift */; }; - 5861161136ED8784C63A95CF9EE918C8 /* shared_realm.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 778399867C21AA8021204104ACC147DA /* shared_realm.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 59EAF48CDE5B2776073636EF02FABB06 /* RLMSwiftSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = B262BA381A559D0635AE9B56A311892D /* RLMSwiftSupport.m */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 5A03607F11B77EE686FEF0E50BE7F9FB /* DTTableViewManager+Registration.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4F96F975B2E88A8C9B50AB07B95B3CD /* DTTableViewManager+Registration.swift */; }; - 5AAD8DB30DDD23AEB92406F89174D7EF /* sync_config.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 644F8E01BE16AC1DC2EC57F200E6A6C1 /* sync_config.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 5AEBFA2535D6E5B07A2E8AE5D7BBCF51 /* BaseStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = F25AAD1510D8A8961B046208449A88E4 /* BaseStorage.swift */; }; - 5B35E48760312B860F68C7472603D686 /* RLMObject.mm in Sources */ = {isa = PBXBuildFile; fileRef = BEE8A8E0F76002E7834FAFEB10374970 /* RLMObject.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 5B96D0F75CB99CD9B63EED98E14591BA /* RLMUpdateChecker.mm in Sources */ = {isa = PBXBuildFile; fileRef = ED415698AA3EB5DE427CF87AE6B2B877 /* RLMUpdateChecker.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 5F9C606B3BD1513683DCD968D368AE9B /* RLMSyncSubscription.mm in Sources */ = {isa = PBXBuildFile; fileRef = ADA4CA7376B38B6E954AB07A24FA8FB5 /* RLMSyncSubscription.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 615BB4C1722E9019DB212D73FACE7780 /* RLMSyncCredentials.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = EAAB3F222D60BB795C12F584D81E0542 /* RLMSyncCredentials.h */; }; - 63A047238792804F506E0FBCE39F78FF /* RLMSyncUtil_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 83226A8F1E0F2767A08452B45B57BC29 /* RLMSyncUtil_Private.h */; }; - 655154DB907EF05CED9DA1664D45DC05 /* RLMRealm.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4F74FB6E257915D5C1974672A2520FA5 /* RLMRealm.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 665FFAEB9248C6D0998E934BB75D3F75 /* RLMSyncCredentials.m in Sources */ = {isa = PBXBuildFile; fileRef = 3B31FB10E2273F59614E18103B23BC93 /* RLMSyncCredentials.m */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 671CD8B463F59407A51B7C18F8DBD7E1 /* RLMSchema.h in Headers */ = {isa = PBXBuildFile; fileRef = 96820C3C661F733FF50D3B2EBC178AD0 /* RLMSchema.h */; }; - 67AB6A2540052673DDB030ED4BB1409C /* RLMRealm.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = D219B16E47E5854B2B9B80326D823559 /* RLMRealm.h */; }; - 6808C5BEF3D1556A431CD453E63E7E38 /* NSError+RLMSync.m in Sources */ = {isa = PBXBuildFile; fileRef = 5194A0EB6E38A52770B77C79FCCAF779 /* NSError+RLMSync.m */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 683DF482E4E5C25C03F3729230C63CE4 /* RLMCollection.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 1F0E2A67636815327AF51E8324AC7DFF /* RLMCollection.h */; }; - 686A82F039EDE84C9AC2711B56DDF860 /* DTTableViewDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2977EA8AA20923C44E80AAFC1A6F3222 /* DTTableViewDataSource.swift */; }; - 688EE044B4D96D5DA2E7B700CCD3B2BF /* object_schema.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3CB2906AE3A9E50A11DC9ED209793702 /* object_schema.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 68C57DF30A9CA33AACD78464E1AFF476 /* RLMObjectSchema_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = F06E86C4C5188AF4009102863AB52FFD /* RLMObjectSchema_Private.h */; }; - 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F967EC8E34615D73A752C6E619B83F8A /* ConstraintMakerExtendable.swift */; }; - 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4B268EAA2058C23CC635EBD65D0B662 /* ConstraintRelatableTarget.swift */; }; - 6B938D16C9BEE9AF42415C99D1F6DA52 /* MemoryStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63315A69198070A681994D590BBD42ED /* MemoryStorage.swift */; }; - 6DDD3EAC7634C6B8EBD88EB32F758913 /* RLMAccessor.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = B5882A01A23F29222C693AC6453B2C22 /* RLMAccessor.h */; }; - 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDBF900C13704E3C349CCC1AAAE09B2D /* UILayoutSupport+Extensions.swift */; }; - 6E9102E055262D2DEAD56E7D56364357 /* SingleSectionStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4489D501A65F0FFFCB1B928E1B1CF8E8 /* SingleSectionStorage.swift */; }; - 6FC528DFE6BAEA42D1373B2658656903 /* RLMArray_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 3D9BC1AB715B9C60E650377023BA6453 /* RLMArray_Private.h */; }; - 70B0B87B78BFDEADABD02EC1425B7C0E /* sync_manager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD68071084759E025904A0CF5E4CACE /* sync_manager.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 70BCE5BACB52D99796645EE3A451B783 /* Object.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA0DF3C2211484ED19DF5E089344E170 /* Object.swift */; }; - 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B005D46C74CFA9A8251EBA2B7DF0CFA /* ConstraintDirectionalInsetTarget.swift */; }; - 73AC76F3FEC279A4AF42D33F3743EFB1 /* RLMObjectBase.h in Headers */ = {isa = PBXBuildFile; fileRef = A8285F9C4A29355AF7659A1EBD2E179F /* RLMObjectBase.h */; }; - 73E187F34F85D27E664867D8FAD02B15 /* SectionProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = DED40C8AFCCC2C704B7DC2D93E75DE56 /* SectionProtocols.swift */; }; - 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C283EA9E079F3598F412CEFF2167CD91 /* ConstraintMakerRelatable.swift */; }; - 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AB046C46DB77ED8BA8F9BDA9F271138 /* ConstraintLayoutGuideDSL.swift */; }; - 79120D7382A3564038E796B8872271AC /* Property.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59DD1951661B55FBB6E5561C5E6A6641 /* Property.swift */; }; - 7912D79016C638A8B5C9221D6B637B1D /* RLMSyncPermission.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = F00D131E27474BBE252362168003516F /* RLMSyncPermission.h */; }; - 793929EC869818B425DBE85F6447FA84 /* RLMProperty.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 3B8C0C088A43AF55F2F1804C536FF82B /* RLMProperty.h */; }; - 7A2C7D86EEC730D0860FDBCCFA634D19 /* RLMObjectBase_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 6C71F5065524F1657625088FAC3E6808 /* RLMObjectBase_Private.h */; }; - 7B3161F2A225550C77AFEA5B4376A50B /* RLMSyncCredentials.h in Headers */ = {isa = PBXBuildFile; fileRef = EAAB3F222D60BB795C12F584D81E0542 /* RLMSyncCredentials.h */; }; - 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D54E81BDD6D4184B6D7112334877DC3 /* ConstraintMakerEditable.swift */; }; - 7D468FA6413DFA8873F8672B6CBF2468 /* sync_permission.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3D2FDC0D84F98632EE7330317E6C2302 /* sync_permission.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 7EC9F94A0049BFFDFD0B8795F08B4A37 /* RLMProperty.mm in Sources */ = {isa = PBXBuildFile; fileRef = 7C0DA5F6F3AAEF85A81BCA4825B4086D /* RLMProperty.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 7ED9728B8FDE98CAAA531D19854AFA4A /* RLMProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B8C0C088A43AF55F2F1804C536FF82B /* RLMProperty.h */; }; - 7FE1D9C8A8C25D367EEA42987989907F /* RLMResults.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 0B216D4857F045F87E7D90352446172F /* RLMResults.h */; }; - 8069CAE326CAF7B3FBAB1DAADDB0A15F /* RLMSyncUtil.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = AA94BDFD0BC51FFBD31ED2D027E28B63 /* RLMSyncUtil.h */; }; - 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52D11ADC324C5332A4F6299A79430067 /* ConstraintDSL.swift */; }; - 834B6599A6B209A582FA2DAD81BE47BC /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B437E9E2DD5D50C699667686417A6BDE /* UIKit.framework */; }; - 84E1FE5DD6DE9A0C7764A29FC9F11155 /* RLMResults.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B216D4857F045F87E7D90352446172F /* RLMResults.h */; }; - 84E8B926FACE4FA809F931BFB6CEF96D /* RLMSyncSubscription.h in Headers */ = {isa = PBXBuildFile; fileRef = 8B7AE71079AFC8D636C516AD4F0761CA /* RLMSyncSubscription.h */; }; - 86C28A1FA2ADAF175EB56237CFD9FB36 /* uuid.cpp in Sources */ = {isa = PBXBuildFile; fileRef = EAD5109EB15C46D504DA80E174E0273B /* uuid.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 862AFD197149B8569B424BDE9510D221 /* ConstraintOffsetTarget.swift */; }; - 87B23A6C7190531AD4546209E6728EFA /* weak_realm_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FB755329134A0AE7AE1A72007512C8BA /* weak_realm_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 88C46C846B36D44D755C2C62B8BFD50A /* DTTableViewDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD94DA44E270CDB057579FA88B39883E /* DTTableViewDelegate.swift */; }; - 89C03071BA28C58414C5F9A4B8614B90 /* sync_metadata.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDAE99C2028C04AA0EE9094DC3758018 /* sync_metadata.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 89DE4BDBF92376984DFFA4D6B9A789E7 /* RLMCollection_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = F8606ABDC6A34CDF6B0BFFE5569D5B6E /* RLMCollection_Private.h */; }; - 8A782F5B16AB7C0003017D728FBD849B /* DTModelStorage-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A45825178B6ADCC06CD7AA31113287A9 /* DTModelStorage-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8B4FC46A3DB2BD43F4046DAFA4FC8F8F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - 8D4B51F2A6E57273E12A76C160B2CC4F /* RLMObjectBase.mm in Sources */ = {isa = PBXBuildFile; fileRef = E4C1D302E7DA9E44265A5964B8A5FD93 /* RLMObjectBase.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 8D7A7EEEC4C2BD76CC49368163BEF17B /* DTTableViewManager+Delegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F98BA3CDA21C9F5C0A564A02B92E5AFA /* DTTableViewManager+Delegate.swift */; }; - 8DBB2BB97A17DCEAE003D2116E709489 /* sync_session.cpp in Sources */ = {isa = PBXBuildFile; fileRef = EBF63AD578849DDDD82044FF6C610E9A /* sync_session.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 92142DB3CEF7BA2BB8942694C45D3065 /* RLMRealmConfiguration+Sync.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = BC99A40943538DC1761A8F623E480CC9 /* RLMRealmConfiguration+Sync.h */; }; - 974071500397CA88E104EB9828047CF9 /* RLMConstants.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 3F57B49A0FA692575F0606763D7A9F07 /* RLMConstants.h */; }; - 97F26585AD4B634C86136CEF0E5B1EF2 /* RLMSchema.mm in Sources */ = {isa = PBXBuildFile; fileRef = E65CEF9DAA5E4147882A1C0848D8F2AF /* RLMSchema.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3F91BBE7AF9F154EF08C316238670E2 /* ConstraintItem.swift */; }; - 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6726AFA0176A345BC0CA041F40C91D08 /* ConstraintConfig.swift */; }; - 9BAED39893E3A38E86EC0CB7F1B4664D /* RealmSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 467846062075DF9A615F0712528D51CD /* RealmSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 9C0DED0B53B311D880B84EAD42A5C367 /* RLMArray.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = BC0F4D611C9EA3BAFA7BC6C34945BBE5 /* RLMArray.h */; }; - 9C5DFFE29827A2D989C2DE6910ACA270 /* RLMRealm+Sync.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 0B9A4143194FD94ED0FC12F263C7222B /* RLMRealm+Sync.h */; }; - 9D89150563C25286D022E024EAAE0224 /* RLMSyncManager.mm in Sources */ = {isa = PBXBuildFile; fileRef = 664C66D52716CF12032C6F83873CF72A /* RLMSyncManager.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87EBD3107688814C52D9C3DFFE4C05A3 /* ConstraintLayoutGuide.swift */; }; - A2F591F45DBBFB19EFBBC5CCF8BA2793 /* RLMObservation.mm in Sources */ = {isa = PBXBuildFile; fileRef = EE5C4C8B95DB8FB3884ACDC2BFD56907 /* RLMObservation.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - A3F37516CDD7B7C6E9E67F7937775CB8 /* RLMThreadSafeReference.h in Headers */ = {isa = PBXBuildFile; fileRef = 1CECF04B4631D24458F6D379B1BF6FAF /* RLMThreadSafeReference.h */; }; - A524B1A8F063D71F7854055E86AEA72F /* RLMListBase.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = E6CA98FF964046EC7C66391B28BF094F /* RLMListBase.h */; }; - A5F84ADB1D6B8B23FC3AC2ACE718E988 /* StorageUpdate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 912A7824E526E706ADF17636A87C8AAC /* StorageUpdate.swift */; }; - A6645ABF85B1F4050B50D4DD62851C62 /* RLMObjectStore.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 4A6D3AA87CE10E84A55129189076FA01 /* RLMObjectStore.h */; }; - A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 439DD2ED964B85F221832C11D774EB8E /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - A8E82498433F11FB31D93E4F8DE0AE6F /* RLMObjectStore.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2FC04F46E165B5BC076542E93F20D045 /* RLMObjectStore.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - A9F434D093BEFF605C24C2D0B71B4767 /* RLMRealm_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7626FBCB0DB4F4FB4A0966F840256122 /* RLMRealm_Private.h */; }; - AA8CB96B506F6AF065AB1F8C9F9495CB /* sync_user.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8907267A50CC886474A3D542965A19A9 /* sync_user.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - AABEE951C89957EB5E1FCD3D25CD45B4 /* Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4935C70EBBD3BDC88BA42FB0D34B93DE /* Schema.swift */; }; - AACEBC8596A841C7B61CD7E1A9AE2DE4 /* collection_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F2F2E1C2F9F3865A6D08EE0427069C34 /* collection_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - AADBCD1B21CD4A8302788D60CBA914EB /* RLMSyncManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 5BA121DEBDEFE4FE4C6CB10F50CB0C20 /* RLMSyncManager.h */; }; - AB378EF4F418F0A00D68FA7B37A60491 /* RLMOptionalBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 385A3E979126AC8011F7211B7EC28505 /* RLMOptionalBase.h */; }; - AC0F5BE9969AFF9FC4DBF4D3115917ED /* ObjectSchema.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB68296FEF989F38D67625187DFDC2A4 /* ObjectSchema.swift */; }; - AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC0E36BD9D81DE0383BBAE911F2DF9C4 /* ConstraintDirectionalInsets.swift */; }; - AC7D415C826932227566EB2B916A7C26 /* SortDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BBF9E1FE4BE88841D92BD4F7D49DD12 /* SortDescriptor.swift */; }; - AD439220D07411D7CAFB3DEDC427B14E /* SectionModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BD817C7300CEFDC2B38E4BA2CE97F12 /* SectionModel.swift */; }; - ADC590829802B94CE186B3E5DBC57D7B /* RLMConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 4AB088E51E743F45688903D4D8D2D66B /* RLMConstants.m */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - ADF1076FF0CE456B5E0E046EEC33CD97 /* ThreadSafeReference.swift in Sources */ = {isa = PBXBuildFile; fileRef = D657CEEA4664E23DDBCAF74EB352D3B5 /* ThreadSafeReference.swift */; }; - AE96328EC72F4BC41BD1A496D45C9325 /* RLMSyncSession.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = E5727F4907EF17975910B5D42BB8E58C /* RLMSyncSession.h */; }; - AFDC58FF42E02745753EE6C5A502C3BB /* RLMSyncUser.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF85951E33188510ED514531C7A57C32 /* RLMSyncUser.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - B34A0A6D659D5D2F79FEEEAF83B87B43 /* RLMObjectSchema_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = F06E86C4C5188AF4009102863AB52FFD /* RLMObjectSchema_Private.h */; }; - B3D636D90E51741683F376016D836355 /* partial_sync.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1C22ACA9772C6A64DAC86BCE215D0644 /* partial_sync.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - B4A64C9136805CB6BE283579A76C7658 /* RLMListBase.h in Headers */ = {isa = PBXBuildFile; fileRef = E6CA98FF964046EC7C66391B28BF094F /* RLMListBase.h */; }; - B4AC0F92C5EC63BD3AEBA713BE3F380E /* CoreDataStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48D9995270C83F315AFE4069D26661B2 /* CoreDataStorage.swift */; }; - B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EEB0CADB7C3F9B63A159DF537792DC4 /* ConstraintDescription.swift */; }; - B5AD279F634D06859F4F4FB1E02D3FF0 /* network_reachability_observer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D1B48050A06FB75408DE8922A1F9FFA3 /* network_reachability_observer.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - B5DE9220D13AF658E71BF359A73D15E6 /* UIView+XibLoading.swift in Sources */ = {isa = PBXBuildFile; fileRef = 613F36E25BEC199D7DE60CC8F891BB76 /* UIView+XibLoading.swift */; }; - B5FF707FEE8A4B13B59255108E0151E7 /* object_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 16EB414EA3030B111E1FD38437F0FCAD /* object_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - B6DAA4FE8AFA5CD4BF68AF52102E0355 /* RLMObjectSchema.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 3040BA8B8BF3441A8A25C292951EE282 /* RLMObjectSchema.h */; }; - B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03D883FE0F80438243F85F3090469E58 /* Debugging.swift */; }; - B7CC2CEBDCF42DB4BCF7FDCA67991C6F /* RLMOptionalBase.mm in Sources */ = {isa = PBXBuildFile; fileRef = ECF7C4199C3A121F8B6DD2FDEB44B34F /* RLMOptionalBase.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - BB3DB1E3C5D3E73D974FBDEE16859798 /* ModelTransfer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4099E157F7F8FD6588668F172659E2A7 /* ModelTransfer.swift */; }; - BBCC6DDC1E888668E9DB4E11FDECBE76 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61C0831E1A5A5F9BAE73DB2BCBAC1CE6 /* Error.swift */; }; - BCF68AD207127F823C99CEB4AD4AAE5D /* RLMArray.h in Headers */ = {isa = PBXBuildFile; fileRef = BC0F4D611C9EA3BAFA7BC6C34945BBE5 /* RLMArray.h */; }; - BDA4AA86FD634DB021EA0D5ABD701463 /* DTModelStorage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7A505FD515BAA6636F6D6363877150F1 /* DTModelStorage-dummy.m */; }; - BE33F3D2B1E4AA74939221284D92652C /* placeholder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C717E81CC42248D9FFF258716E2F18EB /* placeholder.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - BE5BEFEEC9617E6F2ECA81E0B0ED9928 /* RLMRealmConfiguration_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 57CA8968BD61AF1FB07C178ABAEBDCAF /* RLMRealmConfiguration_Private.h */; }; - BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAACEBB9AA0416B30137379B9A48EE8B /* ConstraintView.swift */; }; - BF08EB397775EFE40ABE7B19BA55B672 /* RLMSyncUtil_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 83226A8F1E0F2767A08452B45B57BC29 /* RLMSyncUtil_Private.h */; }; - C009AEA5BEBB2A205D84DC8073AA4CDF /* ViewModelMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE7FE5AE8A0B542B038BFF6E8E0B46B7 /* ViewModelMapping.swift */; }; - C1147050F9B9901A377C3A9B6E253612 /* RLMPlatform.h in Headers */ = {isa = PBXBuildFile; fileRef = BEA345D3718292AC478C1585AA32958B /* RLMPlatform.h */; }; - C1F1C70CEE7F80A8BBECBF05FCF79142 /* primitive_list_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 981F2F2BE46A6A67F1DB95FB287D72AD /* primitive_list_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - C2A9D7E2A7356B9BD179D726A2418F4B /* RLMAccessor.h in Headers */ = {isa = PBXBuildFile; fileRef = B5882A01A23F29222C693AC6453B2C22 /* RLMAccessor.h */; }; - C2F3CF174A85ECA0C7164F16CC6B00EC /* DTTableViewManager-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C78053BA00DD1B43D3361AFD59385AD2 /* DTTableViewManager-dummy.m */; }; - C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B092C8AF4A98CF45C6D1B26A0112D99D /* ConstraintMakerFinalizable.swift */; }; - C4294B9B857B87FE82EAA022A5E5A833 /* ProxyDiffableDataSourceStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEFB9B52BC635068A822A8830FD5AEF7 /* ProxyDiffableDataSourceStorage.swift */; }; - C49FEFB601CD36B3BE61FB6D4494D733 /* Realm-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FF0033B28EAB2BBC47A324C37EB13EC /* Realm-dummy.m */; }; - C81A970A0C95B15D031D606D0F987BA7 /* list.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 12B715A8E70389228ED31B65F19C360F /* list.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - C900AF92B70CCC35CF46BE3DEF231564 /* RLMListBase.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = E6CA98FF964046EC7C66391B28BF094F /* RLMListBase.h */; }; - CA784FB6D280003577399FC6357DF9E5 /* RLMRealm_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 7626FBCB0DB4F4FB4A0966F840256122 /* RLMRealm_Private.h */; }; - CB2B572644D56110576B961927A43B1E /* index_set.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6881ACD7B5E2E79D91E759FF3A0328BF /* index_set.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - CB40C58EF0AFEC7A5076DA07A08179C1 /* RLMSyncSession.h in Headers */ = {isa = PBXBuildFile; fileRef = E5727F4907EF17975910B5D42BB8E58C /* RLMSyncSession.h */; }; - CC272BD40CB17460F25E41C5F1604501 /* RLMProperty_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 5730C0642E0B713E6D46E16EC744C664 /* RLMProperty_Private.h */; }; - CD19EBB20252CC326563A92DF6098DC5 /* RLMSyncConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = DDCDF9F009A106410A660DDBD032F3B1 /* RLMSyncConfiguration.h */; }; - CD72CF57029AB4D1987E746D1C969B03 /* DTTableViewManager+Drop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90BF1A1247D2F23ADE5ADCA24D1D28EC /* DTTableViewManager+Drop.swift */; }; - CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DCFD9448E93E8D52A0BFC8E487D79A4 /* ConstraintRelation.swift */; }; - CF585AA54281BB45C03037C4A4C56AED /* RLMJSONModels.m in Sources */ = {isa = PBXBuildFile; fileRef = 21EDFDE383A3E251A56134BB51546D8A /* RLMJSONModels.m */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - D02A8F3A322426429314853341237059 /* RLMConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = 3F57B49A0FA692575F0606763D7A9F07 /* RLMConstants.h */; }; - D04919918C4E858CB048BCB2E2CA99C0 /* RLMSchema_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = F86572350A8EAD5F502303916A06FC89 /* RLMSchema_Private.h */; }; - D0FFA07135B6B357BF7FB4097C2ED5B0 /* NSError+RLMSync.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = C6EC7AB761B7755F64E1AA0339DD01C5 /* NSError+RLMSync.h */; }; - D13E571CFDFA478398231DD5D0F4EB52 /* RLMOptionalBase.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 385A3E979126AC8011F7211B7EC28505 /* RLMOptionalBase.h */; }; - D1E16D8B852B793DC73D69F98267636C /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CDDB1047780AAB8197609AE2BE4C856 /* Migration.swift */; }; - D28C130F5F3012F587CC16763CBD3DBE /* collection_change_builder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1CBC562EC852B09B8CD2ACBD39C1EEC /* collection_change_builder.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A87B28EF9993C400DEBDF15F7FD9AE /* ConstraintMultiplierTarget.swift */; }; - D844CF4AE7817A9A17D4BEC4BC39598E /* RLMSyncPermission.h in Headers */ = {isa = PBXBuildFile; fileRef = F00D131E27474BBE252362168003516F /* RLMSyncPermission.h */; }; - D87888C7A3F26BFAD3127B56D8AB474E /* object_store.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4F2C4966C1F8F7D76C798B9AAB71EC90 /* object_store.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - D895603455ACE427358968E0E072B475 /* UINib+Existance.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC51D92027327486360A76BCCABA2FEC /* UINib+Existance.swift */; }; - DA84AF88D7E5CD43D8BDE2CBC55296BD /* RLMRealmConfiguration+Sync.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0A8EDE30155A51E91D2B5E200DADD8A2 /* RLMRealmConfiguration+Sync.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - DB94BFB21436F7294C66D5CC40307397 /* RLMRealm.h in Headers */ = {isa = PBXBuildFile; fileRef = D219B16E47E5854B2B9B80326D823559 /* RLMRealm.h */; }; - DD76BA97F4C10B0FD53483BC8356C895 /* RLMSyncPermission.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1083A4885420B80A0DEF06162BE20E5C /* RLMSyncPermission.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - E04BEC6F14A0260CE4638DE000E9CBC8 /* RLMResults_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 68E0D242B4CF6EECA616C62E84474DB4 /* RLMResults_Private.h */; }; - E06FDB5F41A48F312BC053F63FB6FCFD /* DTTableViewDropDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A3212B24B75D44F977B3A62A4FB68DB /* DTTableViewDropDelegate.swift */; }; - E1C04EBBCE44BD3141F4EB0A81118085 /* Realm.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 445878DC71013C9D0CC42ADB420DD563 /* Realm.h */; }; - E22BB3552C77566B1B6955CE66218BCD /* Results.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33321F2CD36D73D1A44684BD2F159AF0 /* Results.swift */; }; - E372C5DB9505173CE808FAE38016D9D5 /* RLMProperty_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 5730C0642E0B713E6D46E16EC744C664 /* RLMProperty_Private.h */; }; - E3A82EF1BFEB4A449FFE7FC26AEC1FB9 /* RLMSyncSessionRefreshHandle.mm in Sources */ = {isa = PBXBuildFile; fileRef = 55A9C857A404B21A6B2AD31F34D73AB2 /* RLMSyncSessionRefreshHandle.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - E57EBC2383EE0C6A61D1D0A46FE47383 /* RLMThreadSafeReference.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 1CECF04B4631D24458F6D379B1BF6FAF /* RLMThreadSafeReference.h */; }; - E673B58F6FFC7F910AE4162B1C5B3AB6 /* RLMOptionalBase.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 385A3E979126AC8011F7211B7EC28505 /* RLMOptionalBase.h */; }; - E6A59169AB160B828757961CC391334C /* List.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9E00CC2D0D1AED18E5F6376107D503C /* List.swift */; }; - E83D2896CD2930EB85C3343E33752B47 /* RLMResults.mm in Sources */ = {isa = PBXBuildFile; fileRef = B7877F32D45F2485328B85C726E06A1E /* RLMResults.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - E8A754B37F44784D8B78A872DE6B2C92 /* Realm.h in Headers */ = {isa = PBXBuildFile; fileRef = 445878DC71013C9D0CC42ADB420DD563 /* Realm.h */; }; - E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74260EB22D575024DC5228FBC8C2197 /* ConstraintPriorityTarget.swift */; }; - E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24B46237E6B206F33C48065315A194AA /* LayoutConstraintItem.swift */; }; - EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BE59092C1B6889846B48FA19267C0DC /* ConstraintViewDSL.swift */; }; - EB86DF3DFB2AF93D4DB8CDD6F7295F73 /* RLMObject_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = F7CA0BB82F5F89D00F5037115FC02A38 /* RLMObject_Private.h */; }; - ED3035ABEBCD639F75DDC5C472795706 /* realm_coordinator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FE5DF8BE50F18860AD2A5402CD6A0D2C /* realm_coordinator.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - EE19F864673AF83DB4C21CA8464455AC /* object.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 25F27AB33CE0E841B278A87213AE50A8 /* object.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - EE2A5AE21E43B6A17BFFFE1695AF66FE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - EE3322A4595447F7FC50F86C6E99BC1B /* TableViewFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E06DEA517360838F7E6F503976CD655 /* TableViewFactory.swift */; }; - EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03AE55402C8DD9016517B857675BFA2E /* ConstraintMakerPriortizable.swift */; }; - F03298753DA84C04036A6A3D24D96950 /* RLMClassInfo.mm in Sources */ = {isa = PBXBuildFile; fileRef = 463E09DA282396F49269B9BE5AB5FFEF /* RLMClassInfo.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - F070B603DA8F5E7BA55B688D183E0B03 /* RLMRealmConfiguration.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = 372E3888C543E4F7354D55B652942A31 /* RLMRealmConfiguration.h */; }; - F15001312B4A1AFC5C0C39DB4B63962A /* RLMResults_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 68E0D242B4CF6EECA616C62E84474DB4 /* RLMResults_Private.h */; }; - F15174B61A15FA03A0C23B3BE0493169 /* AccumulationStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AFC1E88C8C18507112F90DC8F907645 /* AccumulationStrategy.swift */; }; - F28BFCB7597D463ECD8CF3DF3B596211 /* Aliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C476BB5591A011F11627DBA609467E2 /* Aliases.swift */; }; - F3365FB46BF0E869D92A464B07BB9948 /* RLMRealmConfiguration_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 57CA8968BD61AF1FB07C178ABAEBDCAF /* RLMRealmConfiguration_Private.h */; }; - F370D8390B7AF207E60E2D1DE01F913D /* DTTableViewManager+DataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFA85E1304D239D6A6A95C79A4918214 /* DTTableViewManager+DataSource.swift */; }; - F389A49251DDCBB29CEAA1E8D567B385 /* TableViewUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F59BE00B7EE46EFC70821C1E5DE811B /* TableViewUpdater.swift */; }; - F489AF2C3A4BAA41260095DAB13D5C17 /* RLMObject.h in Headers */ = {isa = PBXBuildFile; fileRef = 7740C7998C1E0ED03EB9222CC2BE9B64 /* RLMObject.h */; }; - F76444CD589D114686BB510A6066CE67 /* results_notifier.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C64C7547345B55464EF85916B43708A4 /* results_notifier.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - F7C4C0980A7CD46EDCAAF366A722FFCD /* RLMRealm+Sync.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3359F271A535F71023502BD8B9F38CA8 /* RLMRealm+Sync.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - F8116420B37CA79D3BFACFFA8B4E4A15 /* RLMSyncConfiguration.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = DDCDF9F009A106410A660DDBD032F3B1 /* RLMSyncConfiguration.h */; }; - F92BD30DFB4218BCD136C73A3EE04927 /* RLMRealm_Dynamic.h in Copy . Public Headers */ = {isa = PBXBuildFile; fileRef = DB5FBF630A2A4A790E0AA44490038B22 /* RLMRealm_Dynamic.h */; }; - F9CEDE306E79AB2DFD9744ECD1DAE87A /* RLMSyncConfiguration_Private.h in Copy . Private Headers */ = {isa = PBXBuildFile; fileRef = 940E4029EA051813FE224A3B6F7B61E6 /* RLMSyncConfiguration_Private.h */; }; - FAC633B5F15EB82A7DEB6253A7D12218 /* MemoryStorage+UpdateWithoutAnimations.swift in Sources */ = {isa = PBXBuildFile; fileRef = E64054DFA1F5E48708A72C63D4C0370A /* MemoryStorage+UpdateWithoutAnimations.swift */; }; - FB16D14072713E368969885E4ECD099B /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A35EE58F7669385825A01A135CD0491 /* Optional.swift */; }; - FB1DC2E9C1E29C6641CF63A061C7717A /* RLMListBase.mm in Sources */ = {isa = PBXBuildFile; fileRef = B23CF3923361D3CD2BF7BCA026541078 /* RLMListBase.mm */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; - FDA216D4735B3DBE4CD394C51F446E24 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */; }; - FEC148147D381D36ABDEAB648CFDB90A /* RLMSchema_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = F86572350A8EAD5F502303916A06FC89 /* RLMSchema_Private.h */; }; - FF4B2BB0EF29444776166A439A9D4E30 /* async_open_task.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 28990CB3B69D5F426AC00FAD0388848D /* async_open_task.cpp */; settings = {COMPILER_FLAGS = "-DREALM_HAVE_CONFIG -DREALM_COCOA_VERSION='@\"4.3.1\"' -D__ASSERTMACROS__ -DREALM_ENABLE_SYNC"; }; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 1FB2B3D314BDFC56A97DEF307E89BED5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 68494F30B4A13F8E5E88BCCAEC25B0A4; - remoteInfo = Realm; - }; - 2241096BF52D154C2390A33A7C459082 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 68494F30B4A13F8E5E88BCCAEC25B0A4; - remoteInfo = Realm; - }; - 38798EE4C9A9293F3745F976F22ADABC /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = E1F697AE01D68453B8B3B86DA9E42200; - remoteInfo = DTModelStorage; - }; - 3F2A2734043D65622E33BDE4027D227F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; - remoteInfo = SnapKit; - }; - A7ECE5DAC5D472D878AC0BAA34E66644 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = E1F697AE01D68453B8B3B86DA9E42200; - remoteInfo = DTModelStorage; - }; - AE66927C5CF3921B56CA3228BCBDB87D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 3EF3490B4B0DD7F07469ADEE907B9E59; - remoteInfo = DTTableViewManager; - }; - FAF4CD30CA4F48CABEE58034D8583ADF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 782725687624F8665247B84AB581BEB1; - remoteInfo = RealmSwift; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 1F16170A859A60D821655356EE33494F /* Copy . Public Headers */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = "$(PUBLIC_HEADERS_FOLDER_PATH)/."; - dstSubfolderSpec = 16; - files = ( - D0FFA07135B6B357BF7FB4097C2ED5B0 /* NSError+RLMSync.h in Copy . Public Headers */, - E1C04EBBCE44BD3141F4EB0A81118085 /* Realm.h in Copy . Public Headers */, - 9C0DED0B53B311D880B84EAD42A5C367 /* RLMArray.h in Copy . Public Headers */, - 683DF482E4E5C25C03F3729230C63CE4 /* RLMCollection.h in Copy . Public Headers */, - 974071500397CA88E104EB9828047CF9 /* RLMConstants.h in Copy . Public Headers */, - A524B1A8F063D71F7854055E86AEA72F /* RLMListBase.h in Copy . Public Headers */, - 5120291734D77494B3D96DFCC2EE9857 /* RLMMigration.h in Copy . Public Headers */, - 286807D3C2B82C0C52156AC968CFA068 /* RLMObject.h in Copy . Public Headers */, - 27426BDEE639040D91F43848108A18D0 /* RLMObjectBase.h in Copy . Public Headers */, - 164553A0AACB1FB27D68230B7439AB7B /* RLMObjectBase_Dynamic.h in Copy . Public Headers */, - B6DAA4FE8AFA5CD4BF68AF52102E0355 /* RLMObjectSchema.h in Copy . Public Headers */, - D13E571CFDFA478398231DD5D0F4EB52 /* RLMOptionalBase.h in Copy . Public Headers */, - 4FFF5D9D67F39D2CF4D4C016EECACB00 /* RLMPlatform.h in Copy . Public Headers */, - 793929EC869818B425DBE85F6447FA84 /* RLMProperty.h in Copy . Public Headers */, - 9C5DFFE29827A2D989C2DE6910ACA270 /* RLMRealm+Sync.h in Copy . Public Headers */, - 67AB6A2540052673DDB030ED4BB1409C /* RLMRealm.h in Copy . Public Headers */, - F92BD30DFB4218BCD136C73A3EE04927 /* RLMRealm_Dynamic.h in Copy . Public Headers */, - 92142DB3CEF7BA2BB8942694C45D3065 /* RLMRealmConfiguration+Sync.h in Copy . Public Headers */, - F070B603DA8F5E7BA55B688D183E0B03 /* RLMRealmConfiguration.h in Copy . Public Headers */, - 7FE1D9C8A8C25D367EEA42987989907F /* RLMResults.h in Copy . Public Headers */, - 1E68DAAF9FA67C987AED67B4DA41F855 /* RLMSchema.h in Copy . Public Headers */, - F8116420B37CA79D3BFACFFA8B4E4A15 /* RLMSyncConfiguration.h in Copy . Public Headers */, - 615BB4C1722E9019DB212D73FACE7780 /* RLMSyncCredentials.h in Copy . Public Headers */, - 56D79D21489B99536E56D11613733DD3 /* RLMSyncManager.h in Copy . Public Headers */, - 7912D79016C638A8B5C9221D6B637B1D /* RLMSyncPermission.h in Copy . Public Headers */, - AE96328EC72F4BC41BD1A496D45C9325 /* RLMSyncSession.h in Copy . Public Headers */, - 0111886BCBA7E203D31D37D93130988C /* RLMSyncSubscription.h in Copy . Public Headers */, - 066893C78B248DE542B8229D75F2040A /* RLMSyncUser.h in Copy . Public Headers */, - 8069CAE326CAF7B3FBAB1DAADDB0A15F /* RLMSyncUtil.h in Copy . Public Headers */, - E57EBC2383EE0C6A61D1D0A46FE47383 /* RLMThreadSafeReference.h in Copy . Public Headers */, - ); - name = "Copy . Public Headers"; - runOnlyForDeploymentPostprocessing = 0; - }; - 31E1852A7D8B204006F453FB1209492D /* Copy . Private Headers */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = "$(PRIVATE_HEADERS_FOLDER_PATH)/."; - dstSubfolderSpec = 16; - files = ( - 6DDD3EAC7634C6B8EBD88EB32F758913 /* RLMAccessor.h in Copy . Private Headers */, - 6FC528DFE6BAEA42D1373B2658656903 /* RLMArray_Private.h in Copy . Private Headers */, - 0ABD1A69D54921D4230DA47F703B47C8 /* RLMCollection_Private.h in Copy . Private Headers */, - C900AF92B70CCC35CF46BE3DEF231564 /* RLMListBase.h in Copy . Private Headers */, - 1856BEBADAA6691FD5C43D4D737029EA /* RLMObject_Private.h in Copy . Private Headers */, - 50A8B48A98FC0D65D138AB7D030497AA /* RLMObjectBase_Private.h in Copy . Private Headers */, - 68C57DF30A9CA33AACD78464E1AFF476 /* RLMObjectSchema_Private.h in Copy . Private Headers */, - A6645ABF85B1F4050B50D4DD62851C62 /* RLMObjectStore.h in Copy . Private Headers */, - E673B58F6FFC7F910AE4162B1C5B3AB6 /* RLMOptionalBase.h in Copy . Private Headers */, - E372C5DB9505173CE808FAE38016D9D5 /* RLMProperty_Private.h in Copy . Private Headers */, - CA784FB6D280003577399FC6357DF9E5 /* RLMRealm_Private.h in Copy . Private Headers */, - BE5BEFEEC9617E6F2ECA81E0B0ED9928 /* RLMRealmConfiguration_Private.h in Copy . Private Headers */, - E04BEC6F14A0260CE4638DE000E9CBC8 /* RLMResults_Private.h in Copy . Private Headers */, - D04919918C4E858CB048BCB2E2CA99C0 /* RLMSchema_Private.h in Copy . Private Headers */, - F9CEDE306E79AB2DFD9744ECD1DAE87A /* RLMSyncConfiguration_Private.h in Copy . Private Headers */, - 63A047238792804F506E0FBCE39F78FF /* RLMSyncUtil_Private.h in Copy . Private Headers */, - ); - name = "Copy . Private Headers"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 018C9874C67DCA911E8AD2EBE1174F7B /* DTModelStorage-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "DTModelStorage-Info.plist"; sourceTree = ""; }; - 03AE55402C8DD9016517B857675BFA2E /* ConstraintMakerPriortizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPriortizable.swift; path = Source/ConstraintMakerPriortizable.swift; sourceTree = ""; }; - 03D883FE0F80438243F85F3090469E58 /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Source/Debugging.swift; sourceTree = ""; }; - 04A8F2229E09694DEB1FF0F56FAB5DF7 /* RLMMigration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMMigration.h; path = include/RLMMigration.h; sourceTree = ""; }; - 0589B80789798770DC6C2CA206518B07 /* SnapKit.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.xcconfig; sourceTree = ""; }; - 072B68414DD27FF40271269943D5481E /* LinkingObjects.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LinkingObjects.swift; path = RealmSwift/LinkingObjects.swift; sourceTree = ""; }; - 083618C0629088D7CF458809465AF73A /* DTTableViewManager-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "DTTableViewManager-umbrella.h"; sourceTree = ""; }; - 0A3212B24B75D44F977B3A62A4FB68DB /* DTTableViewDropDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDropDelegate.swift; path = Sources/DTTableViewManager/DTTableViewDropDelegate.swift; sourceTree = ""; }; - 0A8EDE30155A51E91D2B5E200DADD8A2 /* RLMRealmConfiguration+Sync.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = "RLMRealmConfiguration+Sync.mm"; path = "Realm/RLMRealmConfiguration+Sync.mm"; sourceTree = ""; }; - 0B216D4857F045F87E7D90352446172F /* RLMResults.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMResults.h; path = include/RLMResults.h; sourceTree = ""; }; - 0B9A4143194FD94ED0FC12F263C7222B /* RLMRealm+Sync.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "RLMRealm+Sync.h"; path = "include/RLMRealm+Sync.h"; sourceTree = ""; }; - 1083A4885420B80A0DEF06162BE20E5C /* RLMSyncPermission.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncPermission.mm; path = Realm/RLMSyncPermission.mm; sourceTree = ""; }; - 110A8836C3844ECCE172E4B315C14D5C /* AnomalyHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnomalyHandler.swift; path = Sources/DTModelStorage/AnomalyHandler.swift; sourceTree = ""; }; - 12B715A8E70389228ED31B65F19C360F /* list.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = list.cpp; path = Realm/ObjectStore/src/list.cpp; sourceTree = ""; }; - 147BC758236001BE6BC568B869EB5B6D /* work_queue.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = work_queue.cpp; path = Realm/ObjectStore/src/sync/impl/work_queue.cpp; sourceTree = ""; }; - 1516938D464E51B0644674C984843905 /* RLMQueryUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMQueryUtil.mm; path = Realm/RLMQueryUtil.mm; sourceTree = ""; }; - 1680DE752CFF211598AA28BA23DC0423 /* DTTableViewManager+Drag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+Drag.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+Drag.swift"; sourceTree = ""; }; - 16EB414EA3030B111E1FD38437F0FCAD /* object_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = object_notifier.cpp; path = Realm/ObjectStore/src/impl/object_notifier.cpp; sourceTree = ""; }; - 180EA465872694E44858D9057786BFA5 /* RLMPredicateUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMPredicateUtil.mm; path = Realm/RLMPredicateUtil.mm; sourceTree = ""; }; - 19674D3C9E9AA3C53DA5162DE029918E /* RLMSyncSession.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncSession.mm; path = Realm/RLMSyncSession.mm; sourceTree = ""; }; - 1C22ACA9772C6A64DAC86BCE215D0644 /* partial_sync.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = partial_sync.cpp; path = Realm/ObjectStore/src/sync/partial_sync.cpp; sourceTree = ""; }; - 1CECF04B4631D24458F6D379B1BF6FAF /* RLMThreadSafeReference.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMThreadSafeReference.h; path = include/RLMThreadSafeReference.h; sourceTree = ""; }; - 1F0E2A67636815327AF51E8324AC7DFF /* RLMCollection.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMCollection.h; path = include/RLMCollection.h; sourceTree = ""; }; - 1F2A650980474B09474FBD14355A3EFB /* RLMSyncUser.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncUser.h; path = include/RLMSyncUser.h; sourceTree = ""; }; - 205924444AE13CD4400A7C8037655DEF /* list_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = list_notifier.cpp; path = Realm/ObjectStore/src/impl/list_notifier.cpp; sourceTree = ""; }; - 21EDFDE383A3E251A56134BB51546D8A /* RLMJSONModels.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = RLMJSONModels.m; path = Realm/RLMJSONModels.m; sourceTree = ""; }; - 240AD0928397EDD73DBA6FA830C2F200 /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Source/ConstraintInsetTarget.swift; sourceTree = ""; }; - 24520BA6825D00730ED9C7DFF85EB308 /* schema.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = schema.cpp; path = Realm/ObjectStore/src/schema.cpp; sourceTree = ""; }; - 24B46237E6B206F33C48065315A194AA /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Source/LayoutConstraintItem.swift; sourceTree = ""; }; - 25705CA1710F89251D9929DCF3D1F08A /* Realm.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Realm.xcconfig; sourceTree = ""; }; - 25F27AB33CE0E841B278A87213AE50A8 /* object.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = object.cpp; path = Realm/ObjectStore/src/object.cpp; sourceTree = ""; }; - 273DA2E6224B9EA0181B06B50F8C5B39 /* RuntimeHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RuntimeHelper.swift; path = Sources/DTModelStorage/RuntimeHelper.swift; sourceTree = ""; }; - 28990CB3B69D5F426AC00FAD0388848D /* async_open_task.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = async_open_task.cpp; path = Realm/ObjectStore/src/sync/async_open_task.cpp; sourceTree = ""; }; - 2977EA8AA20923C44E80AAFC1A6F3222 /* DTTableViewDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDataSource.swift; path = Sources/DTTableViewManager/DTTableViewDataSource.swift; sourceTree = ""; }; - 29A6623BC5A747B5D3FE4D29896046F5 /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; - 2A2C7E26B2784AEE83ED67176365A58B /* DTTableViewDropPlaceholderContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDropPlaceholderContext.swift; path = Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift; sourceTree = ""; }; - 2A7D4E01FFA210388B2222C35DD50FD6 /* ObjectiveCSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObjectiveCSupport.swift; path = RealmSwift/ObjectiveCSupport.swift; sourceTree = ""; }; - 2E7F0F57CD0F4C1477BF8AD8178F6E0C /* DTTableViewManager-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "DTTableViewManager-prefix.pch"; sourceTree = ""; }; - 2FC04F46E165B5BC076542E93F20D045 /* RLMObjectStore.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObjectStore.mm; path = Realm/RLMObjectStore.mm; sourceTree = ""; }; - 3040BA8B8BF3441A8A25C292951EE282 /* RLMObjectSchema.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectSchema.h; path = include/RLMObjectSchema.h; sourceTree = ""; }; - 32DE6835AFD8DCE99328A08562FC7304 /* RLMThreadSafeReference.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMThreadSafeReference.mm; path = Realm/RLMThreadSafeReference.mm; sourceTree = ""; }; - 332E388AC73063ABF70E858AC63EF417 /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; - 33321F2CD36D73D1A44684BD2F159AF0 /* Results.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Results.swift; path = RealmSwift/Results.swift; sourceTree = ""; }; - 3359F271A535F71023502BD8B9F38CA8 /* RLMRealm+Sync.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = "RLMRealm+Sync.mm"; path = "Realm/RLMRealm+Sync.mm"; sourceTree = ""; }; - 33A2DD2812754AECA0F1F9ABAA9139E9 /* RLMCollection.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMCollection.mm; path = Realm/RLMCollection.mm; sourceTree = ""; }; - 351ACFD6F28BB294CAB5D95EF421209A /* Pods-Lesson12-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Lesson12-acknowledgements.markdown"; sourceTree = ""; }; - 37267A6188287FEB6B93C67DBE9A517A /* SingleSectionDiffing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleSectionDiffing.swift; path = Sources/DTModelStorage/SingleSectionDiffing.swift; sourceTree = ""; }; - 372E3888C543E4F7354D55B652942A31 /* RLMRealmConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealmConfiguration.h; path = include/RLMRealmConfiguration.h; sourceTree = ""; }; - 385A3E979126AC8011F7211B7EC28505 /* RLMOptionalBase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMOptionalBase.h; path = include/RLMOptionalBase.h; sourceTree = ""; }; - 394E9BF21C25ED2E5345E53020A5CC3D /* ObjectiveCSupport+Sync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObjectiveCSupport+Sync.swift"; path = "RealmSwift/ObjectiveCSupport+Sync.swift"; sourceTree = ""; }; - 3A905DD29462C9D166D93B5223857DEA /* thread_safe_reference.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = thread_safe_reference.cpp; path = Realm/ObjectStore/src/thread_safe_reference.cpp; sourceTree = ""; }; - 3B31FB10E2273F59614E18103B23BC93 /* RLMSyncCredentials.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = RLMSyncCredentials.m; path = Realm/RLMSyncCredentials.m; sourceTree = ""; }; - 3B8C0C088A43AF55F2F1804C536FF82B /* RLMProperty.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMProperty.h; path = include/RLMProperty.h; sourceTree = ""; }; - 3BBF9E1FE4BE88841D92BD4F7D49DD12 /* SortDescriptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SortDescriptor.swift; path = RealmSwift/SortDescriptor.swift; sourceTree = ""; }; - 3CB2906AE3A9E50A11DC9ED209793702 /* object_schema.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = object_schema.cpp; path = Realm/ObjectStore/src/object_schema.cpp; sourceTree = ""; }; - 3D2FDC0D84F98632EE7330317E6C2302 /* sync_permission.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_permission.cpp; path = Realm/ObjectStore/src/sync/sync_permission.cpp; sourceTree = ""; }; - 3D54E81BDD6D4184B6D7112334877DC3 /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Source/ConstraintMakerEditable.swift; sourceTree = ""; }; - 3D9BC1AB715B9C60E650377023BA6453 /* RLMArray_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMArray_Private.h; path = include/RLMArray_Private.h; sourceTree = ""; }; - 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 3E6F1519F5C5F6C2B02A5BA985B3B40E /* Pods-Lesson12-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Lesson12-umbrella.h"; sourceTree = ""; }; - 3F57B49A0FA692575F0606763D7A9F07 /* RLMConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMConstants.h; path = include/RLMConstants.h; sourceTree = ""; }; - 4099E157F7F8FD6588668F172659E2A7 /* ModelTransfer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ModelTransfer.swift; path = Sources/DTModelStorage/ModelTransfer.swift; sourceTree = ""; }; - 40E517C7A659C9196BE238502EC31611 /* RLMObjectSchema.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObjectSchema.mm; path = Realm/RLMObjectSchema.mm; sourceTree = ""; }; - 437919EE08EC6BFCCBAC3BD346309742 /* RealmSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RealmSwift.framework; path = RealmSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 439DD2ED964B85F221832C11D774EB8E /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; - 445878DC71013C9D0CC42ADB420DD563 /* Realm.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Realm.h; path = include/Realm.h; sourceTree = ""; }; - 4489D501A65F0FFFCB1B928E1B1CF8E8 /* SingleSectionStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleSectionStorage.swift; path = Sources/DTModelStorage/SingleSectionStorage.swift; sourceTree = ""; }; - 463E09DA282396F49269B9BE5AB5FFEF /* RLMClassInfo.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMClassInfo.mm; path = Realm/RLMClassInfo.mm; sourceTree = ""; }; - 467846062075DF9A615F0712528D51CD /* RealmSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RealmSwift-umbrella.h"; sourceTree = ""; }; - 4714D922CCEE7B36C134A0E4C7671DDB /* collection_notifications.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = collection_notifications.cpp; path = Realm/ObjectStore/src/collection_notifications.cpp; sourceTree = ""; }; - 4825BA092AE4221CD1C2FD69CAA8C577 /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Source/ConstraintPriority.swift; sourceTree = ""; }; - 48D9995270C83F315AFE4069D26661B2 /* CoreDataStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CoreDataStorage.swift; path = Sources/DTModelStorage/CoreDataStorage.swift; sourceTree = ""; }; - 4935C70EBBD3BDC88BA42FB0D34B93DE /* Schema.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Schema.swift; path = RealmSwift/Schema.swift; sourceTree = ""; }; - 49A70E08C233891700C4E8171EE3841D /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; - 4A6D3AA87CE10E84A55129189076FA01 /* RLMObjectStore.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectStore.h; path = include/RLMObjectStore.h; sourceTree = ""; }; - 4AB088E51E743F45688903D4D8D2D66B /* RLMConstants.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = RLMConstants.m; path = Realm/RLMConstants.m; sourceTree = ""; }; - 4AD2D182CD2BFCF831AAB8ACF8D45BF9 /* Realm-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Realm-Info.plist"; sourceTree = ""; }; - 4B91595DE4A0B5B7F17B4D74DB1ADB8F /* results.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = results.cpp; path = Realm/ObjectStore/src/results.cpp; sourceTree = ""; }; - 4D1513A17CD9C965CEC10CB203F69CF2 /* DTModelStorage.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = DTModelStorage.xcconfig; sourceTree = ""; }; - 4D2B381E2885D444F3F4569560E331A4 /* RLMSyncConfiguration.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncConfiguration.mm; path = Realm/RLMSyncConfiguration.mm; sourceTree = ""; }; - 4D2CA8C9C3EC78FD1CC396472819EDAD /* DTModelStorage.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = DTModelStorage.modulemap; sourceTree = ""; }; - 4E45EF266A78A58B8C91A2F04FB0D029 /* RLMNetworkClient.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMNetworkClient.mm; path = Realm/RLMNetworkClient.mm; sourceTree = ""; }; - 4E63ED5E1312A8515A4FE88F4D7CE934 /* Pods-Lesson12-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson12-acknowledgements.plist"; sourceTree = ""; }; - 4F2C4966C1F8F7D76C798B9AAB71EC90 /* object_store.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = object_store.cpp; path = Realm/ObjectStore/src/object_store.cpp; sourceTree = ""; }; - 4F74FB6E257915D5C1974672A2520FA5 /* RLMRealm.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMRealm.mm; path = Realm/RLMRealm.mm; sourceTree = ""; }; - 4FC9128FB437A8E6B3C211DC0C88004E /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Source/Typealiases.swift; sourceTree = ""; }; - 5194A0EB6E38A52770B77C79FCCAF779 /* NSError+RLMSync.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSError+RLMSync.m"; path = "Realm/NSError+RLMSync.m"; sourceTree = ""; }; - 52D11ADC324C5332A4F6299A79430067 /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Source/ConstraintDSL.swift; sourceTree = ""; }; - 52DBA640AED2F6F34036625774076D4D /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Source/LayoutConstraint.swift; sourceTree = ""; }; - 539DD206E6B4E2DE0FC82DF732FC8E76 /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Source/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; - 55A9C857A404B21A6B2AD31F34D73AB2 /* RLMSyncSessionRefreshHandle.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncSessionRefreshHandle.mm; path = Realm/RLMSyncSessionRefreshHandle.mm; sourceTree = ""; }; - 57222B8653830F1ED81211926DF5A060 /* RealmSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RealmSwift-prefix.pch"; sourceTree = ""; }; - 5730C0642E0B713E6D46E16EC744C664 /* RLMProperty_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMProperty_Private.h; path = include/RLMProperty_Private.h; sourceTree = ""; }; - 57CA8968BD61AF1FB07C178ABAEBDCAF /* RLMRealmConfiguration_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealmConfiguration_Private.h; path = include/RLMRealmConfiguration_Private.h; sourceTree = ""; }; - 59DD1951661B55FBB6E5561C5E6A6641 /* Property.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Property.swift; path = RealmSwift/Property.swift; sourceTree = ""; }; - 5A2F892D6FCA6C28ED679E370B18CDE9 /* DTTableViewDragDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDragDelegate.swift; path = Sources/DTTableViewManager/DTTableViewDragDelegate.swift; sourceTree = ""; }; - 5BA121DEBDEFE4FE4C6CB10F50CB0C20 /* RLMSyncManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncManager.h; path = include/RLMSyncManager.h; sourceTree = ""; }; - 60CB733150050B0A03D2C5FB83782840 /* Pods-Lesson12.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson12.release.xcconfig"; sourceTree = ""; }; - 613F36E25BEC199D7DE60CC8F891BB76 /* UIView+XibLoading.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+XibLoading.swift"; path = "Sources/DTTableViewManager/UIView+XibLoading.swift"; sourceTree = ""; }; - 61C0831E1A5A5F9BAE73DB2BCBAC1CE6 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RealmSwift/Error.swift; sourceTree = ""; }; - 62B9A4A867C31B9B15A7A69A95EC4876 /* RealmSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RealmSwift.xcconfig; sourceTree = ""; }; - 6300FF17FE30A52A38EC7D7E1F736A9E /* Realm-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Realm-prefix.pch"; sourceTree = ""; }; - 63315A69198070A681994D590BBD42ED /* MemoryStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MemoryStorage.swift; path = Sources/DTModelStorage/MemoryStorage.swift; sourceTree = ""; }; - 63D6B294B05701775E010AC526CB9D77 /* RealmSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RealmSwift.modulemap; sourceTree = ""; }; - 642B46585C61DCCE79A43F69CC13CD53 /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Source/ConstraintLayoutSupport.swift; sourceTree = ""; }; - 644F8E01BE16AC1DC2EC57F200E6A6C1 /* sync_config.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_config.cpp; path = Realm/ObjectStore/src/sync/sync_config.cpp; sourceTree = ""; }; - 664C66D52716CF12032C6F83873CF72A /* RLMSyncManager.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncManager.mm; path = Realm/RLMSyncManager.mm; sourceTree = ""; }; - 6726AFA0176A345BC0CA041F40C91D08 /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Source/ConstraintConfig.swift; sourceTree = ""; }; - 67F84B83E4860C3D13E46A83C6033C47 /* RealmCollection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RealmCollection.swift; path = RealmSwift/RealmCollection.swift; sourceTree = ""; }; - 6881ACD7B5E2E79D91E759FF3A0328BF /* index_set.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = index_set.cpp; path = Realm/ObjectStore/src/index_set.cpp; sourceTree = ""; }; - 68E0D242B4CF6EECA616C62E84474DB4 /* RLMResults_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMResults_Private.h; path = include/RLMResults_Private.h; sourceTree = ""; }; - 6913ADD3EBC59D0E9D381BEA66098F50 /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Source/Constraint.swift; sourceTree = ""; }; - 6BE59092C1B6889846B48FA19267C0DC /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Source/ConstraintViewDSL.swift; sourceTree = ""; }; - 6C71F5065524F1657625088FAC3E6808 /* RLMObjectBase_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectBase_Private.h; path = include/RLMObjectBase_Private.h; sourceTree = ""; }; - 71BF55D66A00B7440DF166FE1DFCCB2B /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; - 7230E3B4D79A605F74D8C9E619F81F85 /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Source/ConstraintConstantTarget.swift; sourceTree = ""; }; - 73226A3C25999F7DBB805EBC80CC4255 /* DTModelStorage.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = DTModelStorage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 74C1F8612B5FAC29958A3688C854B0D3 /* RLMUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMUtil.mm; path = Realm/RLMUtil.mm; sourceTree = ""; }; - 7626FBCB0DB4F4FB4A0966F840256122 /* RLMRealm_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealm_Private.h; path = include/RLMRealm_Private.h; sourceTree = ""; }; - 76A0680EEF6D60432C0739BA193D8AFB /* transact_log_handler.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = transact_log_handler.cpp; path = Realm/ObjectStore/src/impl/transact_log_handler.cpp; sourceTree = ""; }; - 7740C7998C1E0ED03EB9222CC2BE9B64 /* RLMObject.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObject.h; path = include/RLMObject.h; sourceTree = ""; }; - 778399867C21AA8021204104ACC147DA /* shared_realm.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = shared_realm.cpp; path = Realm/ObjectStore/src/shared_realm.cpp; sourceTree = ""; }; - 789E057A5CF6AE2F75A3E5A47AA690EC /* RealmSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RealmSwift-Info.plist"; sourceTree = ""; }; - 7962661A838C6885CDF1F8012F9D2108 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; - 7A505FD515BAA6636F6D6363877150F1 /* DTModelStorage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "DTModelStorage-dummy.m"; sourceTree = ""; }; - 7AA773B5E79F4F73D15464BDC5721177 /* Realm.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Realm.modulemap; sourceTree = ""; }; - 7AB046C46DB77ED8BA8F9BDA9F271138 /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Source/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; - 7C0DA5F6F3AAEF85A81BCA4825B4086D /* RLMProperty.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMProperty.mm; path = Realm/RLMProperty.mm; sourceTree = ""; }; - 7C476BB5591A011F11627DBA609467E2 /* Aliases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Aliases.swift; path = RealmSwift/Aliases.swift; sourceTree = ""; }; - 7C710889361EE8207B98ABA2C4D2A677 /* sync_file.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_file.cpp; path = Realm/ObjectStore/src/sync/impl/sync_file.cpp; sourceTree = ""; }; - 7E0032FF54C224D41AFB44C19F94EFF7 /* Pods-Lesson12.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Lesson12.modulemap"; sourceTree = ""; }; - 7E06DEA517360838F7E6F503976CD655 /* TableViewFactory.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TableViewFactory.swift; path = Sources/DTTableViewManager/TableViewFactory.swift; sourceTree = ""; }; - 7EEB0CADB7C3F9B63A159DF537792DC4 /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Source/ConstraintDescription.swift; sourceTree = ""; }; - 7F257C890C5BA74E7CF941B82C741C56 /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Source/ConstraintAttributes.swift; sourceTree = ""; }; - 83226A8F1E0F2767A08452B45B57BC29 /* RLMSyncUtil_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncUtil_Private.h; path = include/RLMSyncUtil_Private.h; sourceTree = ""; }; - 83BBA83C8AD1E1A7BAC41F307D14F669 /* DTTableViewManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewManager.swift; path = Sources/DTTableViewManager/DTTableViewManager.swift; sourceTree = ""; }; - 85B46BBDF4E92F9E14C5B3E25BE55588 /* RealmSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RealmSwift-dummy.m"; sourceTree = ""; }; - 862AFD197149B8569B424BDE9510D221 /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Source/ConstraintOffsetTarget.swift; sourceTree = ""; }; - 87EBD3107688814C52D9C3DFFE4C05A3 /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Source/ConstraintLayoutGuide.swift; sourceTree = ""; }; - 884F556E058A9DDA81ACB4B57760E082 /* StorageProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StorageProtocols.swift; path = Sources/DTModelStorage/StorageProtocols.swift; sourceTree = ""; }; - 8907267A50CC886474A3D542965A19A9 /* sync_user.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_user.cpp; path = Realm/ObjectStore/src/sync/sync_user.cpp; sourceTree = ""; }; - 8A72F70546CF49ED43127DC915FAB41D /* external_commit_helper.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = external_commit_helper.cpp; path = Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp; sourceTree = ""; }; - 8AFC1E88C8C18507112F90DC8F907645 /* AccumulationStrategy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AccumulationStrategy.swift; path = Sources/DTModelStorage/AccumulationStrategy.swift; sourceTree = ""; }; - 8B005D46C74CFA9A8251EBA2B7DF0CFA /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Source/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; - 8B7AE71079AFC8D636C516AD4F0761CA /* RLMSyncSubscription.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncSubscription.h; path = include/RLMSyncSubscription.h; sourceTree = ""; }; - 8CA3FFE66F25DC21E5B98E8F15E536A3 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Source/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; - 8D7F44C29F5C323A93E174DED4DDB254 /* DTModelStorage.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = DTModelStorage.framework; path = DTModelStorage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8EBFE37C26992B4DD024F56CE87F9AD4 /* Realm.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Realm.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8F59BE00B7EE46EFC70821C1E5DE811B /* TableViewUpdater.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TableViewUpdater.swift; path = Sources/DTTableViewManager/TableViewUpdater.swift; sourceTree = ""; }; - 90BF1A1247D2F23ADE5ADCA24D1D28EC /* DTTableViewManager+Drop.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+Drop.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+Drop.swift"; sourceTree = ""; }; - 911B7D9BFD745E8AA0A37559DB898EBA /* Pods-Lesson12-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Lesson12-dummy.m"; sourceTree = ""; }; - 912A7824E526E706ADF17636A87C8AAC /* StorageUpdate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StorageUpdate.swift; path = Sources/DTModelStorage/StorageUpdate.swift; sourceTree = ""; }; - 91E61A2A30FDB2108A53B95E11B2CCB7 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Source/ConstraintMaker.swift; sourceTree = ""; }; - 921BE4A82C4A7A5C72A0C6F8B8FEF200 /* Realm.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Realm.framework; path = Realm.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 940E4029EA051813FE224A3B6F7B61E6 /* RLMSyncConfiguration_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncConfiguration_Private.h; path = include/RLMSyncConfiguration_Private.h; sourceTree = ""; }; - 96820C3C661F733FF50D3B2EBC178AD0 /* RLMSchema.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSchema.h; path = include/RLMSchema.h; sourceTree = ""; }; - 979486118B3E90C08386079D57962701 /* SnapKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit.framework; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 981F2F2BE46A6A67F1DB95FB287D72AD /* primitive_list_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = primitive_list_notifier.cpp; path = Realm/ObjectStore/src/impl/primitive_list_notifier.cpp; sourceTree = ""; }; - 9A35EE58F7669385825A01A135CD0491 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RealmSwift/Optional.swift; sourceTree = ""; }; - 9BD817C7300CEFDC2B38E4BA2CE97F12 /* SectionModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionModel.swift; path = Sources/DTModelStorage/SectionModel.swift; sourceTree = ""; }; - 9CDDB1047780AAB8197609AE2BE4C856 /* Migration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Migration.swift; path = RealmSwift/Migration.swift; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 9DCFD9448E93E8D52A0BFC8E487D79A4 /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Source/ConstraintRelation.swift; sourceTree = ""; }; - 9F4AC1ADC59F9E8F1AEAB8201B375468 /* Pods-Lesson12-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Lesson12-frameworks.sh"; sourceTree = ""; }; - 9F981DAC47B85F0D9FE919BB033171CD /* DTTableViewManager.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = DTTableViewManager.modulemap; sourceTree = ""; }; - 9FC166983E5A48BFDE3ABE9112FBDD0E /* binding_callback_thread_observer.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = binding_callback_thread_observer.cpp; path = Realm/ObjectStore/src/binding_callback_thread_observer.cpp; sourceTree = ""; }; - 9FF0033B28EAB2BBC47A324C37EB13EC /* Realm-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Realm-dummy.m"; sourceTree = ""; }; - A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = DTTableViewManager.framework; path = DTTableViewManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A1CBC562EC852B09B8CD2ACBD39C1EEC /* collection_change_builder.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = collection_change_builder.cpp; path = Realm/ObjectStore/src/impl/collection_change_builder.cpp; sourceTree = ""; }; - A35BEADF5432B761E8DF789A30215D2C /* DTTableViewManager.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = DTTableViewManager.xcconfig; sourceTree = ""; }; - A3F91BBE7AF9F154EF08C316238670E2 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Source/ConstraintItem.swift; sourceTree = ""; }; - A45825178B6ADCC06CD7AA31113287A9 /* DTModelStorage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "DTModelStorage-umbrella.h"; sourceTree = ""; }; - A6BB363083C035E6988F54E9A44982FF /* DTTableViewManagerAnomalyHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewManagerAnomalyHandler.swift; path = Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift; sourceTree = ""; }; - A6C0C2966A4A5D3599B61ED5EAE870BF /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Source/ConstraintInsets.swift; sourceTree = ""; }; - A6C41A5F855BA7C4A3D21CC85CABA10C /* DTTableViewDelegateWrapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDelegateWrapper.swift; path = Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift; sourceTree = ""; }; - A6F478FC4B97F58B619554CC291ECCF1 /* EventReactions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventReactions.swift; path = Sources/DTModelStorage/EventReactions.swift; sourceTree = ""; }; - A8285F9C4A29355AF7659A1EBD2E179F /* RLMObjectBase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectBase.h; path = include/RLMObjectBase.h; sourceTree = ""; }; - AA4BB6A5AD4DA3521D25B7A7B31598D2 /* system_configuration.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = system_configuration.cpp; path = Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp; sourceTree = ""; }; - AA94BDFD0BC51FFBD31ED2D027E28B63 /* RLMSyncUtil.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncUtil.h; path = include/RLMSyncUtil.h; sourceTree = ""; }; - ADA4CA7376B38B6E954AB07A24FA8FB5 /* RLMSyncSubscription.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncSubscription.mm; path = Realm/RLMSyncSubscription.mm; sourceTree = ""; }; - AE7FE5AE8A0B542B038BFF6E8E0B46B7 /* ViewModelMapping.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ViewModelMapping.swift; path = Sources/DTModelStorage/ViewModelMapping.swift; sourceTree = ""; }; - AFD0CAAC8C1C696AC1294007FB1D6EA4 /* Section.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Section.swift; path = Sources/DTModelStorage/Section.swift; sourceTree = ""; }; - B092C8AF4A98CF45C6D1B26A0112D99D /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Source/ConstraintMakerFinalizable.swift; sourceTree = ""; }; - B1C773E67BF4B069808A7E8ADE542E88 /* Pods_Lesson12.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Lesson12.framework; path = "Pods-Lesson12.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - B23CF3923361D3CD2BF7BCA026541078 /* RLMListBase.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMListBase.mm; path = Realm/RLMListBase.mm; sourceTree = ""; }; - B262BA381A559D0635AE9B56A311892D /* RLMSwiftSupport.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = RLMSwiftSupport.m; path = Realm/RLMSwiftSupport.m; sourceTree = ""; }; - B28830DD90409A0543F7F8F82849A7EC /* RLMArray.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMArray.mm; path = Realm/RLMArray.mm; sourceTree = ""; }; - B437E9E2DD5D50C699667686417A6BDE /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; - B5882A01A23F29222C693AC6453B2C22 /* RLMAccessor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMAccessor.h; path = include/RLMAccessor.h; sourceTree = ""; }; - B7877F32D45F2485328B85C726E06A1E /* RLMResults.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMResults.mm; path = Realm/RLMResults.mm; sourceTree = ""; }; - BAC764CE511370D9847A2392D1D55C73 /* Util.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Util.swift; path = RealmSwift/Util.swift; sourceTree = ""; }; - BAD19CEF1DE12B2691DB29FEC292B840 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CoreData.framework; sourceTree = DEVELOPER_DIR; }; - BAEC53929DBDB1101C311029FB1A5A5A /* TableViewConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TableViewConfiguration.swift; path = Sources/DTTableViewManager/TableViewConfiguration.swift; sourceTree = ""; }; - BC0F4D611C9EA3BAFA7BC6C34945BBE5 /* RLMArray.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMArray.h; path = include/RLMArray.h; sourceTree = ""; }; - BC99A40943538DC1761A8F623E480CC9 /* RLMRealmConfiguration+Sync.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "RLMRealmConfiguration+Sync.h"; path = "include/RLMRealmConfiguration+Sync.h"; sourceTree = ""; }; - BD5C19305B180CC0D2D4142A0CDA0DE2 /* keychain_helper.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = keychain_helper.cpp; path = Realm/ObjectStore/src/impl/apple/keychain_helper.cpp; sourceTree = ""; }; - BEA345D3718292AC478C1585AA32958B /* RLMPlatform.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMPlatform.h; path = include/RLMPlatform.h; sourceTree = ""; }; - BEE8A8E0F76002E7834FAFEB10374970 /* RLMObject.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObject.mm; path = Realm/RLMObject.mm; sourceTree = ""; }; - BF85951E33188510ED514531C7A57C32 /* RLMSyncUser.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncUser.mm; path = Realm/RLMSyncUser.mm; sourceTree = ""; }; - C04E7F51401C97CBFFE90525078D9868 /* Pods-Lesson12.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Lesson12.debug.xcconfig"; sourceTree = ""; }; - C1762070B33912BE7387C65B9816080D /* DTTableViewManager-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "DTTableViewManager-Info.plist"; sourceTree = ""; }; - C283EA9E079F3598F412CEFF2167CD91 /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Source/ConstraintMakerRelatable.swift; sourceTree = ""; }; - C40098B8DEB3229D47B663D80E0813D9 /* Realm.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Realm.swift; path = RealmSwift/Realm.swift; sourceTree = ""; }; - C64C7547345B55464EF85916B43708A4 /* results_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = results_notifier.cpp; path = Realm/ObjectStore/src/impl/results_notifier.cpp; sourceTree = ""; }; - C6EC7AB761B7755F64E1AA0339DD01C5 /* NSError+RLMSync.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSError+RLMSync.h"; path = "include/NSError+RLMSync.h"; sourceTree = ""; }; - C717E81CC42248D9FFF258716E2F18EB /* placeholder.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = placeholder.cpp; path = Realm/ObjectStore/src/placeholder.cpp; sourceTree = ""; }; - C78053BA00DD1B43D3361AFD59385AD2 /* DTTableViewManager-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "DTTableViewManager-dummy.m"; sourceTree = ""; }; - CB68296FEF989F38D67625187DFDC2A4 /* ObjectSchema.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObjectSchema.swift; path = RealmSwift/ObjectSchema.swift; sourceTree = ""; }; - CC0E36BD9D81DE0383BBAE911F2DF9C4 /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Source/ConstraintDirectionalInsets.swift; sourceTree = ""; }; - CD94DA44E270CDB057579FA88B39883E /* DTTableViewDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DTTableViewDelegate.swift; path = Sources/DTTableViewManager/DTTableViewDelegate.swift; sourceTree = ""; }; - CE58AA507A58423CA7B5FEDDE9E23058 /* RLMAccessor.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMAccessor.mm; path = Realm/RLMAccessor.mm; sourceTree = ""; }; - CF192D8F67FA60E5D01C25180A34ED7D /* RLMManagedArray.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMManagedArray.mm; path = Realm/RLMManagedArray.mm; sourceTree = ""; }; - CFA85E1304D239D6A6A95C79A4918214 /* DTTableViewManager+DataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+DataSource.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+DataSource.swift"; sourceTree = ""; }; - CFC738E414DCDEDDF7D8D2E6C1053446 /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Source/ConstraintView+Extensions.swift"; sourceTree = ""; }; - D1B48050A06FB75408DE8922A1F9FFA3 /* network_reachability_observer.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = network_reachability_observer.cpp; path = Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp; sourceTree = ""; }; - D219B16E47E5854B2B9B80326D823559 /* RLMRealm.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealm.h; path = include/RLMRealm.h; sourceTree = ""; }; - D657CEEA4664E23DDBCAF74EB352D3B5 /* ThreadSafeReference.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ThreadSafeReference.swift; path = RealmSwift/ThreadSafeReference.swift; sourceTree = ""; }; - D799CECCDA496FD6FC0E4A8E9CF9707C /* RLMMigration.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMMigration.mm; path = Realm/RLMMigration.mm; sourceTree = ""; }; - D7FB328B75EAF13BB9C043DC8E767448 /* librealmcore-ios.a */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = archive.ar; name = "librealmcore-ios.a"; path = "core/librealmcore-ios.a"; sourceTree = ""; }; - D9E00CC2D0D1AED18E5F6376107D503C /* List.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = List.swift; path = RealmSwift/List.swift; sourceTree = ""; }; - DA0DF3C2211484ED19DF5E089344E170 /* Object.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Object.swift; path = RealmSwift/Object.swift; sourceTree = ""; }; - DAACEBB9AA0416B30137379B9A48EE8B /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Source/ConstraintView.swift; sourceTree = ""; }; - DB5FBF630A2A4A790E0AA44490038B22 /* RLMRealm_Dynamic.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMRealm_Dynamic.h; path = include/RLMRealm_Dynamic.h; sourceTree = ""; }; - DC0D2F818024F7F7CC0A029A727816AA /* BackwardsCompatibility.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BackwardsCompatibility.swift; path = Sources/DTTableViewManager/BackwardsCompatibility.swift; sourceTree = ""; }; - DDAE99C2028C04AA0EE9094DC3758018 /* sync_metadata.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_metadata.cpp; path = Realm/ObjectStore/src/sync/impl/sync_metadata.cpp; sourceTree = ""; }; - DDCDF9F009A106410A660DDBD032F3B1 /* RLMSyncConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncConfiguration.h; path = include/RLMSyncConfiguration.h; sourceTree = ""; }; - DDD68071084759E025904A0CF5E4CACE /* sync_manager.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_manager.cpp; path = Realm/ObjectStore/src/sync/sync_manager.cpp; sourceTree = ""; }; - DE344BB25054A813F1438C84A4BB948B /* DTModelStorage-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "DTModelStorage-prefix.pch"; sourceTree = ""; }; - DED40C8AFCCC2C704B7DC2D93E75DE56 /* SectionProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionProtocols.swift; path = Sources/DTModelStorage/SectionProtocols.swift; sourceTree = ""; }; - DEFB9B52BC635068A822A8830FD5AEF7 /* ProxyDiffableDataSourceStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ProxyDiffableDataSourceStorage.swift; path = Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift; sourceTree = ""; }; - DF0EF208569C6F026D7BF14A7737D674 /* RLMRealmUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMRealmUtil.mm; path = Realm/RLMRealmUtil.mm; sourceTree = ""; }; - DF86A4B189E4AC67FF10D9B507853FA2 /* RLMSyncUtil.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSyncUtil.mm; path = Realm/RLMSyncUtil.mm; sourceTree = ""; }; - E37C9F700248227792DC60FFE6D5F8D8 /* RLMRealmConfiguration.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMRealmConfiguration.mm; path = Realm/RLMRealmConfiguration.mm; sourceTree = ""; }; - E4C1D302E7DA9E44265A5964B8A5FD93 /* RLMObjectBase.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObjectBase.mm; path = Realm/RLMObjectBase.mm; sourceTree = ""; }; - E4F96F975B2E88A8C9B50AB07B95B3CD /* DTTableViewManager+Registration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+Registration.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+Registration.swift"; sourceTree = ""; }; - E5727F4907EF17975910B5D42BB8E58C /* RLMSyncSession.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncSession.h; path = include/RLMSyncSession.h; sourceTree = ""; }; - E64054DFA1F5E48708A72C63D4C0370A /* MemoryStorage+UpdateWithoutAnimations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "MemoryStorage+UpdateWithoutAnimations.swift"; path = "Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift"; sourceTree = ""; }; - E65CEF9DAA5E4147882A1C0848D8F2AF /* RLMSchema.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMSchema.mm; path = Realm/RLMSchema.mm; sourceTree = ""; }; - E6CA98FF964046EC7C66391B28BF094F /* RLMListBase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMListBase.h; path = include/RLMListBase.h; sourceTree = ""; }; - E74260EB22D575024DC5228FBC8C2197 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Source/ConstraintPriorityTarget.swift; sourceTree = ""; }; - E9368BE5CA3CC81EEFBE9871BA951F4E /* Sync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sync.swift; path = RealmSwift/Sync.swift; sourceTree = ""; }; - EAAB3F222D60BB795C12F584D81E0542 /* RLMSyncCredentials.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncCredentials.h; path = include/RLMSyncCredentials.h; sourceTree = ""; }; - EAD5109EB15C46D504DA80E174E0273B /* uuid.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = uuid.cpp; path = Realm/ObjectStore/src/util/uuid.cpp; sourceTree = ""; }; - EBF63AD578849DDDD82044FF6C610E9A /* sync_session.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = sync_session.cpp; path = Realm/ObjectStore/src/sync/sync_session.cpp; sourceTree = ""; }; - EC2BB33A92D7A93B652127EB59489BC9 /* RLMObjectBase_Dynamic.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectBase_Dynamic.h; path = include/RLMObjectBase_Dynamic.h; sourceTree = ""; }; - EC51D92027327486360A76BCCABA2FEC /* UINib+Existance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UINib+Existance.swift"; path = "Sources/DTModelStorage/UINib+Existance.swift"; sourceTree = ""; }; - ECF7C4199C3A121F8B6DD2FDEB44B34F /* RLMOptionalBase.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMOptionalBase.mm; path = Realm/RLMOptionalBase.mm; sourceTree = ""; }; - ED415698AA3EB5DE427CF87AE6B2B877 /* RLMUpdateChecker.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMUpdateChecker.mm; path = Realm/RLMUpdateChecker.mm; sourceTree = ""; }; - EE5C4C8B95DB8FB3884ACDC2BFD56907 /* RLMObservation.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMObservation.mm; path = Realm/RLMObservation.mm; sourceTree = ""; }; - F00D131E27474BBE252362168003516F /* RLMSyncPermission.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSyncPermission.h; path = include/RLMSyncPermission.h; sourceTree = ""; }; - F06E86C4C5188AF4009102863AB52FFD /* RLMObjectSchema_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObjectSchema_Private.h; path = include/RLMObjectSchema_Private.h; sourceTree = ""; }; - F0A1B167BD2DDEB507724316F8048D06 /* RealmConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RealmConfiguration.swift; path = RealmSwift/RealmConfiguration.swift; sourceTree = ""; }; - F1A87B28EF9993C400DEBDF15F7FD9AE /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Source/ConstraintMultiplierTarget.swift; sourceTree = ""; }; - F25AAD1510D8A8961B046208449A88E4 /* BaseStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BaseStorage.swift; path = Sources/DTModelStorage/BaseStorage.swift; sourceTree = ""; }; - F2F2E1C2F9F3865A6D08EE0427069C34 /* collection_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = collection_notifier.cpp; path = Realm/ObjectStore/src/impl/collection_notifier.cpp; sourceTree = ""; }; - F4B268EAA2058C23CC635EBD65D0B662 /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Source/ConstraintRelatableTarget.swift; sourceTree = ""; }; - F603994BDE622506612E83CCEA121CB2 /* RLMAnalytics.mm */ = {isa = PBXFileReference; includeInIndex = 1; name = RLMAnalytics.mm; path = Realm/RLMAnalytics.mm; sourceTree = ""; }; - F7CA0BB82F5F89D00F5037115FC02A38 /* RLMObject_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMObject_Private.h; path = include/RLMObject_Private.h; sourceTree = ""; }; - F8606ABDC6A34CDF6B0BFFE5569D5B6E /* RLMCollection_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMCollection_Private.h; path = include/RLMCollection_Private.h; sourceTree = ""; }; - F86572350A8EAD5F502303916A06FC89 /* RLMSchema_Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RLMSchema_Private.h; path = include/RLMSchema_Private.h; sourceTree = ""; }; - F967EC8E34615D73A752C6E619B83F8A /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Source/ConstraintMakerExtendable.swift; sourceTree = ""; }; - F98BA3CDA21C9F5C0A564A02B92E5AFA /* DTTableViewManager+Delegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DTTableViewManager+Delegate.swift"; path = "Sources/DTTableViewManager/DTTableViewManager+Delegate.swift"; sourceTree = ""; }; - FB755329134A0AE7AE1A72007512C8BA /* weak_realm_notifier.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = weak_realm_notifier.cpp; path = Realm/ObjectStore/src/impl/weak_realm_notifier.cpp; sourceTree = ""; }; - FCB05CE00499B4F9A6549B894AB13DDB /* SwiftVersion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftVersion.swift; path = RealmSwift/SwiftVersion.swift; sourceTree = ""; }; - FDBF900C13704E3C349CCC1AAAE09B2D /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Source/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; - FE5DF8BE50F18860AD2A5402CD6A0D2C /* realm_coordinator.cpp */ = {isa = PBXFileReference; includeInIndex = 1; name = realm_coordinator.cpp; path = Realm/ObjectStore/src/impl/realm_coordinator.cpp; sourceTree = ""; }; - FE6E7FB76DF9C529D9CD3A7021E7D3C5 /* Pods-Lesson12-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Lesson12-Info.plist"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 08CD702D1429A2117569F2B2411A17CC /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 2E6C5B6B0FF9C24A29C82F72B5247E80 /* CoreData.framework in Frameworks */, - 168F5EE58AB4133A14140D47953CE310 /* Foundation.framework in Frameworks */, - 14E03A84F0AC43960D7EC2D1D222C61A /* UIKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 13F11F541D34164B14B584D318519CB6 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 168480E2A975C77B32F37553CE06B5AC /* DTModelStorage.framework in Frameworks */, - FDA216D4735B3DBE4CD394C51F446E24 /* Foundation.framework in Frameworks */, - 834B6599A6B209A582FA2DAD81BE47BC /* UIKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 04543980C4A7CE442330B0F1BC4A9A54 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 3F81A986F906693FB7FA4041342F24F4 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 4092FC1A7951B5402262D0F4148D3E68 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 57E714585194E469459E9A1FDA3471BA /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - EE2A5AE21E43B6A17BFFFE1695AF66FE /* Foundation.framework in Frameworks */, - 530EC7E20DB092A84F13DFAF89701619 /* Realm.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 814CE1FDC9DE4A46D13F0A053EA8EC97 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 8B4FC46A3DB2BD43F4046DAFA4FC8F8F /* Foundation.framework in Frameworks */, - 4702C63F91C7967ECD570C5CD8D092E3 /* Security.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 000946E7789016F28B8BF927FDEBF1D9 /* Pods-Lesson12 */ = { - isa = PBXGroup; - children = ( - 7E0032FF54C224D41AFB44C19F94EFF7 /* Pods-Lesson12.modulemap */, - 351ACFD6F28BB294CAB5D95EF421209A /* Pods-Lesson12-acknowledgements.markdown */, - 4E63ED5E1312A8515A4FE88F4D7CE934 /* Pods-Lesson12-acknowledgements.plist */, - 911B7D9BFD745E8AA0A37559DB898EBA /* Pods-Lesson12-dummy.m */, - 9F4AC1ADC59F9E8F1AEAB8201B375468 /* Pods-Lesson12-frameworks.sh */, - FE6E7FB76DF9C529D9CD3A7021E7D3C5 /* Pods-Lesson12-Info.plist */, - 3E6F1519F5C5F6C2B02A5BA985B3B40E /* Pods-Lesson12-umbrella.h */, - C04E7F51401C97CBFFE90525078D9868 /* Pods-Lesson12.debug.xcconfig */, - 60CB733150050B0A03D2C5FB83782840 /* Pods-Lesson12.release.xcconfig */, - ); - name = "Pods-Lesson12"; - path = "Target Support Files/Pods-Lesson12"; - sourceTree = ""; - }; - 08698F1DEBF28C7A43B1E40FF0374730 /* iOS */ = { - isa = PBXGroup; - children = ( - BAD19CEF1DE12B2691DB29FEC292B840 /* CoreData.framework */, - 3E6054BF9CC76ACBB4A12F26EC059CC7 /* Foundation.framework */, - 7962661A838C6885CDF1F8012F9D2108 /* Security.framework */, - B437E9E2DD5D50C699667686417A6BDE /* UIKit.framework */, - ); - name = iOS; - sourceTree = ""; - }; - 17A2DA7BCEB938FD46B4E9E6CF5C4B26 /* Realm */ = { - isa = PBXGroup; - children = ( - 28990CB3B69D5F426AC00FAD0388848D /* async_open_task.cpp */, - 9FC166983E5A48BFDE3ABE9112FBDD0E /* binding_callback_thread_observer.cpp */, - A1CBC562EC852B09B8CD2ACBD39C1EEC /* collection_change_builder.cpp */, - 4714D922CCEE7B36C134A0E4C7671DDB /* collection_notifications.cpp */, - F2F2E1C2F9F3865A6D08EE0427069C34 /* collection_notifier.cpp */, - 8A72F70546CF49ED43127DC915FAB41D /* external_commit_helper.cpp */, - 6881ACD7B5E2E79D91E759FF3A0328BF /* index_set.cpp */, - BD5C19305B180CC0D2D4142A0CDA0DE2 /* keychain_helper.cpp */, - 12B715A8E70389228ED31B65F19C360F /* list.cpp */, - 205924444AE13CD4400A7C8037655DEF /* list_notifier.cpp */, - D1B48050A06FB75408DE8922A1F9FFA3 /* network_reachability_observer.cpp */, - 5194A0EB6E38A52770B77C79FCCAF779 /* NSError+RLMSync.m */, - 25F27AB33CE0E841B278A87213AE50A8 /* object.cpp */, - 16EB414EA3030B111E1FD38437F0FCAD /* object_notifier.cpp */, - 3CB2906AE3A9E50A11DC9ED209793702 /* object_schema.cpp */, - 4F2C4966C1F8F7D76C798B9AAB71EC90 /* object_store.cpp */, - 1C22ACA9772C6A64DAC86BCE215D0644 /* partial_sync.cpp */, - C717E81CC42248D9FFF258716E2F18EB /* placeholder.cpp */, - 981F2F2BE46A6A67F1DB95FB287D72AD /* primitive_list_notifier.cpp */, - FE5DF8BE50F18860AD2A5402CD6A0D2C /* realm_coordinator.cpp */, - 4B91595DE4A0B5B7F17B4D74DB1ADB8F /* results.cpp */, - C64C7547345B55464EF85916B43708A4 /* results_notifier.cpp */, - B5882A01A23F29222C693AC6453B2C22 /* RLMAccessor.h */, - CE58AA507A58423CA7B5FEDDE9E23058 /* RLMAccessor.mm */, - F603994BDE622506612E83CCEA121CB2 /* RLMAnalytics.mm */, - B28830DD90409A0543F7F8F82849A7EC /* RLMArray.mm */, - 3D9BC1AB715B9C60E650377023BA6453 /* RLMArray_Private.h */, - 463E09DA282396F49269B9BE5AB5FFEF /* RLMClassInfo.mm */, - 33A2DD2812754AECA0F1F9ABAA9139E9 /* RLMCollection.mm */, - F8606ABDC6A34CDF6B0BFFE5569D5B6E /* RLMCollection_Private.h */, - 4AB088E51E743F45688903D4D8D2D66B /* RLMConstants.m */, - 21EDFDE383A3E251A56134BB51546D8A /* RLMJSONModels.m */, - E6CA98FF964046EC7C66391B28BF094F /* RLMListBase.h */, - B23CF3923361D3CD2BF7BCA026541078 /* RLMListBase.mm */, - CF192D8F67FA60E5D01C25180A34ED7D /* RLMManagedArray.mm */, - D799CECCDA496FD6FC0E4A8E9CF9707C /* RLMMigration.mm */, - 4E45EF266A78A58B8C91A2F04FB0D029 /* RLMNetworkClient.mm */, - BEE8A8E0F76002E7834FAFEB10374970 /* RLMObject.mm */, - F7CA0BB82F5F89D00F5037115FC02A38 /* RLMObject_Private.h */, - E4C1D302E7DA9E44265A5964B8A5FD93 /* RLMObjectBase.mm */, - 6C71F5065524F1657625088FAC3E6808 /* RLMObjectBase_Private.h */, - 40E517C7A659C9196BE238502EC31611 /* RLMObjectSchema.mm */, - F06E86C4C5188AF4009102863AB52FFD /* RLMObjectSchema_Private.h */, - 4A6D3AA87CE10E84A55129189076FA01 /* RLMObjectStore.h */, - 2FC04F46E165B5BC076542E93F20D045 /* RLMObjectStore.mm */, - EE5C4C8B95DB8FB3884ACDC2BFD56907 /* RLMObservation.mm */, - 385A3E979126AC8011F7211B7EC28505 /* RLMOptionalBase.h */, - ECF7C4199C3A121F8B6DD2FDEB44B34F /* RLMOptionalBase.mm */, - 180EA465872694E44858D9057786BFA5 /* RLMPredicateUtil.mm */, - 7C0DA5F6F3AAEF85A81BCA4825B4086D /* RLMProperty.mm */, - 5730C0642E0B713E6D46E16EC744C664 /* RLMProperty_Private.h */, - 1516938D464E51B0644674C984843905 /* RLMQueryUtil.mm */, - 4F74FB6E257915D5C1974672A2520FA5 /* RLMRealm.mm */, - 3359F271A535F71023502BD8B9F38CA8 /* RLMRealm+Sync.mm */, - 7626FBCB0DB4F4FB4A0966F840256122 /* RLMRealm_Private.h */, - E37C9F700248227792DC60FFE6D5F8D8 /* RLMRealmConfiguration.mm */, - 0A8EDE30155A51E91D2B5E200DADD8A2 /* RLMRealmConfiguration+Sync.mm */, - 57CA8968BD61AF1FB07C178ABAEBDCAF /* RLMRealmConfiguration_Private.h */, - DF0EF208569C6F026D7BF14A7737D674 /* RLMRealmUtil.mm */, - B7877F32D45F2485328B85C726E06A1E /* RLMResults.mm */, - 68E0D242B4CF6EECA616C62E84474DB4 /* RLMResults_Private.h */, - E65CEF9DAA5E4147882A1C0848D8F2AF /* RLMSchema.mm */, - F86572350A8EAD5F502303916A06FC89 /* RLMSchema_Private.h */, - B262BA381A559D0635AE9B56A311892D /* RLMSwiftSupport.m */, - 4D2B381E2885D444F3F4569560E331A4 /* RLMSyncConfiguration.mm */, - 940E4029EA051813FE224A3B6F7B61E6 /* RLMSyncConfiguration_Private.h */, - 3B31FB10E2273F59614E18103B23BC93 /* RLMSyncCredentials.m */, - 664C66D52716CF12032C6F83873CF72A /* RLMSyncManager.mm */, - 1083A4885420B80A0DEF06162BE20E5C /* RLMSyncPermission.mm */, - 19674D3C9E9AA3C53DA5162DE029918E /* RLMSyncSession.mm */, - 55A9C857A404B21A6B2AD31F34D73AB2 /* RLMSyncSessionRefreshHandle.mm */, - ADA4CA7376B38B6E954AB07A24FA8FB5 /* RLMSyncSubscription.mm */, - BF85951E33188510ED514531C7A57C32 /* RLMSyncUser.mm */, - DF86A4B189E4AC67FF10D9B507853FA2 /* RLMSyncUtil.mm */, - 83226A8F1E0F2767A08452B45B57BC29 /* RLMSyncUtil_Private.h */, - 32DE6835AFD8DCE99328A08562FC7304 /* RLMThreadSafeReference.mm */, - ED415698AA3EB5DE427CF87AE6B2B877 /* RLMUpdateChecker.mm */, - 74C1F8612B5FAC29958A3688C854B0D3 /* RLMUtil.mm */, - 24520BA6825D00730ED9C7DFF85EB308 /* schema.cpp */, - 778399867C21AA8021204104ACC147DA /* shared_realm.cpp */, - 644F8E01BE16AC1DC2EC57F200E6A6C1 /* sync_config.cpp */, - 7C710889361EE8207B98ABA2C4D2A677 /* sync_file.cpp */, - DDD68071084759E025904A0CF5E4CACE /* sync_manager.cpp */, - DDAE99C2028C04AA0EE9094DC3758018 /* sync_metadata.cpp */, - 3D2FDC0D84F98632EE7330317E6C2302 /* sync_permission.cpp */, - EBF63AD578849DDDD82044FF6C610E9A /* sync_session.cpp */, - 8907267A50CC886474A3D542965A19A9 /* sync_user.cpp */, - AA4BB6A5AD4DA3521D25B7A7B31598D2 /* system_configuration.cpp */, - 3A905DD29462C9D166D93B5223857DEA /* thread_safe_reference.cpp */, - 76A0680EEF6D60432C0739BA193D8AFB /* transact_log_handler.cpp */, - EAD5109EB15C46D504DA80E174E0273B /* uuid.cpp */, - FB755329134A0AE7AE1A72007512C8BA /* weak_realm_notifier.cpp */, - 147BC758236001BE6BC568B869EB5B6D /* work_queue.cpp */, - 7EAF5F0D7B033E069E373D5152FD1F5B /* Frameworks */, - A87C27D0F1E7F7D3143BC797076AB3DF /* Headers */, - A58DB9B925439793AC2D432E55C05181 /* Support Files */, - ); - name = Realm; - path = Realm; - sourceTree = ""; - }; - 24D297B41C6022154AC8A2D1C09E469A /* Support Files */ = { - isa = PBXGroup; - children = ( - 9F981DAC47B85F0D9FE919BB033171CD /* DTTableViewManager.modulemap */, - A35BEADF5432B761E8DF789A30215D2C /* DTTableViewManager.xcconfig */, - C78053BA00DD1B43D3361AFD59385AD2 /* DTTableViewManager-dummy.m */, - C1762070B33912BE7387C65B9816080D /* DTTableViewManager-Info.plist */, - 2E7F0F57CD0F4C1477BF8AD8178F6E0C /* DTTableViewManager-prefix.pch */, - 083618C0629088D7CF458809465AF73A /* DTTableViewManager-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/DTTableViewManager"; - sourceTree = ""; - }; - 2DCBFFDB84ED37768828E1D3EA73D2F7 /* Products */ = { - isa = PBXGroup; - children = ( - 8D7F44C29F5C323A93E174DED4DDB254 /* DTModelStorage.framework */, - A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */, - B1C773E67BF4B069808A7E8ADE542E88 /* Pods_Lesson12.framework */, - 921BE4A82C4A7A5C72A0C6F8B8FEF200 /* Realm.framework */, - 437919EE08EC6BFCCBAC3BD346309742 /* RealmSwift.framework */, - 979486118B3E90C08386079D57962701 /* SnapKit.framework */, - ); - name = Products; - sourceTree = ""; - }; - 3F746F4B9F3C432D85AC28093953F5D0 /* Support Files */ = { - isa = PBXGroup; - children = ( - 63D6B294B05701775E010AC526CB9D77 /* RealmSwift.modulemap */, - 62B9A4A867C31B9B15A7A69A95EC4876 /* RealmSwift.xcconfig */, - 85B46BBDF4E92F9E14C5B3E25BE55588 /* RealmSwift-dummy.m */, - 789E057A5CF6AE2F75A3E5A47AA690EC /* RealmSwift-Info.plist */, - 57222B8653830F1ED81211926DF5A060 /* RealmSwift-prefix.pch */, - 467846062075DF9A615F0712528D51CD /* RealmSwift-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/RealmSwift"; - sourceTree = ""; - }; - 4413E7A09E59513E0C616AF65C2CB569 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 73226A3C25999F7DBB805EBC80CC4255 /* DTModelStorage.framework */, - 8EBFE37C26992B4DD024F56CE87F9AD4 /* Realm.framework */, - 08698F1DEBF28C7A43B1E40FF0374730 /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - 4711FD7D0E4EDAA80B96C7135E7BCBDC /* Support Files */ = { - isa = PBXGroup; - children = ( - 49A70E08C233891700C4E8171EE3841D /* SnapKit.modulemap */, - 0589B80789798770DC6C2CA206518B07 /* SnapKit.xcconfig */, - 71BF55D66A00B7440DF166FE1DFCCB2B /* SnapKit-dummy.m */, - 332E388AC73063ABF70E858AC63EF417 /* SnapKit-Info.plist */, - 29A6623BC5A747B5D3FE4D29896046F5 /* SnapKit-prefix.pch */, - 439DD2ED964B85F221832C11D774EB8E /* SnapKit-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/SnapKit"; - sourceTree = ""; - }; - 47744D6720F1B908D4E5B09AB30F9039 /* RealmSwift */ = { - isa = PBXGroup; - children = ( - 7C476BB5591A011F11627DBA609467E2 /* Aliases.swift */, - 61C0831E1A5A5F9BAE73DB2BCBAC1CE6 /* Error.swift */, - 072B68414DD27FF40271269943D5481E /* LinkingObjects.swift */, - D9E00CC2D0D1AED18E5F6376107D503C /* List.swift */, - 9CDDB1047780AAB8197609AE2BE4C856 /* Migration.swift */, - DA0DF3C2211484ED19DF5E089344E170 /* Object.swift */, - 2A7D4E01FFA210388B2222C35DD50FD6 /* ObjectiveCSupport.swift */, - 394E9BF21C25ED2E5345E53020A5CC3D /* ObjectiveCSupport+Sync.swift */, - CB68296FEF989F38D67625187DFDC2A4 /* ObjectSchema.swift */, - 9A35EE58F7669385825A01A135CD0491 /* Optional.swift */, - 59DD1951661B55FBB6E5561C5E6A6641 /* Property.swift */, - C40098B8DEB3229D47B663D80E0813D9 /* Realm.swift */, - 67F84B83E4860C3D13E46A83C6033C47 /* RealmCollection.swift */, - F0A1B167BD2DDEB507724316F8048D06 /* RealmConfiguration.swift */, - 33321F2CD36D73D1A44684BD2F159AF0 /* Results.swift */, - 4935C70EBBD3BDC88BA42FB0D34B93DE /* Schema.swift */, - 3BBF9E1FE4BE88841D92BD4F7D49DD12 /* SortDescriptor.swift */, - FCB05CE00499B4F9A6549B894AB13DDB /* SwiftVersion.swift */, - E9368BE5CA3CC81EEFBE9871BA951F4E /* Sync.swift */, - D657CEEA4664E23DDBCAF74EB352D3B5 /* ThreadSafeReference.swift */, - BAC764CE511370D9847A2392D1D55C73 /* Util.swift */, - 3F746F4B9F3C432D85AC28093953F5D0 /* Support Files */, - ); - name = RealmSwift; - path = RealmSwift; - sourceTree = ""; - }; - 5439C37A890E9B2A3DA3073A14E23E17 /* SnapKit */ = { - isa = PBXGroup; - children = ( - 6913ADD3EBC59D0E9D381BEA66098F50 /* Constraint.swift */, - 7F257C890C5BA74E7CF941B82C741C56 /* ConstraintAttributes.swift */, - 6726AFA0176A345BC0CA041F40C91D08 /* ConstraintConfig.swift */, - 7230E3B4D79A605F74D8C9E619F81F85 /* ConstraintConstantTarget.swift */, - 7EEB0CADB7C3F9B63A159DF537792DC4 /* ConstraintDescription.swift */, - CC0E36BD9D81DE0383BBAE911F2DF9C4 /* ConstraintDirectionalInsets.swift */, - 8B005D46C74CFA9A8251EBA2B7DF0CFA /* ConstraintDirectionalInsetTarget.swift */, - 52D11ADC324C5332A4F6299A79430067 /* ConstraintDSL.swift */, - A6C0C2966A4A5D3599B61ED5EAE870BF /* ConstraintInsets.swift */, - 240AD0928397EDD73DBA6FA830C2F200 /* ConstraintInsetTarget.swift */, - A3F91BBE7AF9F154EF08C316238670E2 /* ConstraintItem.swift */, - 87EBD3107688814C52D9C3DFFE4C05A3 /* ConstraintLayoutGuide.swift */, - 539DD206E6B4E2DE0FC82DF732FC8E76 /* ConstraintLayoutGuide+Extensions.swift */, - 7AB046C46DB77ED8BA8F9BDA9F271138 /* ConstraintLayoutGuideDSL.swift */, - 642B46585C61DCCE79A43F69CC13CD53 /* ConstraintLayoutSupport.swift */, - 8CA3FFE66F25DC21E5B98E8F15E536A3 /* ConstraintLayoutSupportDSL.swift */, - 91E61A2A30FDB2108A53B95E11B2CCB7 /* ConstraintMaker.swift */, - 3D54E81BDD6D4184B6D7112334877DC3 /* ConstraintMakerEditable.swift */, - F967EC8E34615D73A752C6E619B83F8A /* ConstraintMakerExtendable.swift */, - B092C8AF4A98CF45C6D1B26A0112D99D /* ConstraintMakerFinalizable.swift */, - 03AE55402C8DD9016517B857675BFA2E /* ConstraintMakerPriortizable.swift */, - C283EA9E079F3598F412CEFF2167CD91 /* ConstraintMakerRelatable.swift */, - F1A87B28EF9993C400DEBDF15F7FD9AE /* ConstraintMultiplierTarget.swift */, - 862AFD197149B8569B424BDE9510D221 /* ConstraintOffsetTarget.swift */, - 4825BA092AE4221CD1C2FD69CAA8C577 /* ConstraintPriority.swift */, - E74260EB22D575024DC5228FBC8C2197 /* ConstraintPriorityTarget.swift */, - F4B268EAA2058C23CC635EBD65D0B662 /* ConstraintRelatableTarget.swift */, - 9DCFD9448E93E8D52A0BFC8E487D79A4 /* ConstraintRelation.swift */, - DAACEBB9AA0416B30137379B9A48EE8B /* ConstraintView.swift */, - CFC738E414DCDEDDF7D8D2E6C1053446 /* ConstraintView+Extensions.swift */, - 6BE59092C1B6889846B48FA19267C0DC /* ConstraintViewDSL.swift */, - 03D883FE0F80438243F85F3090469E58 /* Debugging.swift */, - 52DBA640AED2F6F34036625774076D4D /* LayoutConstraint.swift */, - 24B46237E6B206F33C48065315A194AA /* LayoutConstraintItem.swift */, - 4FC9128FB437A8E6B3C211DC0C88004E /* Typealiases.swift */, - FDBF900C13704E3C349CCC1AAAE09B2D /* UILayoutSupport+Extensions.swift */, - 4711FD7D0E4EDAA80B96C7135E7BCBDC /* Support Files */, - ); - name = SnapKit; - path = SnapKit; - sourceTree = ""; - }; - 7EAF5F0D7B033E069E373D5152FD1F5B /* Frameworks */ = { - isa = PBXGroup; - children = ( - D7FB328B75EAF13BB9C043DC8E767448 /* librealmcore-ios.a */, - ); - name = Frameworks; - sourceTree = ""; - }; - 899A246385E89D580765053AD33D1E02 /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - 000946E7789016F28B8BF927FDEBF1D9 /* Pods-Lesson12 */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; - 8E3CB54A66A0A20EB0D735B63F8304B7 /* DTModelStorage */ = { - isa = PBXGroup; - children = ( - 9BA7BE3C2CA0BBF0EBEEC81082D96494 /* Core */, - A1F5E931DE05DCDCF0DC10365B227413 /* Support Files */, - ); - name = DTModelStorage; - path = DTModelStorage; - sourceTree = ""; - }; - 909CD089176E53B4FE2EEA09EA6BEC9D /* Pods */ = { - isa = PBXGroup; - children = ( - 8E3CB54A66A0A20EB0D735B63F8304B7 /* DTModelStorage */, - 9B26051825A7E4EEA5FDD6147ACD957F /* DTTableViewManager */, - 17A2DA7BCEB938FD46B4E9E6CF5C4B26 /* Realm */, - 47744D6720F1B908D4E5B09AB30F9039 /* RealmSwift */, - 5439C37A890E9B2A3DA3073A14E23E17 /* SnapKit */, - ); - name = Pods; - sourceTree = ""; - }; - 9B26051825A7E4EEA5FDD6147ACD957F /* DTTableViewManager */ = { - isa = PBXGroup; - children = ( - DC0D2F818024F7F7CC0A029A727816AA /* BackwardsCompatibility.swift */, - 2977EA8AA20923C44E80AAFC1A6F3222 /* DTTableViewDataSource.swift */, - CD94DA44E270CDB057579FA88B39883E /* DTTableViewDelegate.swift */, - A6C41A5F855BA7C4A3D21CC85CABA10C /* DTTableViewDelegateWrapper.swift */, - 5A2F892D6FCA6C28ED679E370B18CDE9 /* DTTableViewDragDelegate.swift */, - 0A3212B24B75D44F977B3A62A4FB68DB /* DTTableViewDropDelegate.swift */, - 2A2C7E26B2784AEE83ED67176365A58B /* DTTableViewDropPlaceholderContext.swift */, - 83BBA83C8AD1E1A7BAC41F307D14F669 /* DTTableViewManager.swift */, - CFA85E1304D239D6A6A95C79A4918214 /* DTTableViewManager+DataSource.swift */, - F98BA3CDA21C9F5C0A564A02B92E5AFA /* DTTableViewManager+Delegate.swift */, - 1680DE752CFF211598AA28BA23DC0423 /* DTTableViewManager+Drag.swift */, - 90BF1A1247D2F23ADE5ADCA24D1D28EC /* DTTableViewManager+Drop.swift */, - E4F96F975B2E88A8C9B50AB07B95B3CD /* DTTableViewManager+Registration.swift */, - A6BB363083C035E6988F54E9A44982FF /* DTTableViewManagerAnomalyHandler.swift */, - BAEC53929DBDB1101C311029FB1A5A5A /* TableViewConfiguration.swift */, - 7E06DEA517360838F7E6F503976CD655 /* TableViewFactory.swift */, - 8F59BE00B7EE46EFC70821C1E5DE811B /* TableViewUpdater.swift */, - 613F36E25BEC199D7DE60CC8F891BB76 /* UIView+XibLoading.swift */, - 24D297B41C6022154AC8A2D1C09E469A /* Support Files */, - ); - name = DTTableViewManager; - path = DTTableViewManager; - sourceTree = ""; - }; - 9BA7BE3C2CA0BBF0EBEEC81082D96494 /* Core */ = { - isa = PBXGroup; - children = ( - 8AFC1E88C8C18507112F90DC8F907645 /* AccumulationStrategy.swift */, - 110A8836C3844ECCE172E4B315C14D5C /* AnomalyHandler.swift */, - F25AAD1510D8A8961B046208449A88E4 /* BaseStorage.swift */, - 48D9995270C83F315AFE4069D26661B2 /* CoreDataStorage.swift */, - A6F478FC4B97F58B619554CC291ECCF1 /* EventReactions.swift */, - 63315A69198070A681994D590BBD42ED /* MemoryStorage.swift */, - E64054DFA1F5E48708A72C63D4C0370A /* MemoryStorage+UpdateWithoutAnimations.swift */, - 4099E157F7F8FD6588668F172659E2A7 /* ModelTransfer.swift */, - DEFB9B52BC635068A822A8830FD5AEF7 /* ProxyDiffableDataSourceStorage.swift */, - 273DA2E6224B9EA0181B06B50F8C5B39 /* RuntimeHelper.swift */, - AFD0CAAC8C1C696AC1294007FB1D6EA4 /* Section.swift */, - 9BD817C7300CEFDC2B38E4BA2CE97F12 /* SectionModel.swift */, - DED40C8AFCCC2C704B7DC2D93E75DE56 /* SectionProtocols.swift */, - 37267A6188287FEB6B93C67DBE9A517A /* SingleSectionDiffing.swift */, - 4489D501A65F0FFFCB1B928E1B1CF8E8 /* SingleSectionStorage.swift */, - 884F556E058A9DDA81ACB4B57760E082 /* StorageProtocols.swift */, - 912A7824E526E706ADF17636A87C8AAC /* StorageUpdate.swift */, - EC51D92027327486360A76BCCABA2FEC /* UINib+Existance.swift */, - AE7FE5AE8A0B542B038BFF6E8E0B46B7 /* ViewModelMapping.swift */, - ); - name = Core; - sourceTree = ""; - }; - A1F5E931DE05DCDCF0DC10365B227413 /* Support Files */ = { - isa = PBXGroup; - children = ( - 4D2CA8C9C3EC78FD1CC396472819EDAD /* DTModelStorage.modulemap */, - 4D1513A17CD9C965CEC10CB203F69CF2 /* DTModelStorage.xcconfig */, - 7A505FD515BAA6636F6D6363877150F1 /* DTModelStorage-dummy.m */, - 018C9874C67DCA911E8AD2EBE1174F7B /* DTModelStorage-Info.plist */, - DE344BB25054A813F1438C84A4BB948B /* DTModelStorage-prefix.pch */, - A45825178B6ADCC06CD7AA31113287A9 /* DTModelStorage-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/DTModelStorage"; - sourceTree = ""; - }; - A58DB9B925439793AC2D432E55C05181 /* Support Files */ = { - isa = PBXGroup; - children = ( - 7AA773B5E79F4F73D15464BDC5721177 /* Realm.modulemap */, - 25705CA1710F89251D9929DCF3D1F08A /* Realm.xcconfig */, - 9FF0033B28EAB2BBC47A324C37EB13EC /* Realm-dummy.m */, - 4AD2D182CD2BFCF831AAB8ACF8D45BF9 /* Realm-Info.plist */, - 6300FF17FE30A52A38EC7D7E1F736A9E /* Realm-prefix.pch */, - ); - name = "Support Files"; - path = "../Target Support Files/Realm"; - sourceTree = ""; - }; - A87C27D0F1E7F7D3143BC797076AB3DF /* Headers */ = { - isa = PBXGroup; - children = ( - C6EC7AB761B7755F64E1AA0339DD01C5 /* NSError+RLMSync.h */, - 445878DC71013C9D0CC42ADB420DD563 /* Realm.h */, - BC0F4D611C9EA3BAFA7BC6C34945BBE5 /* RLMArray.h */, - 1F0E2A67636815327AF51E8324AC7DFF /* RLMCollection.h */, - 3F57B49A0FA692575F0606763D7A9F07 /* RLMConstants.h */, - 04A8F2229E09694DEB1FF0F56FAB5DF7 /* RLMMigration.h */, - 7740C7998C1E0ED03EB9222CC2BE9B64 /* RLMObject.h */, - A8285F9C4A29355AF7659A1EBD2E179F /* RLMObjectBase.h */, - EC2BB33A92D7A93B652127EB59489BC9 /* RLMObjectBase_Dynamic.h */, - 3040BA8B8BF3441A8A25C292951EE282 /* RLMObjectSchema.h */, - BEA345D3718292AC478C1585AA32958B /* RLMPlatform.h */, - 3B8C0C088A43AF55F2F1804C536FF82B /* RLMProperty.h */, - D219B16E47E5854B2B9B80326D823559 /* RLMRealm.h */, - 0B9A4143194FD94ED0FC12F263C7222B /* RLMRealm+Sync.h */, - DB5FBF630A2A4A790E0AA44490038B22 /* RLMRealm_Dynamic.h */, - 372E3888C543E4F7354D55B652942A31 /* RLMRealmConfiguration.h */, - BC99A40943538DC1761A8F623E480CC9 /* RLMRealmConfiguration+Sync.h */, - 0B216D4857F045F87E7D90352446172F /* RLMResults.h */, - 96820C3C661F733FF50D3B2EBC178AD0 /* RLMSchema.h */, - DDCDF9F009A106410A660DDBD032F3B1 /* RLMSyncConfiguration.h */, - EAAB3F222D60BB795C12F584D81E0542 /* RLMSyncCredentials.h */, - 5BA121DEBDEFE4FE4C6CB10F50CB0C20 /* RLMSyncManager.h */, - F00D131E27474BBE252362168003516F /* RLMSyncPermission.h */, - E5727F4907EF17975910B5D42BB8E58C /* RLMSyncSession.h */, - 8B7AE71079AFC8D636C516AD4F0761CA /* RLMSyncSubscription.h */, - 1F2A650980474B09474FBD14355A3EFB /* RLMSyncUser.h */, - AA94BDFD0BC51FFBD31ED2D027E28B63 /* RLMSyncUtil.h */, - 1CECF04B4631D24458F6D379B1BF6FAF /* RLMThreadSafeReference.h */, - ); - name = Headers; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - 4413E7A09E59513E0C616AF65C2CB569 /* Frameworks */, - 909CD089176E53B4FE2EEA09EA6BEC9D /* Pods */, - 2DCBFFDB84ED37768828E1D3EA73D2F7 /* Products */, - 899A246385E89D580765053AD33D1E02 /* Targets Support Files */, - ); - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 12936760E1153D2E8EB70500E0D7B965 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 9BAED39893E3A38E86EC0CB7F1B4664D /* RealmSwift-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 1740E12E14304B1B25D76EB608388017 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 30AA515CC73339676F3E4AD889BA0BD1 /* DTTableViewManager-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 521B7A70F646C047AFB28C29AA9850FA /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 8A782F5B16AB7C0003017D728FBD849B /* DTModelStorage-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - A66ED57B365A35434C5BAF4B990819B7 /* SnapKit-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7FCB86B520A54E0B5AEAD6299B49364D /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 00FE6361A6938BF20B5CB06A46872D38 /* Pods-Lesson12-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 93AAA6E3EB2241BD545A3DAF71A2F378 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 1F2F06D3F5D78980F67821B553F0883B /* NSError+RLMSync.h in Headers */, - E8A754B37F44784D8B78A872DE6B2C92 /* Realm.h in Headers */, - C2A9D7E2A7356B9BD179D726A2418F4B /* RLMAccessor.h in Headers */, - BCF68AD207127F823C99CEB4AD4AAE5D /* RLMArray.h in Headers */, - 57B3FEF620AA9F256E6DFC810DF30C04 /* RLMArray_Private.h in Headers */, - 1528AD86DB13AF6FD139D29AD8F17999 /* RLMCollection.h in Headers */, - 89DE4BDBF92376984DFFA4D6B9A789E7 /* RLMCollection_Private.h in Headers */, - D02A8F3A322426429314853341237059 /* RLMConstants.h in Headers */, - B4A64C9136805CB6BE283579A76C7658 /* RLMListBase.h in Headers */, - 2417A9EEC50FA31DD6F764CE4A64762F /* RLMMigration.h in Headers */, - F489AF2C3A4BAA41260095DAB13D5C17 /* RLMObject.h in Headers */, - EB86DF3DFB2AF93D4DB8CDD6F7295F73 /* RLMObject_Private.h in Headers */, - 73AC76F3FEC279A4AF42D33F3743EFB1 /* RLMObjectBase.h in Headers */, - 487D53153D55CE66F0EB58DD50702B51 /* RLMObjectBase_Dynamic.h in Headers */, - 7A2C7D86EEC730D0860FDBCCFA634D19 /* RLMObjectBase_Private.h in Headers */, - 26F0BB95414AA62ACBB0983D8385C6A3 /* RLMObjectSchema.h in Headers */, - B34A0A6D659D5D2F79FEEEAF83B87B43 /* RLMObjectSchema_Private.h in Headers */, - 05E537D6954BE54C14B0C2D0BD748B27 /* RLMObjectStore.h in Headers */, - AB378EF4F418F0A00D68FA7B37A60491 /* RLMOptionalBase.h in Headers */, - C1147050F9B9901A377C3A9B6E253612 /* RLMPlatform.h in Headers */, - 7ED9728B8FDE98CAAA531D19854AFA4A /* RLMProperty.h in Headers */, - CC272BD40CB17460F25E41C5F1604501 /* RLMProperty_Private.h in Headers */, - 0624DA01ECA96AE03CA4CD86AE0DD698 /* RLMRealm+Sync.h in Headers */, - DB94BFB21436F7294C66D5CC40307397 /* RLMRealm.h in Headers */, - 1124DA5AA0690636691F8C16B54BE187 /* RLMRealm_Dynamic.h in Headers */, - A9F434D093BEFF605C24C2D0B71B4767 /* RLMRealm_Private.h in Headers */, - 015A0369EB034ABD53223DCC1697046C /* RLMRealmConfiguration+Sync.h in Headers */, - 163DF9C4EF2939A35285E5487D8AC718 /* RLMRealmConfiguration.h in Headers */, - F3365FB46BF0E869D92A464B07BB9948 /* RLMRealmConfiguration_Private.h in Headers */, - 84E1FE5DD6DE9A0C7764A29FC9F11155 /* RLMResults.h in Headers */, - F15001312B4A1AFC5C0C39DB4B63962A /* RLMResults_Private.h in Headers */, - 671CD8B463F59407A51B7C18F8DBD7E1 /* RLMSchema.h in Headers */, - FEC148147D381D36ABDEAB648CFDB90A /* RLMSchema_Private.h in Headers */, - CD19EBB20252CC326563A92DF6098DC5 /* RLMSyncConfiguration.h in Headers */, - 4A954E1410CC831251D1883F3341A975 /* RLMSyncConfiguration_Private.h in Headers */, - 7B3161F2A225550C77AFEA5B4376A50B /* RLMSyncCredentials.h in Headers */, - AADBCD1B21CD4A8302788D60CBA914EB /* RLMSyncManager.h in Headers */, - D844CF4AE7817A9A17D4BEC4BC39598E /* RLMSyncPermission.h in Headers */, - CB40C58EF0AFEC7A5076DA07A08179C1 /* RLMSyncSession.h in Headers */, - 84E8B926FACE4FA809F931BFB6CEF96D /* RLMSyncSubscription.h in Headers */, - 329FC3E722DE36B8B00674D23CCB031E /* RLMSyncUser.h in Headers */, - 3820FCCABF659770A7A74440C3001C87 /* RLMSyncUtil.h in Headers */, - BF08EB397775EFE40ABE7B19BA55B672 /* RLMSyncUtil_Private.h in Headers */, - A3F37516CDD7B7C6E9E67F7937775CB8 /* RLMThreadSafeReference.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { - isa = PBXNativeTarget; - buildConfigurationList = 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */; - buildPhases = ( - 7DFCF5F12AEEED0500986DBC9BF76170 /* Headers */, - 89222AF845A30312C284F407BA48B98F /* Sources */, - 3C8B1704CC97EF12D3409771318C6433 /* Frameworks */, - 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = SnapKit; - productName = SnapKit; - productReference = 979486118B3E90C08386079D57962701 /* SnapKit.framework */; - productType = "com.apple.product-type.framework"; - }; - 3EF3490B4B0DD7F07469ADEE907B9E59 /* DTTableViewManager */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1A342D90638B02D992A14313597765C2 /* Build configuration list for PBXNativeTarget "DTTableViewManager" */; - buildPhases = ( - 1740E12E14304B1B25D76EB608388017 /* Headers */, - 3010A8698DF99E86EE44ACAB0B1068CA /* Sources */, - 13F11F541D34164B14B584D318519CB6 /* Frameworks */, - F8B1B1BD912B90951517DEC8901D1ABF /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 904D619A8DD745E4591136B946231ACB /* PBXTargetDependency */, - ); - name = DTTableViewManager; - productName = DTTableViewManager; - productReference = A076ED6E3C75D009316EEC7E55F2810B /* DTTableViewManager.framework */; - productType = "com.apple.product-type.framework"; - }; - 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */ = { - isa = PBXNativeTarget; - buildConfigurationList = C78C1F585AF9F23F8E5BE58C65DFB1B0 /* Build configuration list for PBXNativeTarget "Realm" */; - buildPhases = ( - 93AAA6E3EB2241BD545A3DAF71A2F378 /* Headers */, - 19B5DC80E1527C4C9FB77505BB071140 /* Sources */, - 814CE1FDC9DE4A46D13F0A053EA8EC97 /* Frameworks */, - 76BE90AD3450229977577041A0B3137B /* Resources */, - 31E1852A7D8B204006F453FB1209492D /* Copy . Private Headers */, - 1F16170A859A60D821655356EE33494F /* Copy . Public Headers */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Realm; - productName = Realm; - productReference = 921BE4A82C4A7A5C72A0C6F8B8FEF200 /* Realm.framework */; - productType = "com.apple.product-type.framework"; - }; - 782725687624F8665247B84AB581BEB1 /* RealmSwift */ = { - isa = PBXNativeTarget; - buildConfigurationList = 22886CEE8A1196C43C2AD1112FC689C4 /* Build configuration list for PBXNativeTarget "RealmSwift" */; - buildPhases = ( - 12936760E1153D2E8EB70500E0D7B965 /* Headers */, - 02332DDABEC84D721F48118D5F43BFAA /* Sources */, - 57E714585194E469459E9A1FDA3471BA /* Frameworks */, - 13B653C20CC1D0B28162EEB3B2D27AE7 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - B0F2CB59E7E3549DFC145C2E0973B40E /* PBXTargetDependency */, - ); - name = RealmSwift; - productName = RealmSwift; - productReference = 437919EE08EC6BFCCBAC3BD346309742 /* RealmSwift.framework */; - productType = "com.apple.product-type.framework"; - }; - A6897EC32E89F90D011B77C5EA296C1B /* Pods-Lesson12 */ = { - isa = PBXNativeTarget; - buildConfigurationList = DBC3F2C104B3E116B2B4121D5AF43206 /* Build configuration list for PBXNativeTarget "Pods-Lesson12" */; - buildPhases = ( - 7FCB86B520A54E0B5AEAD6299B49364D /* Headers */, - 0233DACB0400653C53145DAA97B7F44B /* Sources */, - 3F81A986F906693FB7FA4041342F24F4 /* Frameworks */, - C31817F7F332484EDBC41FFA11E2C1E3 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 0EF860BD8F33683695DAF4F820E0343A /* PBXTargetDependency */, - 3E0AFFD599B51C8DC892A37730388036 /* PBXTargetDependency */, - 26B041B2BF86DF8FDE6B30D88F728275 /* PBXTargetDependency */, - BF61B04164760CDA17C84A5FA6C6563B /* PBXTargetDependency */, - BDD84D5D0C58DE3C6ECEF80DB9DC63AE /* PBXTargetDependency */, - ); - name = "Pods-Lesson12"; - productName = "Pods-Lesson12"; - productReference = B1C773E67BF4B069808A7E8ADE542E88 /* Pods_Lesson12.framework */; - productType = "com.apple.product-type.framework"; - }; - E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */ = { - isa = PBXNativeTarget; - buildConfigurationList = BA6271B202E8EC84ACB5775DDA67F32F /* Build configuration list for PBXNativeTarget "DTModelStorage" */; - buildPhases = ( - 521B7A70F646C047AFB28C29AA9850FA /* Headers */, - 5A2AE47FA31C7306BE73BC410FB18B2A /* Sources */, - 08CD702D1429A2117569F2B2411A17CC /* Frameworks */, - 6E8C1AE67879928E1C17593D9565D540 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = DTModelStorage; - productName = DTModelStorage; - productReference = 8D7F44C29F5C323A93E174DED4DDB254 /* DTModelStorage.framework */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1100; - LastUpgradeCheck = 1100; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 10.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 2DCBFFDB84ED37768828E1D3EA73D2F7 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */, - 3EF3490B4B0DD7F07469ADEE907B9E59 /* DTTableViewManager */, - A6897EC32E89F90D011B77C5EA296C1B /* Pods-Lesson12 */, - 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */, - 782725687624F8665247B84AB581BEB1 /* RealmSwift */, - 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 13B653C20CC1D0B28162EEB3B2D27AE7 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 6E8C1AE67879928E1C17593D9565D540 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 76BE90AD3450229977577041A0B3137B /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 9C691CAA90D9565F2EFF5EF823D8A80C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C31817F7F332484EDBC41FFA11E2C1E3 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8B1B1BD912B90951517DEC8901D1ABF /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 02332DDABEC84D721F48118D5F43BFAA /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - F28BFCB7597D463ECD8CF3DF3B596211 /* Aliases.swift in Sources */, - BBCC6DDC1E888668E9DB4E11FDECBE76 /* Error.swift in Sources */, - 3CAC503A5DAA8D2DFB6895C2F4F46591 /* LinkingObjects.swift in Sources */, - E6A59169AB160B828757961CC391334C /* List.swift in Sources */, - D1E16D8B852B793DC73D69F98267636C /* Migration.swift in Sources */, - 70BCE5BACB52D99796645EE3A451B783 /* Object.swift in Sources */, - 42243F8F8A3A333A3543A3798E0BB9B2 /* ObjectiveCSupport+Sync.swift in Sources */, - 12A94B085B960FFF94A98BCF9F6E27E0 /* ObjectiveCSupport.swift in Sources */, - AC0F5BE9969AFF9FC4DBF4D3115917ED /* ObjectSchema.swift in Sources */, - FB16D14072713E368969885E4ECD099B /* Optional.swift in Sources */, - 79120D7382A3564038E796B8872271AC /* Property.swift in Sources */, - 354BE05906E0CB457569A8E29F9D8532 /* Realm.swift in Sources */, - 2B374445507BAC21E6FDCE6318EB1023 /* RealmCollection.swift in Sources */, - 17CE12E3F777B243FCE5AC6201AEF303 /* RealmConfiguration.swift in Sources */, - 436803A8CCC81A15C5EA20B71B444217 /* RealmSwift-dummy.m in Sources */, - E22BB3552C77566B1B6955CE66218BCD /* Results.swift in Sources */, - AABEE951C89957EB5E1FCD3D25CD45B4 /* Schema.swift in Sources */, - AC7D415C826932227566EB2B916A7C26 /* SortDescriptor.swift in Sources */, - 17E74A0C302C627A1374F313FA16E7EE /* SwiftVersion.swift in Sources */, - 3BD063008F14A0D06586F954907110D9 /* Sync.swift in Sources */, - ADF1076FF0CE456B5E0E046EEC33CD97 /* ThreadSafeReference.swift in Sources */, - 45EDE7CCF5471B181EA12B3C8FC66F4D /* Util.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 0233DACB0400653C53145DAA97B7F44B /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3C73AB0188912D4205DC2503BA8A27E4 /* Pods-Lesson12-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 19B5DC80E1527C4C9FB77505BB071140 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - FF4B2BB0EF29444776166A439A9D4E30 /* async_open_task.cpp in Sources */, - 0E031C031301B192EA4337E12804CC70 /* binding_callback_thread_observer.cpp in Sources */, - D28C130F5F3012F587CC16763CBD3DBE /* collection_change_builder.cpp in Sources */, - 0EC3A2761F6C42CDFC6CAF132CB0B83F /* collection_notifications.cpp in Sources */, - AACEBC8596A841C7B61CD7E1A9AE2DE4 /* collection_notifier.cpp in Sources */, - 45792F139DDBCE8090EA0D61771C5A9E /* external_commit_helper.cpp in Sources */, - CB2B572644D56110576B961927A43B1E /* index_set.cpp in Sources */, - 14F7AFD9FFD7EB0B3CB02DA66BEE976F /* keychain_helper.cpp in Sources */, - C81A970A0C95B15D031D606D0F987BA7 /* list.cpp in Sources */, - 22F963CEA7CC2CA57EBEAEE4DA490029 /* list_notifier.cpp in Sources */, - B5AD279F634D06859F4F4FB1E02D3FF0 /* network_reachability_observer.cpp in Sources */, - 6808C5BEF3D1556A431CD453E63E7E38 /* NSError+RLMSync.m in Sources */, - EE19F864673AF83DB4C21CA8464455AC /* object.cpp in Sources */, - B5FF707FEE8A4B13B59255108E0151E7 /* object_notifier.cpp in Sources */, - 688EE044B4D96D5DA2E7B700CCD3B2BF /* object_schema.cpp in Sources */, - D87888C7A3F26BFAD3127B56D8AB474E /* object_store.cpp in Sources */, - B3D636D90E51741683F376016D836355 /* partial_sync.cpp in Sources */, - BE33F3D2B1E4AA74939221284D92652C /* placeholder.cpp in Sources */, - C1F1C70CEE7F80A8BBECBF05FCF79142 /* primitive_list_notifier.cpp in Sources */, - C49FEFB601CD36B3BE61FB6D4494D733 /* Realm-dummy.m in Sources */, - ED3035ABEBCD639F75DDC5C472795706 /* realm_coordinator.cpp in Sources */, - 5290BB41346D30D8DAF45533FB141177 /* results.cpp in Sources */, - F76444CD589D114686BB510A6066CE67 /* results_notifier.cpp in Sources */, - 50B7D08F90D2D6435BBE891E1547332E /* RLMAccessor.mm in Sources */, - 05E61A3ADD15D7CB6C969A76E95EAAF9 /* RLMAnalytics.mm in Sources */, - 2E638CEA645E715DB0E123AD6A08647D /* RLMArray.mm in Sources */, - F03298753DA84C04036A6A3D24D96950 /* RLMClassInfo.mm in Sources */, - 1CB5C6760130C03AE56AD4870F1C1457 /* RLMCollection.mm in Sources */, - ADC590829802B94CE186B3E5DBC57D7B /* RLMConstants.m in Sources */, - CF585AA54281BB45C03037C4A4C56AED /* RLMJSONModels.m in Sources */, - FB1DC2E9C1E29C6641CF63A061C7717A /* RLMListBase.mm in Sources */, - 0250F77A3345CB64BCB6492E9D8D3FD3 /* RLMManagedArray.mm in Sources */, - 3E05EFB380BB32DD4E9D12038BB6A6C7 /* RLMMigration.mm in Sources */, - 430FBA64DC0FC3E07D39B0DAF4657C81 /* RLMNetworkClient.mm in Sources */, - 5B35E48760312B860F68C7472603D686 /* RLMObject.mm in Sources */, - 8D4B51F2A6E57273E12A76C160B2CC4F /* RLMObjectBase.mm in Sources */, - 4516012F99A1A9B2EA4313B79E29A580 /* RLMObjectSchema.mm in Sources */, - A8E82498433F11FB31D93E4F8DE0AE6F /* RLMObjectStore.mm in Sources */, - A2F591F45DBBFB19EFBBC5CCF8BA2793 /* RLMObservation.mm in Sources */, - B7CC2CEBDCF42DB4BCF7FDCA67991C6F /* RLMOptionalBase.mm in Sources */, - 33FED9F98332B8339C1D056B51E97B4C /* RLMPredicateUtil.mm in Sources */, - 7EC9F94A0049BFFDFD0B8795F08B4A37 /* RLMProperty.mm in Sources */, - 0E9649E3134E8BC6C9380EC78E376481 /* RLMQueryUtil.mm in Sources */, - F7C4C0980A7CD46EDCAAF366A722FFCD /* RLMRealm+Sync.mm in Sources */, - 655154DB907EF05CED9DA1664D45DC05 /* RLMRealm.mm in Sources */, - DA84AF88D7E5CD43D8BDE2CBC55296BD /* RLMRealmConfiguration+Sync.mm in Sources */, - 268A0739FE706CAD204F61702EEA9CB6 /* RLMRealmConfiguration.mm in Sources */, - 0FEACBA97148B598AA27162DDE4C7E4F /* RLMRealmUtil.mm in Sources */, - E83D2896CD2930EB85C3343E33752B47 /* RLMResults.mm in Sources */, - 97F26585AD4B634C86136CEF0E5B1EF2 /* RLMSchema.mm in Sources */, - 59EAF48CDE5B2776073636EF02FABB06 /* RLMSwiftSupport.m in Sources */, - 1A6FAC76E6834F1EDF069FF9FB4A189B /* RLMSyncConfiguration.mm in Sources */, - 665FFAEB9248C6D0998E934BB75D3F75 /* RLMSyncCredentials.m in Sources */, - 9D89150563C25286D022E024EAAE0224 /* RLMSyncManager.mm in Sources */, - DD76BA97F4C10B0FD53483BC8356C895 /* RLMSyncPermission.mm in Sources */, - 24F7392348EAB0ED45B6B1DCA4391914 /* RLMSyncSession.mm in Sources */, - E3A82EF1BFEB4A449FFE7FC26AEC1FB9 /* RLMSyncSessionRefreshHandle.mm in Sources */, - 5F9C606B3BD1513683DCD968D368AE9B /* RLMSyncSubscription.mm in Sources */, - AFDC58FF42E02745753EE6C5A502C3BB /* RLMSyncUser.mm in Sources */, - 049F23964BF99F1E034E600749DF4778 /* RLMSyncUtil.mm in Sources */, - 149DFEA17780F138C2D65F734477EC74 /* RLMThreadSafeReference.mm in Sources */, - 5B96D0F75CB99CD9B63EED98E14591BA /* RLMUpdateChecker.mm in Sources */, - 2B3B6A1F3CE5A236CF1B97B26E355E7D /* RLMUtil.mm in Sources */, - 1426E7D4526CCF2C32D559E2B538580B /* schema.cpp in Sources */, - 5861161136ED8784C63A95CF9EE918C8 /* shared_realm.cpp in Sources */, - 5AAD8DB30DDD23AEB92406F89174D7EF /* sync_config.cpp in Sources */, - 2CEAEFD70CD74376767EA7D85FA8831E /* sync_file.cpp in Sources */, - 70B0B87B78BFDEADABD02EC1425B7C0E /* sync_manager.cpp in Sources */, - 89C03071BA28C58414C5F9A4B8614B90 /* sync_metadata.cpp in Sources */, - 7D468FA6413DFA8873F8672B6CBF2468 /* sync_permission.cpp in Sources */, - 8DBB2BB97A17DCEAE003D2116E709489 /* sync_session.cpp in Sources */, - AA8CB96B506F6AF065AB1F8C9F9495CB /* sync_user.cpp in Sources */, - 0BFF24D5C16257D168CB59FEAE373808 /* system_configuration.cpp in Sources */, - 069E8403A49DE5921F142696F2518EBF /* thread_safe_reference.cpp in Sources */, - 13AA9F89B18BDC2687A40F18CB1CE6C8 /* transact_log_handler.cpp in Sources */, - 86C28A1FA2ADAF175EB56237CFD9FB36 /* uuid.cpp in Sources */, - 87B23A6C7190531AD4546209E6728EFA /* weak_realm_notifier.cpp in Sources */, - 0047B13AE63FA26AAA8DB8F11B430C02 /* work_queue.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 3010A8698DF99E86EE44ACAB0B1068CA /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 522243013D8403542D273D29C2062AE9 /* BackwardsCompatibility.swift in Sources */, - 686A82F039EDE84C9AC2711B56DDF860 /* DTTableViewDataSource.swift in Sources */, - 88C46C846B36D44D755C2C62B8BFD50A /* DTTableViewDelegate.swift in Sources */, - 5311190402B888CC56C42241BB124F7A /* DTTableViewDelegateWrapper.swift in Sources */, - 03EFB7066E10386B323F367BF3376713 /* DTTableViewDragDelegate.swift in Sources */, - E06FDB5F41A48F312BC053F63FB6FCFD /* DTTableViewDropDelegate.swift in Sources */, - 233EDDBD8F4DBB88B88936BF67D38C43 /* DTTableViewDropPlaceholderContext.swift in Sources */, - F370D8390B7AF207E60E2D1DE01F913D /* DTTableViewManager+DataSource.swift in Sources */, - 8D7A7EEEC4C2BD76CC49368163BEF17B /* DTTableViewManager+Delegate.swift in Sources */, - 4C9515430BF0E0C832C3DE8755A2CAF2 /* DTTableViewManager+Drag.swift in Sources */, - CD72CF57029AB4D1987E746D1C969B03 /* DTTableViewManager+Drop.swift in Sources */, - 5A03607F11B77EE686FEF0E50BE7F9FB /* DTTableViewManager+Registration.swift in Sources */, - C2F3CF174A85ECA0C7164F16CC6B00EC /* DTTableViewManager-dummy.m in Sources */, - 1B357C428FB0595C0C71A50B3065C522 /* DTTableViewManager.swift in Sources */, - 2663DC483B1BD5548693365C8F17F7F5 /* DTTableViewManagerAnomalyHandler.swift in Sources */, - 0DB86F0299A73422AD89CCF3CEC5BC5A /* TableViewConfiguration.swift in Sources */, - EE3322A4595447F7FC50F86C6E99BC1B /* TableViewFactory.swift in Sources */, - F389A49251DDCBB29CEAA1E8D567B385 /* TableViewUpdater.swift in Sources */, - B5DE9220D13AF658E71BF359A73D15E6 /* UIView+XibLoading.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 5A2AE47FA31C7306BE73BC410FB18B2A /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - F15174B61A15FA03A0C23B3BE0493169 /* AccumulationStrategy.swift in Sources */, - 06A9FC6B0E5EB29BFD63F96CB8DFFAE1 /* AnomalyHandler.swift in Sources */, - 5AEBFA2535D6E5B07A2E8AE5D7BBCF51 /* BaseStorage.swift in Sources */, - B4AC0F92C5EC63BD3AEBA713BE3F380E /* CoreDataStorage.swift in Sources */, - BDA4AA86FD634DB021EA0D5ABD701463 /* DTModelStorage-dummy.m in Sources */, - 2D1E4D34FC706A4C5430B6BCCA61F940 /* EventReactions.swift in Sources */, - FAC633B5F15EB82A7DEB6253A7D12218 /* MemoryStorage+UpdateWithoutAnimations.swift in Sources */, - 6B938D16C9BEE9AF42415C99D1F6DA52 /* MemoryStorage.swift in Sources */, - BB3DB1E3C5D3E73D974FBDEE16859798 /* ModelTransfer.swift in Sources */, - C4294B9B857B87FE82EAA022A5E5A833 /* ProxyDiffableDataSourceStorage.swift in Sources */, - 21F8ECB7A03D833A3932C2AAF943EA86 /* RuntimeHelper.swift in Sources */, - 04E5FEE26799A378F03CDE46F25C5F91 /* Section.swift in Sources */, - AD439220D07411D7CAFB3DEDC427B14E /* SectionModel.swift in Sources */, - 73E187F34F85D27E664867D8FAD02B15 /* SectionProtocols.swift in Sources */, - 23389E314CEF385E4A3C3F0904491D1A /* SingleSectionDiffing.swift in Sources */, - 6E9102E055262D2DEAD56E7D56364357 /* SingleSectionStorage.swift in Sources */, - 57382B29E1A24DE8F2EA76CFECA7F686 /* StorageProtocols.swift in Sources */, - A5F84ADB1D6B8B23FC3AC2ACE718E988 /* StorageUpdate.swift in Sources */, - D895603455ACE427358968E0E072B475 /* UINib+Existance.swift in Sources */, - C009AEA5BEBB2A205D84DC8073AA4CDF /* ViewModelMapping.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 89222AF845A30312C284F407BA48B98F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3BFC243AB9BD579969F0D5756560BCAA /* Constraint.swift in Sources */, - 2A1BBBC87AC2367BD14610A9D10D285E /* ConstraintAttributes.swift in Sources */, - 9B09968922C73D50040C6EEF57890D6E /* ConstraintConfig.swift in Sources */, - 5854DF509E8A016B6235793D04083035 /* ConstraintConstantTarget.swift in Sources */, - B599696DFEF6B2A5ECF528F4E5BB1846 /* ConstraintDescription.swift in Sources */, - AC35C9341C4BB156BB26FDD237EE3721 /* ConstraintDirectionalInsets.swift in Sources */, - 71DE9DC2FA583526AB4D1FD7F00C099C /* ConstraintDirectionalInsetTarget.swift in Sources */, - 8277256ADEC3C4DCF79957D1CA681A9A /* ConstraintDSL.swift in Sources */, - 21AB1101BBE4D28D74ED4EDF0D59025A /* ConstraintInsets.swift in Sources */, - 2C06F2E972444D359754D21AC46BFFE2 /* ConstraintInsetTarget.swift in Sources */, - 99B5296A5EDECE0557B9DA53D9E19CA1 /* ConstraintItem.swift in Sources */, - 1AFB1E9136716C0B61D6C700FF1E60FD /* ConstraintLayoutGuide+Extensions.swift in Sources */, - A270CD9EC3C541FE86E65AEDCEF500CF /* ConstraintLayoutGuide.swift in Sources */, - 77C9889055A3B32EA13A9616824DB0ED /* ConstraintLayoutGuideDSL.swift in Sources */, - 57B1876F2BE4168E5BFDB63D8CC849A0 /* ConstraintLayoutSupport.swift in Sources */, - 01C550A53C9E2047C83F8E85BBB558E6 /* ConstraintLayoutSupportDSL.swift in Sources */, - 51CD5887014967E77E58F5A163996454 /* ConstraintMaker.swift in Sources */, - 7C1702076F3A31D8D2D45A4A9F09B266 /* ConstraintMakerEditable.swift in Sources */, - 69CCBEEDFCA6D743D80026568D961919 /* ConstraintMakerExtendable.swift in Sources */, - C412F27D75AFC0DF0F0289DBB270931C /* ConstraintMakerFinalizable.swift in Sources */, - EE909C7C786140109051BC9562EEC7C8 /* ConstraintMakerPriortizable.swift in Sources */, - 75E146C12D1287228A0B493E87CDE31F /* ConstraintMakerRelatable.swift in Sources */, - D4697DC40F3B059E4A0867838CA1814E /* ConstraintMultiplierTarget.swift in Sources */, - 8705BBF0D428BF0AE1B554A377ECC540 /* ConstraintOffsetTarget.swift in Sources */, - 232B2F922E972D9F43D2EE15ACECE734 /* ConstraintPriority.swift in Sources */, - E8F2429683B3015CBD39CE883770BCA7 /* ConstraintPriorityTarget.swift in Sources */, - 69E3A06BBDFDC7D06A9D4BDC4E895E73 /* ConstraintRelatableTarget.swift in Sources */, - CE62FEABA57B2B53EABF8C7DCCC6B2C4 /* ConstraintRelation.swift in Sources */, - 3E5285F4F36EAD77ECABBFB7F36BB1BB /* ConstraintView+Extensions.swift in Sources */, - BECA67DFB5E0984DFAEFCB775C31972E /* ConstraintView.swift in Sources */, - EB1726F5E0D0EEBA20E4528B1E37A8FA /* ConstraintViewDSL.swift in Sources */, - B780B272106411CBE258BB60FFC45410 /* Debugging.swift in Sources */, - 039EAFE7935113805F3FC21BF1B7C9D5 /* LayoutConstraint.swift in Sources */, - E9A970BC24EA15832F248EA020072746 /* LayoutConstraintItem.swift in Sources */, - 4C7A676DAE95EEAC3787A75349F0862D /* SnapKit-dummy.m in Sources */, - 1956E392D500F3CD899D39A5F805736D /* Typealiases.swift in Sources */, - 6E0EB9E7FAAEDBB7A73ECF3095F69C4A /* UILayoutSupport+Extensions.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 0EF860BD8F33683695DAF4F820E0343A /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = DTModelStorage; - target = E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */; - targetProxy = A7ECE5DAC5D472D878AC0BAA34E66644 /* PBXContainerItemProxy */; - }; - 26B041B2BF86DF8FDE6B30D88F728275 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Realm; - target = 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */; - targetProxy = 1FB2B3D314BDFC56A97DEF307E89BED5 /* PBXContainerItemProxy */; - }; - 3E0AFFD599B51C8DC892A37730388036 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = DTTableViewManager; - target = 3EF3490B4B0DD7F07469ADEE907B9E59 /* DTTableViewManager */; - targetProxy = AE66927C5CF3921B56CA3228BCBDB87D /* PBXContainerItemProxy */; - }; - 904D619A8DD745E4591136B946231ACB /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = DTModelStorage; - target = E1F697AE01D68453B8B3B86DA9E42200 /* DTModelStorage */; - targetProxy = 38798EE4C9A9293F3745F976F22ADABC /* PBXContainerItemProxy */; - }; - B0F2CB59E7E3549DFC145C2E0973B40E /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Realm; - target = 68494F30B4A13F8E5E88BCCAEC25B0A4 /* Realm */; - targetProxy = 2241096BF52D154C2390A33A7C459082 /* PBXContainerItemProxy */; - }; - BDD84D5D0C58DE3C6ECEF80DB9DC63AE /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = SnapKit; - target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; - targetProxy = 3F2A2734043D65622E33BDE4027D227F /* PBXContainerItemProxy */; - }; - BF61B04164760CDA17C84A5FA6C6563B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = RealmSwift; - target = 782725687624F8665247B84AB581BEB1 /* RealmSwift */; - targetProxy = FAF4CD30CA4F48CABEE58034D8583ADF /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 020BEC27E3AD6D7C84D288C148A58E74 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 0589B80789798770DC6C2CA206518B07 /* SnapKit.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; - PRODUCT_MODULE_NAME = SnapKit; - PRODUCT_NAME = SnapKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 1DF6778AC92B102A69A49762CB7B33EB /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = C04E7F51401C97CBFFE90525078D9868 /* Pods-Lesson12.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson12/Pods-Lesson12-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson12/Pods-Lesson12.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 2E3C8A300772E0028147E4BAF0D5078A /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 0589B80789798770DC6C2CA206518B07 /* SnapKit.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; - PRODUCT_MODULE_NAME = SnapKit; - PRODUCT_NAME = SnapKit; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 3DE2C4A3A68C76D798374D77D7644459 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 62B9A4A867C31B9B15A7A69A95EC4876 /* RealmSwift.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/RealmSwift/RealmSwift-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/RealmSwift/RealmSwift-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/RealmSwift/RealmSwift.modulemap"; - PRODUCT_MODULE_NAME = RealmSwift; - PRODUCT_NAME = RealmSwift; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 467209F2B478496F5E53A5939039B29E /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 25705CA1710F89251D9929DCF3D1F08A /* Realm.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Realm/Realm-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Realm/Realm-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Realm/Realm.modulemap"; - PRODUCT_MODULE_NAME = Realm; - PRODUCT_NAME = Realm; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 48B776914F7AF8ADCB5D9F1499C6B6D1 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 4D1513A17CD9C965CEC10CB203F69CF2 /* DTModelStorage.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/DTModelStorage/DTModelStorage-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/DTModelStorage/DTModelStorage-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/DTModelStorage/DTModelStorage.modulemap"; - PRODUCT_MODULE_NAME = DTModelStorage; - PRODUCT_NAME = DTModelStorage; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 7095013B95D75BE17FD8027ECC325D00 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 4D1513A17CD9C965CEC10CB203F69CF2 /* DTModelStorage.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/DTModelStorage/DTModelStorage-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/DTModelStorage/DTModelStorage-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/DTModelStorage/DTModelStorage.modulemap"; - PRODUCT_MODULE_NAME = DTModelStorage; - PRODUCT_NAME = DTModelStorage; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 76B04784E199F9E057C51FBC85B40AF9 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 25705CA1710F89251D9929DCF3D1F08A /* Realm.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Realm/Realm-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Realm/Realm-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Realm/Realm.modulemap"; - PRODUCT_MODULE_NAME = Realm; - PRODUCT_NAME = Realm; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 90A064F05A5C97B99A57C8250AFEE047 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A35BEADF5432B761E8DF789A30215D2C /* DTTableViewManager.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/DTTableViewManager/DTTableViewManager.modulemap"; - PRODUCT_MODULE_NAME = DTTableViewManager; - PRODUCT_NAME = DTTableViewManager; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 939F1A8F6BCEB7F9F64D9EEE50CAE014 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - B092C331C85464B1D5C145E2A6C272E8 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A35BEADF5432B761E8DF789A30215D2C /* DTTableViewManager.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/DTTableViewManager/DTTableViewManager-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/DTTableViewManager/DTTableViewManager-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/DTTableViewManager/DTTableViewManager.modulemap"; - PRODUCT_MODULE_NAME = DTTableViewManager; - PRODUCT_NAME = DTTableViewManager; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - D59670DD4B2E8264DF6F0A92362AC2F3 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 60CB733150050B0A03D2C5FB83782840 /* Pods-Lesson12.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-Lesson12/Pods-Lesson12-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-Lesson12/Pods-Lesson12.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - ECB437504DF805BD96CAABF97400B526 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - F86F5AA5D94340F9BF0508955C1D75C5 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 62B9A4A867C31B9B15A7A69A95EC4876 /* RealmSwift.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/RealmSwift/RealmSwift-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/RealmSwift/RealmSwift-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/RealmSwift/RealmSwift.modulemap"; - PRODUCT_MODULE_NAME = RealmSwift; - PRODUCT_NAME = RealmSwift; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1A342D90638B02D992A14313597765C2 /* Build configuration list for PBXNativeTarget "DTTableViewManager" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 90A064F05A5C97B99A57C8250AFEE047 /* Debug */, - B092C331C85464B1D5C145E2A6C272E8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 22886CEE8A1196C43C2AD1112FC689C4 /* Build configuration list for PBXNativeTarget "RealmSwift" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3DE2C4A3A68C76D798374D77D7644459 /* Debug */, - F86F5AA5D94340F9BF0508955C1D75C5 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 939F1A8F6BCEB7F9F64D9EEE50CAE014 /* Debug */, - ECB437504DF805BD96CAABF97400B526 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 7F8CE4DC18DBEA01587212F09727DB3D /* Build configuration list for PBXNativeTarget "SnapKit" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 2E3C8A300772E0028147E4BAF0D5078A /* Debug */, - 020BEC27E3AD6D7C84D288C148A58E74 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - BA6271B202E8EC84ACB5775DDA67F32F /* Build configuration list for PBXNativeTarget "DTModelStorage" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 48B776914F7AF8ADCB5D9F1499C6B6D1 /* Debug */, - 7095013B95D75BE17FD8027ECC325D00 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C78C1F585AF9F23F8E5BE58C65DFB1B0 /* Build configuration list for PBXNativeTarget "Realm" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 76B04784E199F9E057C51FBC85B40AF9 /* Debug */, - 467209F2B478496F5E53A5939039B29E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - DBC3F2C104B3E116B2B4121D5AF43206 /* Build configuration list for PBXNativeTarget "Pods-Lesson12" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DF6778AC92B102A69A49762CB7B33EB /* Debug */, - D59670DD4B2E8264DF6F0A92362AC2F3 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/Lesson12/Pods/SnapKit/LICENSE b/Lesson12/Pods/SnapKit/LICENSE deleted file mode 100644 index a18ccfb..0000000 --- a/Lesson12/Pods/SnapKit/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Lesson12/Pods/SnapKit/README.md b/Lesson12/Pods/SnapKit/README.md deleted file mode 100644 index 0945ce6..0000000 --- a/Lesson12/Pods/SnapKit/README.md +++ /dev/null @@ -1,136 +0,0 @@ - - -SnapKit is a DSL to make Auto Layout easy on both iOS and OS X. - -[![Build Status](https://travis-ci.org/SnapKit/SnapKit.svg)](https://travis-ci.org/SnapKit/SnapKit) -[![Platform](https://img.shields.io/cocoapods/p/SnapKit.svg?style=flat)](https://github.com/SnapKit/SnapKit) -[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/SnapKit.svg)](https://cocoapods.org/pods/SnapKit) -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) - -#### ⚠️ **To use with Swift 4.x please ensure you are using >= 4.0.0** ⚠️ -#### ⚠️ **To use with Swift 5.x please ensure you are using >= 5.0.0** ⚠️ - -## Contents - -- [Requirements](#requirements) -- [Migration Guides](#migration-guides) -- [Communication](#communication) -- [Installation](#installation) -- [Usage](#usage) -- [Credits](#credits) -- [License](#license) - -## Requirements - -- iOS 10.0+ / Mac OS X 10.12+ / tvOS 10.0+ -- Xcode 10.0+ -- Swift 4.0+ - -## Communication - -- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/snapkit). (Tag 'snapkit') -- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/snapkit). -- If you **found a bug**, open an issue. -- If you **have a feature request**, open an issue. -- If you **want to contribute**, submit a pull request. - - -## Installation - -### CocoaPods - -[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 1.1.0+ is required to build SnapKit 4.0.0+. - -To integrate SnapKit into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '10.0' -use_frameworks! - -target '' do - pod 'SnapKit', '~> 5.0.0' -end -``` - -Then, run the following command: - -```bash -$ pod install -``` - -### Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](http://brew.sh/) using the following command: - -```bash -$ brew update -$ brew install carthage -``` - -To integrate SnapKit into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "SnapKit/SnapKit" ~> 5.0.0 -``` - -Run `carthage update` to build the framework and drag the built `SnapKit.framework` into your Xcode project. - -### Manually - -If you prefer not to use either of the aforementioned dependency managers, you can integrate SnapKit into your project manually. - ---- - -## Usage - -### Quick Start - -```swift -import SnapKit - -class MyViewController: UIViewController { - - lazy var box = UIView() - - override func viewDidLoad() { - super.viewDidLoad() - - self.view.addSubview(box) - box.snp.makeConstraints { (make) -> Void in - make.width.height.equalTo(50) - make.center.equalTo(self.view) - } - } - -} -``` - -### Playground -You can try SnapKit in Playground. - -**Note:** - -> To try SnapKit in playground, open `SnapKit.xcworkspace` and build SnapKit.framework for any simulator first. - -### Resources - -- [Documentation](http://snapkit.io/docs/) -- [F.A.Q.](http://snapkit.io/faq/) - -## Credits - -- Robert Payne ([@robertjpayne](https://twitter.com/robertjpayne)) -- Many other contributors - -## License - -SnapKit is released under the MIT license. See LICENSE for details. diff --git a/Lesson12/Pods/SnapKit/Source/Constraint.swift b/Lesson12/Pods/SnapKit/Source/Constraint.swift deleted file mode 100644 index 390629e..0000000 --- a/Lesson12/Pods/SnapKit/Source/Constraint.swift +++ /dev/null @@ -1,341 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - -public final class Constraint { - - internal let sourceLocation: (String, UInt) - internal let label: String? - - private let from: ConstraintItem - private let to: ConstraintItem - private let relation: ConstraintRelation - private let multiplier: ConstraintMultiplierTarget - private var constant: ConstraintConstantTarget { - didSet { - self.updateConstantAndPriorityIfNeeded() - } - } - private var priority: ConstraintPriorityTarget { - didSet { - self.updateConstantAndPriorityIfNeeded() - } - } - public var layoutConstraints: [LayoutConstraint] - - public var isActive: Bool { - set { - if newValue { - activate() - } - else { - deactivate() - } - } - - get { - for layoutConstraint in self.layoutConstraints { - if layoutConstraint.isActive { - return true - } - } - return false - } - } - - // MARK: Initialization - - internal init(from: ConstraintItem, - to: ConstraintItem, - relation: ConstraintRelation, - sourceLocation: (String, UInt), - label: String?, - multiplier: ConstraintMultiplierTarget, - constant: ConstraintConstantTarget, - priority: ConstraintPriorityTarget) { - self.from = from - self.to = to - self.relation = relation - self.sourceLocation = sourceLocation - self.label = label - self.multiplier = multiplier - self.constant = constant - self.priority = priority - self.layoutConstraints = [] - - // get attributes - let layoutFromAttributes = self.from.attributes.layoutAttributes - let layoutToAttributes = self.to.attributes.layoutAttributes - - // get layout from - let layoutFrom = self.from.layoutConstraintItem! - - // get relation - let layoutRelation = self.relation.layoutRelation - - for layoutFromAttribute in layoutFromAttributes { - // get layout to attribute - let layoutToAttribute: LayoutAttribute - #if os(iOS) || os(tvOS) - if layoutToAttributes.count > 0 { - if self.from.attributes == .edges && self.to.attributes == .margins { - switch layoutFromAttribute { - case .left: - layoutToAttribute = .leftMargin - case .right: - layoutToAttribute = .rightMargin - case .top: - layoutToAttribute = .topMargin - case .bottom: - layoutToAttribute = .bottomMargin - default: - fatalError() - } - } else if self.from.attributes == .margins && self.to.attributes == .edges { - switch layoutFromAttribute { - case .leftMargin: - layoutToAttribute = .left - case .rightMargin: - layoutToAttribute = .right - case .topMargin: - layoutToAttribute = .top - case .bottomMargin: - layoutToAttribute = .bottom - default: - fatalError() - } - } else if self.from.attributes == .directionalEdges && self.to.attributes == .directionalMargins { - switch layoutFromAttribute { - case .leading: - layoutToAttribute = .leadingMargin - case .trailing: - layoutToAttribute = .trailingMargin - case .top: - layoutToAttribute = .topMargin - case .bottom: - layoutToAttribute = .bottomMargin - default: - fatalError() - } - } else if self.from.attributes == .directionalMargins && self.to.attributes == .directionalEdges { - switch layoutFromAttribute { - case .leadingMargin: - layoutToAttribute = .leading - case .trailingMargin: - layoutToAttribute = .trailing - case .topMargin: - layoutToAttribute = .top - case .bottomMargin: - layoutToAttribute = .bottom - default: - fatalError() - } - } else if self.from.attributes == self.to.attributes { - layoutToAttribute = layoutFromAttribute - } else { - layoutToAttribute = layoutToAttributes[0] - } - } else { - if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { - layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top - } else { - layoutToAttribute = layoutFromAttribute - } - } - #else - if self.from.attributes == self.to.attributes { - layoutToAttribute = layoutFromAttribute - } else if layoutToAttributes.count > 0 { - layoutToAttribute = layoutToAttributes[0] - } else { - layoutToAttribute = layoutFromAttribute - } - #endif - - // get layout constant - let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) - - // get layout to - var layoutTo: AnyObject? = self.to.target - - // use superview if possible - if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { - layoutTo = layoutFrom.superview - } - - // create layout constraint - let layoutConstraint = LayoutConstraint( - item: layoutFrom, - attribute: layoutFromAttribute, - relatedBy: layoutRelation, - toItem: layoutTo, - attribute: layoutToAttribute, - multiplier: self.multiplier.constraintMultiplierTargetValue, - constant: layoutConstant - ) - - // set label - layoutConstraint.label = self.label - - // set priority - layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) - - // set constraint - layoutConstraint.constraint = self - - // append - self.layoutConstraints.append(layoutConstraint) - } - } - - // MARK: Public - - @available(*, deprecated, message:"Use activate().") - public func install() { - self.activate() - } - - @available(*, deprecated, message:"Use deactivate().") - public func uninstall() { - self.deactivate() - } - - public func activate() { - self.activateIfNeeded() - } - - public func deactivate() { - self.deactivateIfNeeded() - } - - @discardableResult - public func update(offset: ConstraintOffsetTarget) -> Constraint { - self.constant = offset.constraintOffsetTargetValue - return self - } - - @discardableResult - public func update(inset: ConstraintInsetTarget) -> Constraint { - self.constant = inset.constraintInsetTargetValue - return self - } - - #if os(iOS) || os(tvOS) - @discardableResult - @available(iOS 11.0, tvOS 11.0, *) - public func update(inset: ConstraintDirectionalInsetTarget) -> Constraint { - self.constant = inset.constraintDirectionalInsetTargetValue - return self - } - #endif - - @discardableResult - public func update(priority: ConstraintPriorityTarget) -> Constraint { - self.priority = priority.constraintPriorityTargetValue - return self - } - - @discardableResult - public func update(priority: ConstraintPriority) -> Constraint { - self.priority = priority.value - return self - } - - @available(*, deprecated, message:"Use update(offset: ConstraintOffsetTarget) instead.") - public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } - - @available(*, deprecated, message:"Use update(inset: ConstraintInsetTarget) instead.") - public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } - - @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") - public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } - - @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") - public func updatePriorityRequired() -> Void {} - - @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") - public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } - - @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") - public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } - - @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.") - public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } - - // MARK: Internal - - internal func updateConstantAndPriorityIfNeeded() { - for layoutConstraint in self.layoutConstraints { - let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute - layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) - - let requiredPriority = ConstraintPriority.required.value - if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { - layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) - } - } - } - - internal func activateIfNeeded(updatingExisting: Bool = false) { - guard let item = self.from.layoutConstraintItem else { - print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") - return - } - let layoutConstraints = self.layoutConstraints - - if updatingExisting { - var existingLayoutConstraints: [LayoutConstraint] = [] - for constraint in item.constraints { - existingLayoutConstraints += constraint.layoutConstraints - } - - for layoutConstraint in layoutConstraints { - let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } - guard let updateLayoutConstraint = existingLayoutConstraint else { - fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") - } - - let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute - updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) - } - } else { - NSLayoutConstraint.activate(layoutConstraints) - item.add(constraints: [self]) - } - } - - internal func deactivateIfNeeded() { - guard let item = self.from.layoutConstraintItem else { - print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") - return - } - let layoutConstraints = self.layoutConstraints - NSLayoutConstraint.deactivate(layoutConstraints) - item.remove(constraints: [self]) - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintAttributes.swift b/Lesson12/Pods/SnapKit/Source/ConstraintAttributes.swift deleted file mode 100644 index 2f0fbe9..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintAttributes.swift +++ /dev/null @@ -1,199 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -internal struct ConstraintAttributes : OptionSet, ExpressibleByIntegerLiteral { - - typealias IntegerLiteralType = UInt - - internal init(rawValue: UInt) { - self.rawValue = rawValue - } - internal init(_ rawValue: UInt) { - self.init(rawValue: rawValue) - } - internal init(nilLiteral: ()) { - self.rawValue = 0 - } - internal init(integerLiteral rawValue: IntegerLiteralType) { - self.init(rawValue: rawValue) - } - - internal private(set) var rawValue: UInt - internal static var allZeros: ConstraintAttributes { return 0 } - internal static func convertFromNilLiteral() -> ConstraintAttributes { return 0 } - internal var boolValue: Bool { return self.rawValue != 0 } - - internal func toRaw() -> UInt { return self.rawValue } - internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } - internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } - - // normal - - internal static var none: ConstraintAttributes { return 0 } - internal static var left: ConstraintAttributes { return 1 } - internal static var top: ConstraintAttributes { return 2 } - internal static var right: ConstraintAttributes { return 4 } - internal static var bottom: ConstraintAttributes { return 8 } - internal static var leading: ConstraintAttributes { return 16 } - internal static var trailing: ConstraintAttributes { return 32 } - internal static var width: ConstraintAttributes { return 64 } - internal static var height: ConstraintAttributes { return 128 } - internal static var centerX: ConstraintAttributes { return 256 } - internal static var centerY: ConstraintAttributes { return 512 } - internal static var lastBaseline: ConstraintAttributes { return 1024 } - - @available(iOS 8.0, OSX 10.11, *) - internal static var firstBaseline: ConstraintAttributes { return 2048 } - - @available(iOS 8.0, *) - internal static var leftMargin: ConstraintAttributes { return 4096 } - - @available(iOS 8.0, *) - internal static var rightMargin: ConstraintAttributes { return 8192 } - - @available(iOS 8.0, *) - internal static var topMargin: ConstraintAttributes { return 16384 } - - @available(iOS 8.0, *) - internal static var bottomMargin: ConstraintAttributes { return 32768 } - - @available(iOS 8.0, *) - internal static var leadingMargin: ConstraintAttributes { return 65536 } - - @available(iOS 8.0, *) - internal static var trailingMargin: ConstraintAttributes { return 131072 } - - @available(iOS 8.0, *) - internal static var centerXWithinMargins: ConstraintAttributes { return 262144 } - - @available(iOS 8.0, *) - internal static var centerYWithinMargins: ConstraintAttributes { return 524288 } - - // aggregates - - internal static var edges: ConstraintAttributes { return 15 } - internal static var directionalEdges: ConstraintAttributes { return 58 } - internal static var size: ConstraintAttributes { return 192 } - internal static var center: ConstraintAttributes { return 768 } - - @available(iOS 8.0, *) - internal static var margins: ConstraintAttributes { return 61440 } - - @available(iOS 8.0, *) - internal static var directionalMargins: ConstraintAttributes { return 245760 } - - @available(iOS 8.0, *) - internal static var centerWithinMargins: ConstraintAttributes { return 786432 } - - internal var layoutAttributes:[LayoutAttribute] { - var attrs = [LayoutAttribute]() - if (self.contains(ConstraintAttributes.left)) { - attrs.append(.left) - } - if (self.contains(ConstraintAttributes.top)) { - attrs.append(.top) - } - if (self.contains(ConstraintAttributes.right)) { - attrs.append(.right) - } - if (self.contains(ConstraintAttributes.bottom)) { - attrs.append(.bottom) - } - if (self.contains(ConstraintAttributes.leading)) { - attrs.append(.leading) - } - if (self.contains(ConstraintAttributes.trailing)) { - attrs.append(.trailing) - } - if (self.contains(ConstraintAttributes.width)) { - attrs.append(.width) - } - if (self.contains(ConstraintAttributes.height)) { - attrs.append(.height) - } - if (self.contains(ConstraintAttributes.centerX)) { - attrs.append(.centerX) - } - if (self.contains(ConstraintAttributes.centerY)) { - attrs.append(.centerY) - } - if (self.contains(ConstraintAttributes.lastBaseline)) { - attrs.append(.lastBaseline) - } - - #if os(iOS) || os(tvOS) - if (self.contains(ConstraintAttributes.firstBaseline)) { - attrs.append(.firstBaseline) - } - if (self.contains(ConstraintAttributes.leftMargin)) { - attrs.append(.leftMargin) - } - if (self.contains(ConstraintAttributes.rightMargin)) { - attrs.append(.rightMargin) - } - if (self.contains(ConstraintAttributes.topMargin)) { - attrs.append(.topMargin) - } - if (self.contains(ConstraintAttributes.bottomMargin)) { - attrs.append(.bottomMargin) - } - if (self.contains(ConstraintAttributes.leadingMargin)) { - attrs.append(.leadingMargin) - } - if (self.contains(ConstraintAttributes.trailingMargin)) { - attrs.append(.trailingMargin) - } - if (self.contains(ConstraintAttributes.centerXWithinMargins)) { - attrs.append(.centerXWithinMargins) - } - if (self.contains(ConstraintAttributes.centerYWithinMargins)) { - attrs.append(.centerYWithinMargins) - } - #endif - - return attrs - } -} - -internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { - return left.union(right) -} - -internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { - left.formUnion(right) -} - -internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { - left.subtract(right) -} - -internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { - return left.rawValue == right.rawValue -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintConfig.swift b/Lesson12/Pods/SnapKit/Source/ConstraintConfig.swift deleted file mode 100644 index 2746b7d..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintConfig.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit - public typealias ConstraintInterfaceLayoutDirection = UIUserInterfaceLayoutDirection -#else - import AppKit - public typealias ConstraintInterfaceLayoutDirection = NSUserInterfaceLayoutDirection -#endif - - -public struct ConstraintConfig { - - public static var interfaceLayoutDirection: ConstraintInterfaceLayoutDirection = .leftToRight - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintConstantTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintConstantTarget.swift deleted file mode 100644 index 7f54907..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintConstantTarget.swift +++ /dev/null @@ -1,213 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintConstantTarget { -} - -extension CGPoint: ConstraintConstantTarget { -} - -extension CGSize: ConstraintConstantTarget { -} - -extension ConstraintInsets: ConstraintConstantTarget { -} - -#if os(iOS) || os(tvOS) -@available(iOS 11.0, tvOS 11.0, *) -extension ConstraintDirectionalInsets: ConstraintConstantTarget { -} -#endif - -extension ConstraintConstantTarget { - - internal func constraintConstantTargetValueFor(layoutAttribute: LayoutAttribute) -> CGFloat { - if let value = self as? CGFloat { - return value - } - - if let value = self as? Float { - return CGFloat(value) - } - - if let value = self as? Double { - return CGFloat(value) - } - - if let value = self as? Int { - return CGFloat(value) - } - - if let value = self as? UInt { - return CGFloat(value) - } - - if let value = self as? CGSize { - if layoutAttribute == .width { - return value.width - } else if layoutAttribute == .height { - return value.height - } else { - return 0.0 - } - } - - if let value = self as? CGPoint { - #if os(iOS) || os(tvOS) - switch layoutAttribute { - case .left, .right, .leading, .trailing, .centerX, .leftMargin, .rightMargin, .leadingMargin, .trailingMargin, .centerXWithinMargins: - return value.x - case .top, .bottom, .centerY, .topMargin, .bottomMargin, .centerYWithinMargins, .lastBaseline, .firstBaseline: - return value.y - case .width, .height, .notAnAttribute: - return 0.0 - #if swift(>=5.0) - @unknown default: - return 0.0 - #endif - } - #else - switch layoutAttribute { - case .left, .right, .leading, .trailing, .centerX: - return value.x - case .top, .bottom, .centerY, .lastBaseline, .firstBaseline: - return value.y - case .width, .height, .notAnAttribute: - return 0.0 - #if swift(>=5.0) - @unknown default: - return 0.0 - #endif - } - #endif - } - - if let value = self as? ConstraintInsets { - #if os(iOS) || os(tvOS) - switch layoutAttribute { - case .left, .leftMargin: - return value.left - case .top, .topMargin, .firstBaseline: - return value.top - case .right, .rightMargin: - return -value.right - case .bottom, .bottomMargin, .lastBaseline: - return -value.bottom - case .leading, .leadingMargin: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right - case .trailing, .trailingMargin: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left - case .centerX, .centerXWithinMargins: - return (value.left - value.right) / 2 - case .centerY, .centerYWithinMargins: - return (value.top - value.bottom) / 2 - case .width: - return -(value.left + value.right) - case .height: - return -(value.top + value.bottom) - case .notAnAttribute: - return 0.0 - #if swift(>=5.0) - @unknown default: - return 0.0 - #endif - } - #else - switch layoutAttribute { - case .left: - return value.left - case .top, .firstBaseline: - return value.top - case .right: - return -value.right - case .bottom, .lastBaseline: - return -value.bottom - case .leading: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.left : value.right - case .trailing: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.right : -value.left - case .centerX: - return (value.left - value.right) / 2 - case .centerY: - return (value.top - value.bottom) / 2 - case .width: - return -(value.left + value.right) - case .height: - return -(value.top + value.bottom) - case .notAnAttribute: - return 0.0 - #if swift(>=5.0) - @unknown default: - return 0.0 - #endif - } - #endif - } - - #if os(iOS) || os(tvOS) - if #available(iOS 11.0, tvOS 11.0, *), let value = self as? ConstraintDirectionalInsets { - switch layoutAttribute { - case .left, .leftMargin: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? value.leading : value.trailing - case .top, .topMargin, .firstBaseline: - return value.top - case .right, .rightMargin: - return (ConstraintConfig.interfaceLayoutDirection == .leftToRight) ? -value.trailing : -value.leading - case .bottom, .bottomMargin, .lastBaseline: - return -value.bottom - case .leading, .leadingMargin: - return value.leading - case .trailing, .trailingMargin: - return -value.trailing - case .centerX, .centerXWithinMargins: - return (value.leading - value.trailing) / 2 - case .centerY, .centerYWithinMargins: - return (value.top - value.bottom) / 2 - case .width: - return -(value.leading + value.trailing) - case .height: - return -(value.top + value.bottom) - case .notAnAttribute: - return 0.0 - #if swift(>=5.0) - @unknown default: - return 0.0 - #else - default: - return 0.0 - #endif - } - } - #endif - - return 0.0 - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintDSL.swift b/Lesson12/Pods/SnapKit/Source/ConstraintDSL.swift deleted file mode 100644 index ecc5173..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintDSL.swift +++ /dev/null @@ -1,194 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintDSL { - - var target: AnyObject? { get } - - func setLabel(_ value: String?) - func label() -> String? - -} -extension ConstraintDSL { - - public func setLabel(_ value: String?) { - objc_setAssociatedObject(self.target as Any, &labelKey, value, .OBJC_ASSOCIATION_COPY_NONATOMIC) - } - public func label() -> String? { - return objc_getAssociatedObject(self.target as Any, &labelKey) as? String - } - -} -private var labelKey: UInt8 = 0 - - -public protocol ConstraintBasicAttributesDSL : ConstraintDSL { -} -extension ConstraintBasicAttributesDSL { - - // MARK: Basics - - public var left: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.left) - } - - public var top: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.top) - } - - public var right: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.right) - } - - public var bottom: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottom) - } - - public var leading: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leading) - } - - public var trailing: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.trailing) - } - - public var width: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.width) - } - - public var height: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.height) - } - - public var centerX: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerX) - } - - public var centerY: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerY) - } - - public var edges: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.edges) - } - - public var directionalEdges: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalEdges) - } - - public var size: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.size) - } - - public var center: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.center) - } - -} - -public protocol ConstraintAttributesDSL : ConstraintBasicAttributesDSL { -} -extension ConstraintAttributesDSL { - - // MARK: Baselines - - @available(*, deprecated, message:"Use .lastBaseline instead") - public var baseline: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.lastBaseline) - } - - @available(iOS 8.0, OSX 10.11, *) - public var lastBaseline: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.lastBaseline) - } - - @available(iOS 8.0, OSX 10.11, *) - public var firstBaseline: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.firstBaseline) - } - - // MARK: Margins - - @available(iOS 8.0, *) - public var leftMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leftMargin) - } - - @available(iOS 8.0, *) - public var topMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.topMargin) - } - - @available(iOS 8.0, *) - public var rightMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.rightMargin) - } - - @available(iOS 8.0, *) - public var bottomMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottomMargin) - } - - @available(iOS 8.0, *) - public var leadingMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.leadingMargin) - } - - @available(iOS 8.0, *) - public var trailingMargin: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.trailingMargin) - } - - @available(iOS 8.0, *) - public var centerXWithinMargins: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerXWithinMargins) - } - - @available(iOS 8.0, *) - public var centerYWithinMargins: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerYWithinMargins) - } - - @available(iOS 8.0, *) - public var margins: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.margins) - } - - @available(iOS 8.0, *) - public var directionalMargins: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.directionalMargins) - } - - @available(iOS 8.0, *) - public var centerWithinMargins: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.centerWithinMargins) - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintDescription.swift b/Lesson12/Pods/SnapKit/Source/ConstraintDescription.swift deleted file mode 100644 index 3521f9f..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintDescription.swift +++ /dev/null @@ -1,69 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintDescription { - - internal let item: LayoutConstraintItem - internal var attributes: ConstraintAttributes - internal var relation: ConstraintRelation? = nil - internal var sourceLocation: (String, UInt)? = nil - internal var label: String? = nil - internal var related: ConstraintItem? = nil - internal var multiplier: ConstraintMultiplierTarget = 1.0 - internal var constant: ConstraintConstantTarget = 0.0 - internal var priority: ConstraintPriorityTarget = 1000.0 - internal lazy var constraint: Constraint? = { - guard let relation = self.relation, - let related = self.related, - let sourceLocation = self.sourceLocation else { - return nil - } - let from = ConstraintItem(target: self.item, attributes: self.attributes) - - return Constraint( - from: from, - to: related, - relation: relation, - sourceLocation: sourceLocation, - label: self.label, - multiplier: self.multiplier, - constant: self.constant, - priority: self.priority - ) - }() - - // MARK: Initialization - - internal init(item: LayoutConstraintItem, attributes: ConstraintAttributes) { - self.item = item - self.attributes = attributes - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift deleted file mode 100644 index 955aec3..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsetTarget.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) -import UIKit -#else -import AppKit -#endif - -#if os(iOS) || os(tvOS) -public protocol ConstraintDirectionalInsetTarget: ConstraintConstantTarget { -} - -@available(iOS 11.0, tvOS 11.0, *) -extension ConstraintDirectionalInsets: ConstraintDirectionalInsetTarget { -} - -extension ConstraintDirectionalInsetTarget { - - @available(iOS 11.0, tvOS 11.0, *) - internal var constraintDirectionalInsetTargetValue: ConstraintDirectionalInsets { - if let amount = self as? ConstraintDirectionalInsets { - return amount - } else { - return ConstraintDirectionalInsets(top: 0, leading: 0, bottom: 0, trailing: 0) - } - } -} -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift b/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift deleted file mode 100644 index ada8ed5..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintDirectionalInsets.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -#if os(iOS) || os(tvOS) - @available(iOS 11.0, tvOS 11.0, *) - public typealias ConstraintDirectionalInsets = NSDirectionalEdgeInsets -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintInsetTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintInsetTarget.swift deleted file mode 100644 index ba8a0f3..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintInsetTarget.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintInsetTarget: ConstraintConstantTarget { -} - -extension Int: ConstraintInsetTarget { -} - -extension UInt: ConstraintInsetTarget { -} - -extension Float: ConstraintInsetTarget { -} - -extension Double: ConstraintInsetTarget { -} - -extension CGFloat: ConstraintInsetTarget { -} - -extension ConstraintInsets: ConstraintInsetTarget { -} - -extension ConstraintInsetTarget { - - internal var constraintInsetTargetValue: ConstraintInsets { - if let amount = self as? ConstraintInsets { - return amount - } else if let amount = self as? Float { - return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) - } else if let amount = self as? Double { - return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) - } else if let amount = self as? CGFloat { - return ConstraintInsets(top: amount, left: amount, bottom: amount, right: amount) - } else if let amount = self as? Int { - return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) - } else if let amount = self as? UInt { - return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount)) - } else { - return ConstraintInsets(top: 0, left: 0, bottom: 0, right: 0) - } - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintInsets.swift b/Lesson12/Pods/SnapKit/Source/ConstraintInsets.swift deleted file mode 100644 index 738ca05..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintInsets.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -#if os(iOS) || os(tvOS) - public typealias ConstraintInsets = UIEdgeInsets -#else - public typealias ConstraintInsets = NSEdgeInsets -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintItem.swift b/Lesson12/Pods/SnapKit/Source/ConstraintItem.swift deleted file mode 100644 index a342c1d..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintItem.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public final class ConstraintItem { - - internal weak var target: AnyObject? - internal let attributes: ConstraintAttributes - - internal init(target: AnyObject?, attributes: ConstraintAttributes) { - self.target = target - self.attributes = attributes - } - - internal var layoutConstraintItem: LayoutConstraintItem? { - return self.target as? LayoutConstraintItem - } - -} - -public func ==(lhs: ConstraintItem, rhs: ConstraintItem) -> Bool { - // pointer equality - guard lhs !== rhs else { - return true - } - - // must both have valid targets and identical attributes - guard let target1 = lhs.target, - let target2 = rhs.target, - target1 === target2 && lhs.attributes == rhs.attributes else { - return false - } - - return true -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift b/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift deleted file mode 100644 index d429e0c..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide+Extensions.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#endif - - -@available(iOS 9.0, OSX 10.11, *) -public extension ConstraintLayoutGuide { - - var snp: ConstraintLayoutGuideDSL { - return ConstraintLayoutGuideDSL(guide: self) - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide.swift b/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide.swift deleted file mode 100644 index e3e50c8..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuide.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -#if os(iOS) || os(tvOS) - @available(iOS 9.0, *) - public typealias ConstraintLayoutGuide = UILayoutGuide -#else - @available(OSX 10.11, *) - public typealias ConstraintLayoutGuide = NSLayoutGuide -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift b/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift deleted file mode 100644 index 0007819..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutGuideDSL.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -@available(iOS 9.0, OSX 10.11, *) -public struct ConstraintLayoutGuideDSL: ConstraintAttributesDSL { - - @discardableResult - public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - return ConstraintMaker.prepareConstraints(item: self.guide, closure: closure) - } - - public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.makeConstraints(item: self.guide, closure: closure) - } - - public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.remakeConstraints(item: self.guide, closure: closure) - } - - public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.updateConstraints(item: self.guide, closure: closure) - } - - public func removeConstraints() { - ConstraintMaker.removeConstraints(item: self.guide) - } - - public var target: AnyObject? { - return self.guide - } - - internal let guide: ConstraintLayoutGuide - - internal init(guide: ConstraintLayoutGuide) { - self.guide = guide - - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupport.swift b/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupport.swift deleted file mode 100644 index e92e9fb..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupport.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -#if os(iOS) || os(tvOS) - @available(iOS 8.0, *) - public typealias ConstraintLayoutSupport = UILayoutSupport -#else - public class ConstraintLayoutSupport {} -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift b/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift deleted file mode 100644 index 5d6ae89..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintLayoutSupportDSL.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -@available(iOS 8.0, *) -public struct ConstraintLayoutSupportDSL: ConstraintDSL { - - public var target: AnyObject? { - return self.support - } - - internal let support: ConstraintLayoutSupport - - internal init(support: ConstraintLayoutSupport) { - self.support = support - - } - - public var top: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.top) - } - - public var bottom: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.bottom) - } - - public var height: ConstraintItem { - return ConstraintItem(target: self.target, attributes: ConstraintAttributes.height) - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMaker.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMaker.swift deleted file mode 100644 index 38f4d31..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMaker.swift +++ /dev/null @@ -1,212 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - -public class ConstraintMaker { - - public var left: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.left) - } - - public var top: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.top) - } - - public var bottom: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.bottom) - } - - public var right: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.right) - } - - public var leading: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.leading) - } - - public var trailing: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.trailing) - } - - public var width: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.width) - } - - public var height: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.height) - } - - public var centerX: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.centerX) - } - - public var centerY: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.centerY) - } - - @available(*, deprecated, message:"Use lastBaseline instead") - public var baseline: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.lastBaseline) - } - - public var lastBaseline: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.lastBaseline) - } - - @available(iOS 8.0, OSX 10.11, *) - public var firstBaseline: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.firstBaseline) - } - - @available(iOS 8.0, *) - public var leftMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.leftMargin) - } - - @available(iOS 8.0, *) - public var rightMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.rightMargin) - } - - @available(iOS 8.0, *) - public var topMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.topMargin) - } - - @available(iOS 8.0, *) - public var bottomMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.bottomMargin) - } - - @available(iOS 8.0, *) - public var leadingMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.leadingMargin) - } - - @available(iOS 8.0, *) - public var trailingMargin: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.trailingMargin) - } - - @available(iOS 8.0, *) - public var centerXWithinMargins: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.centerXWithinMargins) - } - - @available(iOS 8.0, *) - public var centerYWithinMargins: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.centerYWithinMargins) - } - - public var edges: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.edges) - } - public var directionalEdges: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.directionalEdges) - } - public var size: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.size) - } - public var center: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.center) - } - - @available(iOS 8.0, *) - public var margins: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.margins) - } - - @available(iOS 8.0, *) - public var directionalMargins: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.directionalMargins) - } - - @available(iOS 8.0, *) - public var centerWithinMargins: ConstraintMakerExtendable { - return self.makeExtendableWithAttributes(.centerWithinMargins) - } - - private let item: LayoutConstraintItem - private var descriptions = [ConstraintDescription]() - - internal init(item: LayoutConstraintItem) { - self.item = item - self.item.prepare() - } - - internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable { - let description = ConstraintDescription(item: self.item, attributes: attributes) - self.descriptions.append(description) - return ConstraintMakerExtendable(description) - } - - internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - let maker = ConstraintMaker(item: item) - closure(maker) - var constraints: [Constraint] = [] - for description in maker.descriptions { - guard let constraint = description.constraint else { - continue - } - constraints.append(constraint) - } - return constraints - } - - internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { - let constraints = prepareConstraints(item: item, closure: closure) - for constraint in constraints { - constraint.activateIfNeeded(updatingExisting: false) - } - } - - internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { - self.removeConstraints(item: item) - self.makeConstraints(item: item, closure: closure) - } - - internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { - guard item.constraints.count > 0 else { - self.makeConstraints(item: item, closure: closure) - return - } - - let constraints = prepareConstraints(item: item, closure: closure) - for constraint in constraints { - constraint.activateIfNeeded(updatingExisting: true) - } - } - - internal static func removeConstraints(item: LayoutConstraintItem) { - let constraints = item.constraints - for constraint in constraints { - constraint.deactivateIfNeeded() - } - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMakerEditable.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMakerEditable.swift deleted file mode 100644 index f768a17..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMakerEditable.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintMakerEditable: ConstraintMakerPriortizable { - - @discardableResult - public func multipliedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable { - self.description.multiplier = amount - return self - } - - @discardableResult - public func dividedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable { - return self.multipliedBy(1.0 / amount.constraintMultiplierTargetValue) - } - - @discardableResult - public func offset(_ amount: ConstraintOffsetTarget) -> ConstraintMakerEditable { - self.description.constant = amount.constraintOffsetTargetValue - return self - } - - @discardableResult - public func inset(_ amount: ConstraintInsetTarget) -> ConstraintMakerEditable { - self.description.constant = amount.constraintInsetTargetValue - return self - } - - #if os(iOS) || os(tvOS) - @discardableResult - @available(iOS 11.0, tvOS 11.0, *) - public func inset(_ amount: ConstraintDirectionalInsetTarget) -> ConstraintMakerEditable { - self.description.constant = amount.constraintDirectionalInsetTargetValue - return self - } - #endif -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMakerExtendable.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMakerExtendable.swift deleted file mode 100644 index ce47169..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMakerExtendable.swift +++ /dev/null @@ -1,179 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintMakerExtendable: ConstraintMakerRelatable { - - public var left: ConstraintMakerExtendable { - self.description.attributes += .left - return self - } - - public var top: ConstraintMakerExtendable { - self.description.attributes += .top - return self - } - - public var bottom: ConstraintMakerExtendable { - self.description.attributes += .bottom - return self - } - - public var right: ConstraintMakerExtendable { - self.description.attributes += .right - return self - } - - public var leading: ConstraintMakerExtendable { - self.description.attributes += .leading - return self - } - - public var trailing: ConstraintMakerExtendable { - self.description.attributes += .trailing - return self - } - - public var width: ConstraintMakerExtendable { - self.description.attributes += .width - return self - } - - public var height: ConstraintMakerExtendable { - self.description.attributes += .height - return self - } - - public var centerX: ConstraintMakerExtendable { - self.description.attributes += .centerX - return self - } - - public var centerY: ConstraintMakerExtendable { - self.description.attributes += .centerY - return self - } - - @available(*, deprecated, message:"Use lastBaseline instead") - public var baseline: ConstraintMakerExtendable { - self.description.attributes += .lastBaseline - return self - } - - public var lastBaseline: ConstraintMakerExtendable { - self.description.attributes += .lastBaseline - return self - } - - @available(iOS 8.0, OSX 10.11, *) - public var firstBaseline: ConstraintMakerExtendable { - self.description.attributes += .firstBaseline - return self - } - - @available(iOS 8.0, *) - public var leftMargin: ConstraintMakerExtendable { - self.description.attributes += .leftMargin - return self - } - - @available(iOS 8.0, *) - public var rightMargin: ConstraintMakerExtendable { - self.description.attributes += .rightMargin - return self - } - - @available(iOS 8.0, *) - public var topMargin: ConstraintMakerExtendable { - self.description.attributes += .topMargin - return self - } - - @available(iOS 8.0, *) - public var bottomMargin: ConstraintMakerExtendable { - self.description.attributes += .bottomMargin - return self - } - - @available(iOS 8.0, *) - public var leadingMargin: ConstraintMakerExtendable { - self.description.attributes += .leadingMargin - return self - } - - @available(iOS 8.0, *) - public var trailingMargin: ConstraintMakerExtendable { - self.description.attributes += .trailingMargin - return self - } - - @available(iOS 8.0, *) - public var centerXWithinMargins: ConstraintMakerExtendable { - self.description.attributes += .centerXWithinMargins - return self - } - - @available(iOS 8.0, *) - public var centerYWithinMargins: ConstraintMakerExtendable { - self.description.attributes += .centerYWithinMargins - return self - } - - public var edges: ConstraintMakerExtendable { - self.description.attributes += .edges - return self - } - public var directionalEdges: ConstraintMakerExtendable { - self.description.attributes += .directionalEdges - return self - } - public var size: ConstraintMakerExtendable { - self.description.attributes += .size - return self - } - - @available(iOS 8.0, *) - public var margins: ConstraintMakerExtendable { - self.description.attributes += .margins - return self - } - - @available(iOS 8.0, *) - public var directionalMargins: ConstraintMakerExtendable { - self.description.attributes += .directionalMargins - return self - } - - @available(iOS 8.0, *) - public var centerWithinMargins: ConstraintMakerExtendable { - self.description.attributes += .centerWithinMargins - return self - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift deleted file mode 100644 index 4e1379e..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMakerFinalizable.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintMakerFinalizable { - - internal let description: ConstraintDescription - - internal init(_ description: ConstraintDescription) { - self.description = description - } - - @discardableResult - public func labeled(_ label: String) -> ConstraintMakerFinalizable { - self.description.label = label - return self - } - - public var constraint: Constraint { - return self.description.constraint! - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift deleted file mode 100644 index e0d452d..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMakerPriortizable.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintMakerPriortizable: ConstraintMakerFinalizable { - - @discardableResult - public func priority(_ amount: ConstraintPriority) -> ConstraintMakerFinalizable { - self.description.priority = amount.value - return self - } - - @discardableResult - public func priority(_ amount: ConstraintPriorityTarget) -> ConstraintMakerFinalizable { - self.description.priority = amount - return self - } - - @available(*, deprecated, message:"Use priority(.required) instead.") - @discardableResult - public func priorityRequired() -> ConstraintMakerFinalizable { - return self.priority(.required) - } - - @available(*, deprecated, message:"Use priority(.high) instead.") - @discardableResult - public func priorityHigh() -> ConstraintMakerFinalizable { - return self.priority(.high) - } - - @available(*, deprecated, message:"Use priority(.medium) instead.") - @discardableResult - public func priorityMedium() -> ConstraintMakerFinalizable { - return self.priority(.medium) - } - - @available(*, deprecated, message:"Use priority(.low) instead.") - @discardableResult - public func priorityLow() -> ConstraintMakerFinalizable { - return self.priority(.low) - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMakerRelatable.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMakerRelatable.swift deleted file mode 100644 index 7889532..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMakerRelatable.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class ConstraintMakerRelatable { - - internal let description: ConstraintDescription - - internal init(_ description: ConstraintDescription) { - self.description = description - } - - internal func relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable { - let related: ConstraintItem - let constant: ConstraintConstantTarget - - if let other = other as? ConstraintItem { - guard other.attributes == ConstraintAttributes.none || - other.attributes.layoutAttributes.count <= 1 || - other.attributes.layoutAttributes == self.description.attributes.layoutAttributes || - other.attributes == .edges && self.description.attributes == .margins || - other.attributes == .margins && self.description.attributes == .edges || - other.attributes == .directionalEdges && self.description.attributes == .directionalMargins || - other.attributes == .directionalMargins && self.description.attributes == .directionalEdges else { - fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))"); - } - - related = other - constant = 0.0 - } else if let other = other as? ConstraintView { - related = ConstraintItem(target: other, attributes: ConstraintAttributes.none) - constant = 0.0 - } else if let other = other as? ConstraintConstantTarget { - related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none) - constant = other - } else if #available(iOS 9.0, OSX 10.11, *), let other = other as? ConstraintLayoutGuide { - related = ConstraintItem(target: other, attributes: ConstraintAttributes.none) - constant = 0.0 - } else { - fatalError("Invalid constraint. (\(file), \(line))") - } - - let editable = ConstraintMakerEditable(self.description) - editable.description.sourceLocation = (file, line) - editable.description.relation = relation - editable.description.related = related - editable.description.constant = constant - return editable - } - - @discardableResult - public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - return self.relatedTo(other, relation: .equal, file: file, line: line) - } - - @discardableResult - public func equalToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.item.superview else { - fatalError("Expected superview but found nil when attempting make constraint `equalToSuperview`.") - } - return self.relatedTo(other, relation: .equal, file: file, line: line) - } - - @discardableResult - public func lessThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line) - } - - @discardableResult - public func lessThanOrEqualToSuperview(_ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.item.superview else { - fatalError("Expected superview but found nil when attempting make constraint `lessThanOrEqualToSuperview`.") - } - return self.relatedTo(other, relation: .lessThanOrEqual, file: file, line: line) - } - - @discardableResult - public func greaterThanOrEqualTo(_ other: ConstraintRelatableTarget, _ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { - return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line) - } - - @discardableResult - public func greaterThanOrEqualToSuperview(_ file: String = #file, line: UInt = #line) -> ConstraintMakerEditable { - guard let other = self.description.item.superview else { - fatalError("Expected superview but found nil when attempting make constraint `greaterThanOrEqualToSuperview`.") - } - return self.relatedTo(other, relation: .greaterThanOrEqual, file: file, line: line) - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift deleted file mode 100644 index 6fecd33..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintMultiplierTarget.swift +++ /dev/null @@ -1,75 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintMultiplierTarget { - - var constraintMultiplierTargetValue: CGFloat { get } - -} - -extension Int: ConstraintMultiplierTarget { - - public var constraintMultiplierTargetValue: CGFloat { - return CGFloat(self) - } - -} - -extension UInt: ConstraintMultiplierTarget { - - public var constraintMultiplierTargetValue: CGFloat { - return CGFloat(self) - } - -} - -extension Float: ConstraintMultiplierTarget { - - public var constraintMultiplierTargetValue: CGFloat { - return CGFloat(self) - } - -} - -extension Double: ConstraintMultiplierTarget { - - public var constraintMultiplierTargetValue: CGFloat { - return CGFloat(self) - } - -} - -extension CGFloat: ConstraintMultiplierTarget { - - public var constraintMultiplierTargetValue: CGFloat { - return self - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintOffsetTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintOffsetTarget.swift deleted file mode 100644 index bd9e0a1..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintOffsetTarget.swift +++ /dev/null @@ -1,69 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintOffsetTarget: ConstraintConstantTarget { -} - -extension Int: ConstraintOffsetTarget { -} - -extension UInt: ConstraintOffsetTarget { -} - -extension Float: ConstraintOffsetTarget { -} - -extension Double: ConstraintOffsetTarget { -} - -extension CGFloat: ConstraintOffsetTarget { -} - -extension ConstraintOffsetTarget { - - internal var constraintOffsetTargetValue: CGFloat { - let offset: CGFloat - if let amount = self as? Float { - offset = CGFloat(amount) - } else if let amount = self as? Double { - offset = CGFloat(amount) - } else if let amount = self as? CGFloat { - offset = CGFloat(amount) - } else if let amount = self as? Int { - offset = CGFloat(amount) - } else if let amount = self as? UInt { - offset = CGFloat(amount) - } else { - offset = 0.0 - } - return offset - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintPriority.swift b/Lesson12/Pods/SnapKit/Source/ConstraintPriority.swift deleted file mode 100644 index f9dab16..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintPriority.swift +++ /dev/null @@ -1,77 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - -public struct ConstraintPriority : ExpressibleByFloatLiteral, Equatable, Strideable { - public typealias FloatLiteralType = Float - - public let value: Float - - public init(floatLiteral value: Float) { - self.value = value - } - - public init(_ value: Float) { - self.value = value - } - - public static var required: ConstraintPriority { - return 1000.0 - } - - public static var high: ConstraintPriority { - return 750.0 - } - - public static var medium: ConstraintPriority { - #if os(OSX) - return 501.0 - #else - return 500.0 - #endif - - } - - public static var low: ConstraintPriority { - return 250.0 - } - - public static func ==(lhs: ConstraintPriority, rhs: ConstraintPriority) -> Bool { - return lhs.value == rhs.value - } - - // MARK: Strideable - - public func advanced(by n: FloatLiteralType) -> ConstraintPriority { - return ConstraintPriority(floatLiteral: value + n) - } - - public func distance(to other: ConstraintPriority) -> FloatLiteralType { - return other.value - value - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintPriorityTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintPriorityTarget.swift deleted file mode 100644 index 064f750..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintPriorityTarget.swift +++ /dev/null @@ -1,85 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintPriorityTarget { - - var constraintPriorityTargetValue: Float { get } - -} - -extension Int: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return Float(self) - } - -} - -extension UInt: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return Float(self) - } - -} - -extension Float: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return self - } - -} - -extension Double: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return Float(self) - } - -} - -extension CGFloat: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return Float(self) - } - -} - -#if os(iOS) || os(tvOS) -extension UILayoutPriority: ConstraintPriorityTarget { - - public var constraintPriorityTargetValue: Float { - return self.rawValue - } - -} -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintRelatableTarget.swift b/Lesson12/Pods/SnapKit/Source/ConstraintRelatableTarget.swift deleted file mode 100644 index d517a61..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintRelatableTarget.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol ConstraintRelatableTarget { -} - -extension Int: ConstraintRelatableTarget { -} - -extension UInt: ConstraintRelatableTarget { -} - -extension Float: ConstraintRelatableTarget { -} - -extension Double: ConstraintRelatableTarget { -} - -extension CGFloat: ConstraintRelatableTarget { -} - -extension CGSize: ConstraintRelatableTarget { -} - -extension CGPoint: ConstraintRelatableTarget { -} - -extension ConstraintInsets: ConstraintRelatableTarget { -} - -#if os(iOS) || os(tvOS) -@available(iOS 11.0, tvOS 11.0, *) -extension ConstraintDirectionalInsets: ConstraintRelatableTarget { -} -#endif - -extension ConstraintItem: ConstraintRelatableTarget { -} - -extension ConstraintView: ConstraintRelatableTarget { -} - -@available(iOS 9.0, OSX 10.11, *) -extension ConstraintLayoutGuide: ConstraintRelatableTarget { -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintRelation.swift b/Lesson12/Pods/SnapKit/Source/ConstraintRelation.swift deleted file mode 100644 index 446aaf7..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintRelation.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -internal enum ConstraintRelation : Int { - case equal = 1 - case lessThanOrEqual - case greaterThanOrEqual - - internal var layoutRelation: LayoutRelation { - get { - switch(self) { - case .equal: - return .equal - case .lessThanOrEqual: - return .lessThanOrEqual - case .greaterThanOrEqual: - return .greaterThanOrEqual - } - } - } -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintView+Extensions.swift b/Lesson12/Pods/SnapKit/Source/ConstraintView+Extensions.swift deleted file mode 100644 index a4898dc..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintView+Extensions.swift +++ /dev/null @@ -1,152 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public extension ConstraintView { - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_left: ConstraintItem { return self.snp.left } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_top: ConstraintItem { return self.snp.top } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_right: ConstraintItem { return self.snp.right } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_bottom: ConstraintItem { return self.snp.bottom } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_leading: ConstraintItem { return self.snp.leading } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_trailing: ConstraintItem { return self.snp.trailing } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_width: ConstraintItem { return self.snp.width } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_height: ConstraintItem { return self.snp.height } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_centerX: ConstraintItem { return self.snp.centerX } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_centerY: ConstraintItem { return self.snp.centerY } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_baseline: ConstraintItem { return self.snp.baseline } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, OSX 10.11, *) - var snp_lastBaseline: ConstraintItem { return self.snp.lastBaseline } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, OSX 10.11, *) - var snp_firstBaseline: ConstraintItem { return self.snp.firstBaseline } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_leftMargin: ConstraintItem { return self.snp.leftMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_topMargin: ConstraintItem { return self.snp.topMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_rightMargin: ConstraintItem { return self.snp.rightMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_bottomMargin: ConstraintItem { return self.snp.bottomMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_leadingMargin: ConstraintItem { return self.snp.leadingMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_trailingMargin: ConstraintItem { return self.snp.trailingMargin } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_centerXWithinMargins: ConstraintItem { return self.snp.centerXWithinMargins } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_centerYWithinMargins: ConstraintItem { return self.snp.centerYWithinMargins } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_edges: ConstraintItem { return self.snp.edges } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_size: ConstraintItem { return self.snp.size } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - var snp_center: ConstraintItem { return self.snp.center } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_margins: ConstraintItem { return self.snp.margins } - - @available(iOS, deprecated, message:"Use newer snp.* syntax.") - @available(iOS 8.0, *) - var snp_centerWithinMargins: ConstraintItem { return self.snp.centerWithinMargins } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - func snp_prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - return self.snp.prepareConstraints(closure) - } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - func snp_makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - self.snp.makeConstraints(closure) - } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - func snp_remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - self.snp.remakeConstraints(closure) - } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - func snp_updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - self.snp.updateConstraints(closure) - } - - @available(*, deprecated, message:"Use newer snp.* syntax.") - func snp_removeConstraints() { - self.snp.removeConstraints() - } - - var snp: ConstraintViewDSL { - return ConstraintViewDSL(view: self) - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintView.swift b/Lesson12/Pods/SnapKit/Source/ConstraintView.swift deleted file mode 100644 index 6ff8a76..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintView.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -#if os(iOS) || os(tvOS) - public typealias ConstraintView = UIView -#else - public typealias ConstraintView = NSView -#endif diff --git a/Lesson12/Pods/SnapKit/Source/ConstraintViewDSL.swift b/Lesson12/Pods/SnapKit/Source/ConstraintViewDSL.swift deleted file mode 100644 index a0187f9..0000000 --- a/Lesson12/Pods/SnapKit/Source/ConstraintViewDSL.swift +++ /dev/null @@ -1,101 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public struct ConstraintViewDSL: ConstraintAttributesDSL { - - @discardableResult - public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { - return ConstraintMaker.prepareConstraints(item: self.view, closure: closure) - } - - public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.makeConstraints(item: self.view, closure: closure) - } - - public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.remakeConstraints(item: self.view, closure: closure) - } - - public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { - ConstraintMaker.updateConstraints(item: self.view, closure: closure) - } - - public func removeConstraints() { - ConstraintMaker.removeConstraints(item: self.view) - } - - public var contentHuggingHorizontalPriority: Float { - get { - return self.view.contentHuggingPriority(for: .horizontal).rawValue - } - nonmutating set { - self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .horizontal) - } - } - - public var contentHuggingVerticalPriority: Float { - get { - return self.view.contentHuggingPriority(for: .vertical).rawValue - } - nonmutating set { - self.view.setContentHuggingPriority(LayoutPriority(rawValue: newValue), for: .vertical) - } - } - - public var contentCompressionResistanceHorizontalPriority: Float { - get { - return self.view.contentCompressionResistancePriority(for: .horizontal).rawValue - } - nonmutating set { - self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .horizontal) - } - } - - public var contentCompressionResistanceVerticalPriority: Float { - get { - return self.view.contentCompressionResistancePriority(for: .vertical).rawValue - } - nonmutating set { - self.view.setContentCompressionResistancePriority(LayoutPriority(rawValue: newValue), for: .vertical) - } - } - - public var target: AnyObject? { - return self.view - } - - internal let view: ConstraintView - - internal init(view: ConstraintView) { - self.view = view - - } - -} diff --git a/Lesson12/Pods/SnapKit/Source/Debugging.swift b/Lesson12/Pods/SnapKit/Source/Debugging.swift deleted file mode 100644 index a78579a..0000000 --- a/Lesson12/Pods/SnapKit/Source/Debugging.swift +++ /dev/null @@ -1,169 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - -public extension LayoutConstraint { - - override var description: String { - var description = "<" - - description += descriptionForObject(self) - - if let firstItem = conditionalOptional(from: self.firstItem) { - description += " \(descriptionForObject(firstItem))" - } - - if self.firstAttribute != .notAnAttribute { - description += ".\(descriptionForAttribute(self.firstAttribute))" - } - - description += " \(descriptionForRelation(self.relation))" - - if let secondItem = self.secondItem { - description += " \(descriptionForObject(secondItem))" - } - - if self.secondAttribute != .notAnAttribute { - description += ".\(descriptionForAttribute(self.secondAttribute))" - } - - if self.multiplier != 1.0 { - description += " * \(self.multiplier)" - } - - if self.secondAttribute == .notAnAttribute { - description += " \(self.constant)" - } else { - if self.constant > 0.0 { - description += " + \(self.constant)" - } else if self.constant < 0.0 { - description += " - \(abs(self.constant))" - } - } - - if self.priority.rawValue != 1000.0 { - description += " ^\(self.priority)" - } - - description += ">" - - return description - } - -} - -private func descriptionForRelation(_ relation: LayoutRelation) -> String { - switch relation { - case .equal: return "==" - case .greaterThanOrEqual: return ">=" - case .lessThanOrEqual: return "<=" - #if swift(>=5.0) - @unknown default: return "unknown" - #endif - } -} - -private func descriptionForAttribute(_ attribute: LayoutAttribute) -> String { - #if os(iOS) || os(tvOS) - switch attribute { - case .notAnAttribute: return "notAnAttribute" - case .top: return "top" - case .left: return "left" - case .bottom: return "bottom" - case .right: return "right" - case .leading: return "leading" - case .trailing: return "trailing" - case .width: return "width" - case .height: return "height" - case .centerX: return "centerX" - case .centerY: return "centerY" - case .lastBaseline: return "lastBaseline" - case .firstBaseline: return "firstBaseline" - case .topMargin: return "topMargin" - case .leftMargin: return "leftMargin" - case .bottomMargin: return "bottomMargin" - case .rightMargin: return "rightMargin" - case .leadingMargin: return "leadingMargin" - case .trailingMargin: return "trailingMargin" - case .centerXWithinMargins: return "centerXWithinMargins" - case .centerYWithinMargins: return "centerYWithinMargins" - #if swift(>=5.0) - @unknown default: return "unknown" - #endif - } - #else - switch attribute { - case .notAnAttribute: return "notAnAttribute" - case .top: return "top" - case .left: return "left" - case .bottom: return "bottom" - case .right: return "right" - case .leading: return "leading" - case .trailing: return "trailing" - case .width: return "width" - case .height: return "height" - case .centerX: return "centerX" - case .centerY: return "centerY" - case .lastBaseline: return "lastBaseline" - case .firstBaseline: return "firstBaseline" - #if swift(>=5.0) - @unknown default: return "unknown" - #endif - } - #endif -} - -private func conditionalOptional(from object: Optional) -> Optional { - return object -} - -private func conditionalOptional(from object: T) -> Optional { - return Optional.some(object) -} - -private func descriptionForObject(_ object: AnyObject) -> String { - let pointerDescription = String(format: "%p", UInt(bitPattern: ObjectIdentifier(object))) - var desc = "" - - desc += type(of: object).description() - - if let object = object as? ConstraintView { - desc += ":\(object.snp.label() ?? pointerDescription)" - } else if let object = object as? LayoutConstraint { - desc += ":\(object.label ?? pointerDescription)" - } else { - desc += ":\(pointerDescription)" - } - - if let object = object as? LayoutConstraint, let file = object.constraint?.sourceLocation.0, let line = object.constraint?.sourceLocation.1 { - desc += "@\((file as NSString).lastPathComponent)#\(line)" - } - - desc += "" - return desc -} diff --git a/Lesson12/Pods/SnapKit/Source/LayoutConstraint.swift b/Lesson12/Pods/SnapKit/Source/LayoutConstraint.swift deleted file mode 100644 index 5425ea8..0000000 --- a/Lesson12/Pods/SnapKit/Source/LayoutConstraint.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public class LayoutConstraint : NSLayoutConstraint { - - public var label: String? { - get { - return self.identifier - } - set { - self.identifier = newValue - } - } - - internal weak var constraint: Constraint? = nil - -} - -internal func ==(lhs: LayoutConstraint, rhs: LayoutConstraint) -> Bool { - // If firstItem or secondItem on either constraint has a dangling pointer - // this comparison can cause a crash. The solution for this is to ensure - // your layout code hold strong references to things like Views, LayoutGuides - // and LayoutAnchors as SnapKit will not keep strong references to any of these. - guard lhs.firstAttribute == rhs.firstAttribute && - lhs.secondAttribute == rhs.secondAttribute && - lhs.relation == rhs.relation && - lhs.priority == rhs.priority && - lhs.multiplier == rhs.multiplier && - lhs.secondItem === rhs.secondItem && - lhs.firstItem === rhs.firstItem else { - return false - } - return true -} diff --git a/Lesson12/Pods/SnapKit/Source/LayoutConstraintItem.swift b/Lesson12/Pods/SnapKit/Source/LayoutConstraintItem.swift deleted file mode 100644 index a59de6b..0000000 --- a/Lesson12/Pods/SnapKit/Source/LayoutConstraintItem.swift +++ /dev/null @@ -1,93 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#else - import AppKit -#endif - - -public protocol LayoutConstraintItem: class { -} - -@available(iOS 9.0, OSX 10.11, *) -extension ConstraintLayoutGuide : LayoutConstraintItem { -} - -extension ConstraintView : LayoutConstraintItem { -} - - -extension LayoutConstraintItem { - - internal func prepare() { - if let view = self as? ConstraintView { - view.translatesAutoresizingMaskIntoConstraints = false - } - } - - internal var superview: ConstraintView? { - if let view = self as? ConstraintView { - return view.superview - } - - if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { - return guide.owningView - } - - return nil - } - internal var constraints: [Constraint] { - return self.constraintsSet.allObjects as! [Constraint] - } - - internal func add(constraints: [Constraint]) { - let constraintsSet = self.constraintsSet - for constraint in constraints { - constraintsSet.add(constraint) - } - } - - internal func remove(constraints: [Constraint]) { - let constraintsSet = self.constraintsSet - for constraint in constraints { - constraintsSet.remove(constraint) - } - } - - private var constraintsSet: NSMutableSet { - let constraintsSet: NSMutableSet - - if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { - constraintsSet = existing - } else { - constraintsSet = NSMutableSet() - objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - return constraintsSet - - } - -} -private var constraintsKey: UInt8 = 0 diff --git a/Lesson12/Pods/SnapKit/Source/Typealiases.swift b/Lesson12/Pods/SnapKit/Source/Typealiases.swift deleted file mode 100644 index ded96cc..0000000 --- a/Lesson12/Pods/SnapKit/Source/Typealiases.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -#if os(iOS) || os(tvOS) - import UIKit -#if swift(>=4.2) - typealias LayoutRelation = NSLayoutConstraint.Relation - typealias LayoutAttribute = NSLayoutConstraint.Attribute -#else - typealias LayoutRelation = NSLayoutRelation - typealias LayoutAttribute = NSLayoutAttribute -#endif - typealias LayoutPriority = UILayoutPriority -#else - import AppKit - typealias LayoutRelation = NSLayoutConstraint.Relation - typealias LayoutAttribute = NSLayoutConstraint.Attribute - typealias LayoutPriority = NSLayoutConstraint.Priority -#endif - diff --git a/Lesson12/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift b/Lesson12/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift deleted file mode 100644 index 8e7644c..0000000 --- a/Lesson12/Pods/SnapKit/Source/UILayoutSupport+Extensions.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// SnapKit -// -// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if os(iOS) || os(tvOS) - import UIKit -#endif - - -@available(iOS 8.0, *) -public extension ConstraintLayoutSupport { - - var snp: ConstraintLayoutSupportDSL { - return ConstraintLayoutSupportDSL(support: self) - } - -} diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-Info.plist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-Info.plist deleted file mode 100644 index 2243fe6..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.markdown b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.markdown deleted file mode 100644 index b4fe7b0..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.markdown +++ /dev/null @@ -1,576 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## DTModelStorage - -The MIT License (MIT) - -Copyright (c) 2013 Denys Telezhkin - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -## DTTableViewManager - -Copyright (c) 2012 Denys Telezhkin (http://github.com/DenTelezhkin/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -## Realm - -TABLE OF CONTENTS - -1. Apache License version 2.0 -2. Realm Components -3. Export Compliance - -1. ------------------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -2. ------------------------------------------------------------------------------- - -REALM COMPONENTS - -This software contains components with separate copyright and license terms. -Your use of these components is subject to the terms and conditions of the -following licenses. - -For the Realm Platform Extensions component - - Realm Platform Extensions License - - Copyright (c) 2011-2017 Realm Inc All rights reserved - - Redistribution and use in binary form, with or without modification, is - permitted provided that the following conditions are met: - - 1. You agree not to attempt to decompile, disassemble, reverse engineer or - otherwise discover the source code from which the binary code was derived. - You may, however, access and obtain a separate license for most of the - source code from which this Software was created, at - http://realm.io/pricing/. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -3. ------------------------------------------------------------------------------- - -EXPORT COMPLIANCE - -You understand that the Software may contain cryptographic functions that may be -subject to export restrictions, and you represent and warrant that you are not -(i) located in a jurisdiction that is subject to United States economic -sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, -Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government -blacklist (to include the List of Specially Designated Nationals and Blocked -Persons or the Consolidated Sanctions List administered by the U.S. Department -of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List -or Entity List administered by the U.S. Department of Commerce) -(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned -Person. - -You agree to comply with all export, re-export and import restrictions and -regulations of the U.S. Department of Commerce or other agency or authority of -the United States or other applicable countries. You also agree not to transfer, -or authorize the transfer of, directly or indirectly, of the Software to any -Prohibited Jurisdiction, or otherwise in violation of any such restrictions or -regulations. - - -## RealmSwift - -TABLE OF CONTENTS - -1. Apache License version 2.0 -2. Realm Components -3. Export Compliance - -1. ------------------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -2. ------------------------------------------------------------------------------- - -REALM COMPONENTS - -This software contains components with separate copyright and license terms. -Your use of these components is subject to the terms and conditions of the -following licenses. - -For the Realm Platform Extensions component - - Realm Platform Extensions License - - Copyright (c) 2011-2017 Realm Inc All rights reserved - - Redistribution and use in binary form, with or without modification, is - permitted provided that the following conditions are met: - - 1. You agree not to attempt to decompile, disassemble, reverse engineer or - otherwise discover the source code from which the binary code was derived. - You may, however, access and obtain a separate license for most of the - source code from which this Software was created, at - http://realm.io/pricing/. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -3. ------------------------------------------------------------------------------- - -EXPORT COMPLIANCE - -You understand that the Software may contain cryptographic functions that may be -subject to export restrictions, and you represent and warrant that you are not -(i) located in a jurisdiction that is subject to United States economic -sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, -Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government -blacklist (to include the List of Specially Designated Nationals and Blocked -Persons or the Consolidated Sanctions List administered by the U.S. Department -of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List -or Entity List administered by the U.S. Department of Commerce) -(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned -Person. - -You agree to comply with all export, re-export and import restrictions and -regulations of the U.S. Department of Commerce or other agency or authority of -the United States or other applicable countries. You also agree not to transfer, -or authorize the transfer of, directly or indirectly, of the Software to any -Prohibited Jurisdiction, or otherwise in violation of any such restrictions or -regulations. - - -## SnapKit - -Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Generated by CocoaPods - https://cocoapods.org diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.plist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.plist deleted file mode 100644 index f7328a0..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-acknowledgements.plist +++ /dev/null @@ -1,632 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - The MIT License (MIT) - -Copyright (c) 2013 Denys Telezhkin - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - License - MIT - Title - DTModelStorage - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2012 Denys Telezhkin (http://github.com/DenTelezhkin/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - License - MIT - Title - DTTableViewManager - Type - PSGroupSpecifier - - - FooterText - TABLE OF CONTENTS - -1. Apache License version 2.0 -2. Realm Components -3. Export Compliance - -1. ------------------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -2. ------------------------------------------------------------------------------- - -REALM COMPONENTS - -This software contains components with separate copyright and license terms. -Your use of these components is subject to the terms and conditions of the -following licenses. - -For the Realm Platform Extensions component - - Realm Platform Extensions License - - Copyright (c) 2011-2017 Realm Inc All rights reserved - - Redistribution and use in binary form, with or without modification, is - permitted provided that the following conditions are met: - - 1. You agree not to attempt to decompile, disassemble, reverse engineer or - otherwise discover the source code from which the binary code was derived. - You may, however, access and obtain a separate license for most of the - source code from which this Software was created, at - http://realm.io/pricing/. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -3. ------------------------------------------------------------------------------- - -EXPORT COMPLIANCE - -You understand that the Software may contain cryptographic functions that may be -subject to export restrictions, and you represent and warrant that you are not -(i) located in a jurisdiction that is subject to United States economic -sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, -Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government -blacklist (to include the List of Specially Designated Nationals and Blocked -Persons or the Consolidated Sanctions List administered by the U.S. Department -of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List -or Entity List administered by the U.S. Department of Commerce) -(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned -Person. - -You agree to comply with all export, re-export and import restrictions and -regulations of the U.S. Department of Commerce or other agency or authority of -the United States or other applicable countries. You also agree not to transfer, -or authorize the transfer of, directly or indirectly, of the Software to any -Prohibited Jurisdiction, or otherwise in violation of any such restrictions or -regulations. - - License - Apache 2.0 - Title - Realm - Type - PSGroupSpecifier - - - FooterText - TABLE OF CONTENTS - -1. Apache License version 2.0 -2. Realm Components -3. Export Compliance - -1. ------------------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -2. ------------------------------------------------------------------------------- - -REALM COMPONENTS - -This software contains components with separate copyright and license terms. -Your use of these components is subject to the terms and conditions of the -following licenses. - -For the Realm Platform Extensions component - - Realm Platform Extensions License - - Copyright (c) 2011-2017 Realm Inc All rights reserved - - Redistribution and use in binary form, with or without modification, is - permitted provided that the following conditions are met: - - 1. You agree not to attempt to decompile, disassemble, reverse engineer or - otherwise discover the source code from which the binary code was derived. - You may, however, access and obtain a separate license for most of the - source code from which this Software was created, at - http://realm.io/pricing/. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -3. ------------------------------------------------------------------------------- - -EXPORT COMPLIANCE - -You understand that the Software may contain cryptographic functions that may be -subject to export restrictions, and you represent and warrant that you are not -(i) located in a jurisdiction that is subject to United States economic -sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, -Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government -blacklist (to include the List of Specially Designated Nationals and Blocked -Persons or the Consolidated Sanctions List administered by the U.S. Department -of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List -or Entity List administered by the U.S. Department of Commerce) -(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned -Person. - -You agree to comply with all export, re-export and import restrictions and -regulations of the U.S. Department of Commerce or other agency or authority of -the United States or other applicable countries. You also agree not to transfer, -or authorize the transfer of, directly or indirectly, of the Software to any -Prohibited Jurisdiction, or otherwise in violation of any such restrictions or -regulations. - - License - Apache 2.0 - Title - RealmSwift - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - License - MIT - Title - SnapKit - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-dummy.m b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-dummy.m deleted file mode 100644 index cce0be0..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_Lesson12 : NSObject -@end -@implementation PodsDummy_Pods_Lesson12 -@end diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-input-files.xcfilelist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-input-files.xcfilelist deleted file mode 100644 index 34546b6..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-input-files.xcfilelist +++ /dev/null @@ -1,6 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh -${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework -${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework -${BUILT_PRODUCTS_DIR}/Realm/Realm.framework -${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework -${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework \ No newline at end of file diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-output-files.xcfilelist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-output-files.xcfilelist deleted file mode 100644 index 9b45f96..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Debug-output-files.xcfilelist +++ /dev/null @@ -1,5 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DTModelStorage.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DTTableViewManager.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RealmSwift.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework \ No newline at end of file diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-input-files.xcfilelist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-input-files.xcfilelist deleted file mode 100644 index 34546b6..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-input-files.xcfilelist +++ /dev/null @@ -1,6 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh -${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework -${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework -${BUILT_PRODUCTS_DIR}/Realm/Realm.framework -${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework -${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework \ No newline at end of file diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-output-files.xcfilelist b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-output-files.xcfilelist deleted file mode 100644 index 9b45f96..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks-Release-output-files.xcfilelist +++ /dev/null @@ -1,5 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DTModelStorage.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/DTTableViewManager.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RealmSwift.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SnapKit.framework \ No newline at end of file diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh deleted file mode 100755 index 588b35c..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-frameworks.sh +++ /dev/null @@ -1,179 +0,0 @@ -#!/bin/sh -set -e -set -u -set -o pipefail - -function on_error { - echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" -} -trap 'on_error $LINENO' ERR - -if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then - # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy - # frameworks to, so exit 0 (signalling the script phase was successful). - exit 0 -fi - -echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" -mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - -COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" -SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" - -# Used as a return value for each invocation of `strip_invalid_archs` function. -STRIP_BINARY_RETVAL=0 - -# This protects against multiple targets copying the same framework dependency at the same time. The solution -# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html -RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") - -# Copies and strips a vendored framework -install_framework() -{ - if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then - local source="${BUILT_PRODUCTS_DIR}/$1" - elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then - local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" - elif [ -r "$1" ]; then - local source="$1" - fi - - local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - - if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink "${source}")" - fi - - # Use filter instead of exclude so missing patterns don't throw errors. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" - - local basename - basename="$(basename -s .framework "$1")" - binary="${destination}/${basename}.framework/${basename}" - - if ! [ -r "$binary" ]; then - binary="${destination}/${basename}" - elif [ -L "${binary}" ]; then - echo "Destination binary is symlinked..." - dirname="$(dirname "${binary}")" - binary="${dirname}/$(readlink "${binary}")" - fi - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then - strip_invalid_archs "$binary" - fi - - # Resign the code if required by the build settings to avoid unstable apps - code_sign_if_enabled "${destination}/$(basename "$1")" - - # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. - if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then - local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) - for lib in $swift_runtime_libs; do - echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" - rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" - code_sign_if_enabled "${destination}/${lib}" - done - fi -} - -# Copies and strips a vendored dSYM -install_dsym() { - local source="$1" - if [ -r "$source" ]; then - # Copy the dSYM into a the targets temp dir. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" - - local basename - basename="$(basename -s .framework.dSYM "$source")" - binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then - strip_invalid_archs "$binary" - fi - - if [[ $STRIP_BINARY_RETVAL == 1 ]]; then - # Move the stripped file into its final destination. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" - else - # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. - touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" - fi - fi -} - -# Copies the bcsymbolmap files of a vendored framework -install_bcsymbolmap() { - local bcsymbolmap_path="$1" - local destination="${BUILT_PRODUCTS_DIR}" - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" -} - -# Signs a framework with the provided identity -code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identity - echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" - - if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - code_sign_cmd="$code_sign_cmd &" - fi - echo "$code_sign_cmd" - eval "$code_sign_cmd" - fi -} - -# Strip invalid architectures -strip_invalid_archs() { - binary="$1" - # Get architectures for current target binary - binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" - # Intersect them with the architectures we are building for - intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" - # If there are no archs supported by this binary then warn the user - if [[ -z "$intersected_archs" ]]; then - echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." - STRIP_BINARY_RETVAL=0 - return - fi - stripped="" - for arch in $binary_archs; do - if ! [[ "${ARCHS}" == *"$arch"* ]]; then - # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" - stripped="$stripped $arch" - fi - done - if [[ "$stripped" ]]; then - echo "Stripped $binary of architectures:$stripped" - fi - STRIP_BINARY_RETVAL=1 -} - - -if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework" - install_framework "${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Realm/Realm.framework" - install_framework "${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework" - install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" -fi -if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/DTModelStorage/DTModelStorage.framework" - install_framework "${BUILT_PRODUCTS_DIR}/DTTableViewManager/DTTableViewManager.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Realm/Realm.framework" - install_framework "${BUILT_PRODUCTS_DIR}/RealmSwift/RealmSwift.framework" - install_framework "${BUILT_PRODUCTS_DIR}/SnapKit/SnapKit.framework" -fi -if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - wait -fi diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-umbrella.h b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-umbrella.h deleted file mode 100644 index 965503f..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_Lesson12VersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_Lesson12VersionString[]; - diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.debug.xcconfig b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.debug.xcconfig deleted file mode 100644 index 72e0521..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.debug.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/DTModelStorage" "${PODS_CONFIGURATION_BUILD_DIR}/DTTableViewManager" "${PODS_CONFIGURATION_BUILD_DIR}/Realm" "${PODS_CONFIGURATION_BUILD_DIR}/RealmSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/DTModelStorage/DTModelStorage.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/DTTableViewManager/DTTableViewManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Realm/Realm.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RealmSwift/RealmSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Realm/core" -OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"z" -framework "CoreData" -framework "DTModelStorage" -framework "DTTableViewManager" -framework "Foundation" -framework "Realm" -framework "RealmSwift" -framework "Security" -framework "SnapKit" -framework "UIKit" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.modulemap b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.modulemap deleted file mode 100644 index 9ccc884..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_Lesson12 { - umbrella header "Pods-Lesson12-umbrella.h" - - export * - module * { export * } -} diff --git a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.release.xcconfig b/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.release.xcconfig deleted file mode 100644 index 72e0521..0000000 --- a/Lesson12/Pods/Target Support Files/Pods-Lesson12/Pods-Lesson12.release.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/DTModelStorage" "${PODS_CONFIGURATION_BUILD_DIR}/DTTableViewManager" "${PODS_CONFIGURATION_BUILD_DIR}/Realm" "${PODS_CONFIGURATION_BUILD_DIR}/RealmSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/DTModelStorage/DTModelStorage.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/DTTableViewManager/DTTableViewManager.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Realm/Realm.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RealmSwift/RealmSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SnapKit/SnapKit.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Realm/core" -OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"z" -framework "CoreData" -framework "DTModelStorage" -framework "DTTableViewManager" -framework "Foundation" -framework "Realm" -framework "RealmSwift" -framework "Security" -framework "SnapKit" -framework "UIKit" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-Info.plist b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-Info.plist deleted file mode 100644 index 8d87a1a..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 5.0.1 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-dummy.m b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-dummy.m deleted file mode 100644 index b44e8e5..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_SnapKit : NSObject -@end -@implementation PodsDummy_SnapKit -@end diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch deleted file mode 100644 index beb2a24..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h deleted file mode 100644 index 1b1be64..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double SnapKitVersionNumber; -FOUNDATION_EXPORT const unsigned char SnapKitVersionString[]; - diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.modulemap b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.modulemap deleted file mode 100644 index 4b3e47b..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module SnapKit { - umbrella header "SnapKit-umbrella.h" - - export * - module * { export * } -} diff --git a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.xcconfig b/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.xcconfig deleted file mode 100644 index 6b0071d..0000000 --- a/Lesson12/Pods/Target Support Files/SnapKit/SnapKit.xcconfig +++ /dev/null @@ -1,10 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SnapKit -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/SnapKit -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Lesson13/Lesson13.xcodeproj/project.pbxproj b/Lesson13/Lesson13.xcodeproj/project.pbxproj deleted file mode 100644 index 4860ee9..0000000 --- a/Lesson13/Lesson13.xcodeproj/project.pbxproj +++ /dev/null @@ -1,341 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 50; - objects = { - -/* Begin PBXBuildFile section */ - 3391211123E85420009D8E91 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3391211023E85420009D8E91 /* AppDelegate.swift */; }; - 3391211323E85420009D8E91 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3391211223E85420009D8E91 /* SceneDelegate.swift */; }; - 3391211523E85420009D8E91 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3391211423E85420009D8E91 /* ViewController.swift */; }; - 3391211823E85420009D8E91 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3391211623E85420009D8E91 /* Main.storyboard */; }; - 3391211A23E85428009D8E91 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3391211923E85428009D8E91 /* Assets.xcassets */; }; - 3391211D23E85428009D8E91 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 3391211B23E85428009D8E91 /* LaunchScreen.storyboard */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 3391210D23E85420009D8E91 /* Lesson13.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lesson13.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 3391211023E85420009D8E91 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 3391211223E85420009D8E91 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 3391211423E85420009D8E91 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; - 3391211723E85420009D8E91 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 3391211923E85428009D8E91 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 3391211C23E85428009D8E91 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 3391211E23E85428009D8E91 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 3391210A23E85420009D8E91 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 3391210423E85420009D8E91 = { - isa = PBXGroup; - children = ( - 3391210F23E85420009D8E91 /* Lesson13 */, - 3391210E23E85420009D8E91 /* Products */, - ); - sourceTree = ""; - }; - 3391210E23E85420009D8E91 /* Products */ = { - isa = PBXGroup; - children = ( - 3391210D23E85420009D8E91 /* Lesson13.app */, - ); - name = Products; - sourceTree = ""; - }; - 3391210F23E85420009D8E91 /* Lesson13 */ = { - isa = PBXGroup; - children = ( - 3391211023E85420009D8E91 /* AppDelegate.swift */, - 3391211223E85420009D8E91 /* SceneDelegate.swift */, - 3391211423E85420009D8E91 /* ViewController.swift */, - 3391211623E85420009D8E91 /* Main.storyboard */, - 3391211923E85428009D8E91 /* Assets.xcassets */, - 3391211B23E85428009D8E91 /* LaunchScreen.storyboard */, - 3391211E23E85428009D8E91 /* Info.plist */, - ); - path = Lesson13; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 3391210C23E85420009D8E91 /* Lesson13 */ = { - isa = PBXNativeTarget; - buildConfigurationList = 3391212123E85428009D8E91 /* Build configuration list for PBXNativeTarget "Lesson13" */; - buildPhases = ( - 3391210923E85420009D8E91 /* Sources */, - 3391210A23E85420009D8E91 /* Frameworks */, - 3391210B23E85420009D8E91 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Lesson13; - productName = Lesson13; - productReference = 3391210D23E85420009D8E91 /* Lesson13.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 3391210523E85420009D8E91 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1130; - LastUpgradeCheck = 1130; - ORGANIZATIONNAME = "Михаил Беленко"; - TargetAttributes = { - 3391210C23E85420009D8E91 = { - CreatedOnToolsVersion = 11.3.1; - }; - }; - }; - buildConfigurationList = 3391210823E85420009D8E91 /* Build configuration list for PBXProject "Lesson13" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 3391210423E85420009D8E91; - productRefGroup = 3391210E23E85420009D8E91 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 3391210C23E85420009D8E91 /* Lesson13 */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 3391210B23E85420009D8E91 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3391211D23E85428009D8E91 /* LaunchScreen.storyboard in Resources */, - 3391211A23E85428009D8E91 /* Assets.xcassets in Resources */, - 3391211823E85420009D8E91 /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 3391210923E85420009D8E91 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3391211523E85420009D8E91 /* ViewController.swift in Sources */, - 3391211123E85420009D8E91 /* AppDelegate.swift in Sources */, - 3391211323E85420009D8E91 /* SceneDelegate.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 3391211623E85420009D8E91 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 3391211723E85420009D8E91 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 3391211B23E85428009D8E91 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 3391211C23E85428009D8E91 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 3391211F23E85428009D8E91 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 3391212023E85428009D8E91 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 3391212223E85428009D8E91 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson13/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson13; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 3391212323E85428009D8E91 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = Lesson13/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson13; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 3391210823E85420009D8E91 /* Build configuration list for PBXProject "Lesson13" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3391211F23E85428009D8E91 /* Debug */, - 3391212023E85428009D8E91 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 3391212123E85428009D8E91 /* Build configuration list for PBXNativeTarget "Lesson13" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3391212223E85428009D8E91 /* Debug */, - 3391212323E85428009D8E91 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 3391210523E85420009D8E91 /* Project object */; -} diff --git a/Lesson13/Lesson13.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson13/Lesson13.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index a270162..0000000 --- a/Lesson13/Lesson13.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson13/Lesson13.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson13/Lesson13.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson13/Lesson13.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson13/Lesson13/Assets.xcassets/AppIcon.appiconset/Contents.json b/Lesson13/Lesson13/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d8db8d6..0000000 --- a/Lesson13/Lesson13/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "83.5x83.5", - "scale" : "2x" - }, - { - "idiom" : "ios-marketing", - "size" : "1024x1024", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson13/Lesson13/Assets.xcassets/Contents.json b/Lesson13/Lesson13/Assets.xcassets/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson13/Lesson13/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson13/Lesson13/Base.lproj/LaunchScreen.storyboard b/Lesson13/Lesson13/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 865e932..0000000 --- a/Lesson13/Lesson13/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson13/Lesson13/Base.lproj/Main.storyboard b/Lesson13/Lesson13/Base.lproj/Main.storyboard deleted file mode 100644 index 76f2a53..0000000 --- a/Lesson13/Lesson13/Base.lproj/Main.storyboard +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson13/Lesson13/Info.plist b/Lesson13/Lesson13/Info.plist deleted file mode 100644 index 2a3483c..0000000 --- a/Lesson13/Lesson13/Info.plist +++ /dev/null @@ -1,64 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - UISceneConfigurations - - UIWindowSceneSessionRoleApplication - - - UISceneConfigurationName - Default Configuration - UISceneDelegateClassName - $(PRODUCT_MODULE_NAME).SceneDelegate - UISceneStoryboardFile - Main - - - - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Lesson13/Lesson13/SceneDelegate.swift b/Lesson13/Lesson13/SceneDelegate.swift deleted file mode 100644 index f1eca48..0000000 --- a/Lesson13/Lesson13/SceneDelegate.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// SceneDelegate.swift -// Lesson13 -// -// Created by Михаил Беленко on 03.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - - var window: UIWindow? - - - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). - guard let _ = (scene as? UIWindowScene) else { return } - } - - func sceneDidDisconnect(_ scene: UIScene) { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). - } - - func sceneDidBecomeActive(_ scene: UIScene) { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. - } - - func sceneWillResignActive(_ scene: UIScene) { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). - } - - func sceneWillEnterForeground(_ scene: UIScene) { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. - } - - func sceneDidEnterBackground(_ scene: UIScene) { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. - } - - -} - diff --git a/Lesson13/Lesson13/ViewController.swift b/Lesson13/Lesson13/ViewController.swift deleted file mode 100644 index 3db9761..0000000 --- a/Lesson13/Lesson13/ViewController.swift +++ /dev/null @@ -1,103 +0,0 @@ -// -// ViewController.swift -// Lesson13 -// -// Created by Михаил Беленко on 03.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class ViewController: UIViewController { - - @IBOutlet weak var animateView: UIView! - @IBOutlet weak var animateViewWidthConstraint: NSLayoutConstraint! - @IBOutlet weak var animateViewHeightConstraint: NSLayoutConstraint! - @IBOutlet weak var numberOfAnimationLabel: UILabel! - - private var numberOfAnimation: Int = 1 - - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - - animate() - } - - private func animate() { - switch numberOfAnimation { - case 1: - UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: - { [unowned self] in - self.animateView.backgroundColor = .systemYellow - }, completion: { [unowned self] _ in - self.animateView.backgroundColor = .systemRed - }) - case 2: - self.animateView.frame.origin.y = self.view.frame.size.height / 2 - UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: { [unowned self] in - self.animateView.frame.origin.y = self.view.frame.size.height - self.animateView.frame.origin.x = 0 - }, completion: nil) - case 3: - CATransaction.begin() - CATransaction.setCompletionBlock { [unowned self] in - let animateOff = CABasicAnimation(keyPath: "cornerRadius") - animateOff.fromValue = self.animateView.frame.size.width / 2 - animateOff.toValue = 0 - animateOff.duration = 1 - self.animateView.layer.add(animateOff, forKey: "cornerRadiusOff") - self.animateView.layer.cornerRadius = 0 - } - let animateOn = CABasicAnimation(keyPath: "cornerRadius") - animateOn.fromValue = 0 - animateOn.toValue = animateView.frame.size.width / 2 - animateOn.duration = 1 - animateView.layer.add(animateOn, forKey: "cornerRadiusOn") - animateView.layer.cornerRadius = animateView.frame.size.width / 2 - CATransaction.commit() - case 4: - UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: { [unowned self] in - self.animateView.transform = CGAffineTransform(rotationAngle: CGFloat.pi) - }, completion: nil) - case 5: - UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: { [unowned self] in - self.animateView.alpha = 0 - }, completion: { [unowned self] _ in - self.animateView.alpha = 1 - }) - case 6: - UIView.animate(withDuration: 1, delay: 0, options: .autoreverse, animations: { [unowned self] in - self.animateViewWidthConstraint.constant = self.animateViewWidthConstraint.constant * 2 - self.animateViewHeightConstraint.constant = self.animateViewHeightConstraint.constant * 2 - self.view.layoutIfNeeded() - }, completion: {[unowned self] _ in - self.animateViewWidthConstraint.constant = self.animateViewWidthConstraint.constant / 2 - self.animateViewHeightConstraint.constant = self.animateViewHeightConstraint.constant / 2 - self.view.layoutIfNeeded() - }) - case 7: - UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .curveLinear], animations: { [unowned self] in - self.animateView.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 2) - }, completion: nil) - default: - fatalError("number of animation more 7 or less 1") - } - } - - @IBAction func backBatton(_ sender: Any) { - if numberOfAnimation != 1 { - numberOfAnimation -= 1 - numberOfAnimationLabel.text = "\(numberOfAnimation)" - animate() - } - } - - @IBAction func nextButton(_ sender: Any) { - if numberOfAnimation != 7 { - numberOfAnimation += 1 - numberOfAnimationLabel.text = "\(numberOfAnimation)" - animate() - } - } -} - diff --git a/Lesson14/Lesson14.xcodeproj/project.pbxproj b/Lesson14/Lesson14.xcodeproj/project.pbxproj deleted file mode 100644 index b0e5da1..0000000 --- a/Lesson14/Lesson14.xcodeproj/project.pbxproj +++ /dev/null @@ -1,488 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 33A83ABD23E9411D00E1BF8C /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A83ABC23E9411D00E1BF8C /* AppDelegate.swift */; }; - 33A83ABF23E9411D00E1BF8C /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A83ABE23E9411D00E1BF8C /* SceneDelegate.swift */; }; - 33A83AC123E9411D00E1BF8C /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A83AC023E9411D00E1BF8C /* ViewController.swift */; }; - 33A83AC423E9411D00E1BF8C /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33A83AC223E9411D00E1BF8C /* Main.storyboard */; }; - 33A83AC723E9411D00E1BF8C /* Lesson14.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 33A83AC523E9411D00E1BF8C /* Lesson14.xcdatamodeld */; }; - 33A83AC923E9412500E1BF8C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33A83AC823E9412500E1BF8C /* Assets.xcassets */; }; - 33A83ACC23E9412500E1BF8C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 33A83ACA23E9412500E1BF8C /* LaunchScreen.storyboard */; }; - 33A83AD523E941B900E1BF8C /* UserDefaultsPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A83AD423E941B900E1BF8C /* UserDefaultsPersistence.swift */; }; - 33BDD18E23E948F30008E7AD /* RealmViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD18D23E948F30008E7AD /* RealmViewController.swift */; }; - 33BDD19323E949770008E7AD /* RealmPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19223E949770008E7AD /* RealmPersistence.swift */; }; - 33BDD19523E9498D0008E7AD /* TaskRealmEntity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19423E9498D0008E7AD /* TaskRealmEntity.swift */; }; - 33BDD19923E94D3B0008E7AD /* ToDoListTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19823E94D3B0008E7AD /* ToDoListTableViewCell.swift */; }; - 33BDD19B23E982AB0008E7AD /* CoreDataPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19A23E982AB0008E7AD /* CoreDataPersistence.swift */; }; - 33BDD19D23E9858B0008E7AD /* CoreDataViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19C23E9858B0008E7AD /* CoreDataViewController.swift */; }; - 33BDD19F23E98ABA0008E7AD /* CoreDataToDoListTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BDD19E23E98ABA0008E7AD /* CoreDataToDoListTableViewCell.swift */; }; - D098926CE7379FCA9C42C6D5 /* Pods_Lesson14.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CE7B9703D0AF425726F8223D /* Pods_Lesson14.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 33A83AB923E9411D00E1BF8C /* Lesson14.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lesson14.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 33A83ABC23E9411D00E1BF8C /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33A83ABE23E9411D00E1BF8C /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 33A83AC023E9411D00E1BF8C /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; - 33A83AC323E9411D00E1BF8C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 33A83AC623E9411D00E1BF8C /* Lesson14.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Lesson14.xcdatamodel; sourceTree = ""; }; - 33A83AC823E9412500E1BF8C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 33A83ACB23E9412500E1BF8C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 33A83ACD23E9412500E1BF8C /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 33A83AD423E941B900E1BF8C /* UserDefaultsPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserDefaultsPersistence.swift; sourceTree = ""; }; - 33BDD18D23E948F30008E7AD /* RealmViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealmViewController.swift; sourceTree = ""; }; - 33BDD19223E949770008E7AD /* RealmPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealmPersistence.swift; sourceTree = ""; }; - 33BDD19423E9498D0008E7AD /* TaskRealmEntity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskRealmEntity.swift; sourceTree = ""; }; - 33BDD19823E94D3B0008E7AD /* ToDoListTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToDoListTableViewCell.swift; sourceTree = ""; }; - 33BDD19A23E982AB0008E7AD /* CoreDataPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreDataPersistence.swift; sourceTree = ""; }; - 33BDD19C23E9858B0008E7AD /* CoreDataViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreDataViewController.swift; sourceTree = ""; }; - 33BDD19E23E98ABA0008E7AD /* CoreDataToDoListTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreDataToDoListTableViewCell.swift; sourceTree = ""; }; - CE7B9703D0AF425726F8223D /* Pods_Lesson14.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Lesson14.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E83BF21D34BBD393ED701504 /* Pods-Lesson14.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson14.release.xcconfig"; path = "Target Support Files/Pods-Lesson14/Pods-Lesson14.release.xcconfig"; sourceTree = ""; }; - F6E1205B46E26E73C8E8E670 /* Pods-Lesson14.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Lesson14.debug.xcconfig"; path = "Target Support Files/Pods-Lesson14/Pods-Lesson14.debug.xcconfig"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 33A83AB623E9411D00E1BF8C /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - D098926CE7379FCA9C42C6D5 /* Pods_Lesson14.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 33A83AB023E9411D00E1BF8C = { - isa = PBXGroup; - children = ( - 33A83ABB23E9411D00E1BF8C /* Lesson14 */, - 33A83ABA23E9411D00E1BF8C /* Products */, - 7019CFEAD9ED8E481ADD9A48 /* Pods */, - 50E3AEC32B4C947B3CFC1527 /* Frameworks */, - ); - sourceTree = ""; - }; - 33A83ABA23E9411D00E1BF8C /* Products */ = { - isa = PBXGroup; - children = ( - 33A83AB923E9411D00E1BF8C /* Lesson14.app */, - ); - name = Products; - sourceTree = ""; - }; - 33A83ABB23E9411D00E1BF8C /* Lesson14 */ = { - isa = PBXGroup; - children = ( - 33A83AD323E9418000E1BF8C /* Persistence */, - 33A83ABC23E9411D00E1BF8C /* AppDelegate.swift */, - 33A83ABE23E9411D00E1BF8C /* SceneDelegate.swift */, - 33A83AC023E9411D00E1BF8C /* ViewController.swift */, - 33A83AC223E9411D00E1BF8C /* Main.storyboard */, - 33A83AC823E9412500E1BF8C /* Assets.xcassets */, - 33A83ACA23E9412500E1BF8C /* LaunchScreen.storyboard */, - 33A83ACD23E9412500E1BF8C /* Info.plist */, - 33A83AC523E9411D00E1BF8C /* Lesson14.xcdatamodeld */, - 33BDD18D23E948F30008E7AD /* RealmViewController.swift */, - 33BDD19823E94D3B0008E7AD /* ToDoListTableViewCell.swift */, - 33BDD19C23E9858B0008E7AD /* CoreDataViewController.swift */, - 33BDD19E23E98ABA0008E7AD /* CoreDataToDoListTableViewCell.swift */, - ); - path = Lesson14; - sourceTree = ""; - }; - 33A83AD323E9418000E1BF8C /* Persistence */ = { - isa = PBXGroup; - children = ( - 33BDD19023E949260008E7AD /* Realm */, - 33A83AD423E941B900E1BF8C /* UserDefaultsPersistence.swift */, - 33BDD19A23E982AB0008E7AD /* CoreDataPersistence.swift */, - ); - path = Persistence; - sourceTree = ""; - }; - 33BDD19023E949260008E7AD /* Realm */ = { - isa = PBXGroup; - children = ( - 33BDD19123E9492D0008E7AD /* Entity */, - 33BDD19223E949770008E7AD /* RealmPersistence.swift */, - ); - path = Realm; - sourceTree = ""; - }; - 33BDD19123E9492D0008E7AD /* Entity */ = { - isa = PBXGroup; - children = ( - 33BDD19423E9498D0008E7AD /* TaskRealmEntity.swift */, - ); - path = Entity; - sourceTree = ""; - }; - 50E3AEC32B4C947B3CFC1527 /* Frameworks */ = { - isa = PBXGroup; - children = ( - CE7B9703D0AF425726F8223D /* Pods_Lesson14.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 7019CFEAD9ED8E481ADD9A48 /* Pods */ = { - isa = PBXGroup; - children = ( - F6E1205B46E26E73C8E8E670 /* Pods-Lesson14.debug.xcconfig */, - E83BF21D34BBD393ED701504 /* Pods-Lesson14.release.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 33A83AB823E9411D00E1BF8C /* Lesson14 */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33A83AD023E9412500E1BF8C /* Build configuration list for PBXNativeTarget "Lesson14" */; - buildPhases = ( - 603161FB1A041D0A89A34F5A /* [CP] Check Pods Manifest.lock */, - 33A83AB523E9411D00E1BF8C /* Sources */, - 33A83AB623E9411D00E1BF8C /* Frameworks */, - 33A83AB723E9411D00E1BF8C /* Resources */, - 50DD6E27443D8A61956A6225 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Lesson14; - productName = Lesson14; - productReference = 33A83AB923E9411D00E1BF8C /* Lesson14.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33A83AB123E9411D00E1BF8C /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1130; - LastUpgradeCheck = 1130; - ORGANIZATIONNAME = "Михаил Беленко"; - TargetAttributes = { - 33A83AB823E9411D00E1BF8C = { - CreatedOnToolsVersion = 11.3.1; - }; - }; - }; - buildConfigurationList = 33A83AB423E9411D00E1BF8C /* Build configuration list for PBXProject "Lesson14" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33A83AB023E9411D00E1BF8C; - productRefGroup = 33A83ABA23E9411D00E1BF8C /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33A83AB823E9411D00E1BF8C /* Lesson14 */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 33A83AB723E9411D00E1BF8C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33A83ACC23E9412500E1BF8C /* LaunchScreen.storyboard in Resources */, - 33A83AC923E9412500E1BF8C /* Assets.xcassets in Resources */, - 33A83AC423E9411D00E1BF8C /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 50DD6E27443D8A61956A6225 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Lesson14/Pods-Lesson14-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 603161FB1A041D0A89A34F5A /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Lesson14-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 33A83AB523E9411D00E1BF8C /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33BDD18E23E948F30008E7AD /* RealmViewController.swift in Sources */, - 33BDD19523E9498D0008E7AD /* TaskRealmEntity.swift in Sources */, - 33BDD19F23E98ABA0008E7AD /* CoreDataToDoListTableViewCell.swift in Sources */, - 33BDD19323E949770008E7AD /* RealmPersistence.swift in Sources */, - 33A83AC123E9411D00E1BF8C /* ViewController.swift in Sources */, - 33A83AD523E941B900E1BF8C /* UserDefaultsPersistence.swift in Sources */, - 33BDD19D23E9858B0008E7AD /* CoreDataViewController.swift in Sources */, - 33A83ABD23E9411D00E1BF8C /* AppDelegate.swift in Sources */, - 33BDD19923E94D3B0008E7AD /* ToDoListTableViewCell.swift in Sources */, - 33A83AC723E9411D00E1BF8C /* Lesson14.xcdatamodeld in Sources */, - 33BDD19B23E982AB0008E7AD /* CoreDataPersistence.swift in Sources */, - 33A83ABF23E9411D00E1BF8C /* SceneDelegate.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - 33A83AC223E9411D00E1BF8C /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 33A83AC323E9411D00E1BF8C /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 33A83ACA23E9412500E1BF8C /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 33A83ACB23E9412500E1BF8C /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 33A83ACE23E9412500E1BF8C /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33A83ACF23E9412500E1BF8C /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.2; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 33A83AD123E9412500E1BF8C /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = F6E1205B46E26E73C8E8E670 /* Pods-Lesson14.debug.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = 8374DGJ7W4; - INFOPLIST_FILE = Lesson14/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson14; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Debug; - }; - 33A83AD223E9412500E1BF8C /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = E83BF21D34BBD393ED701504 /* Pods-Lesson14.release.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = 8374DGJ7W4; - INFOPLIST_FILE = Lesson14/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = BelenkoMO.Lesson14; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 33A83AB423E9411D00E1BF8C /* Build configuration list for PBXProject "Lesson14" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33A83ACE23E9412500E1BF8C /* Debug */, - 33A83ACF23E9412500E1BF8C /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33A83AD023E9412500E1BF8C /* Build configuration list for PBXNativeTarget "Lesson14" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33A83AD123E9412500E1BF8C /* Debug */, - 33A83AD223E9412500E1BF8C /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - -/* Begin XCVersionGroup section */ - 33A83AC523E9411D00E1BF8C /* Lesson14.xcdatamodeld */ = { - isa = XCVersionGroup; - children = ( - 33A83AC623E9411D00E1BF8C /* Lesson14.xcdatamodel */, - ); - currentVersion = 33A83AC623E9411D00E1BF8C /* Lesson14.xcdatamodel */; - path = Lesson14.xcdatamodeld; - sourceTree = ""; - versionGroupType = wrapper.xcdatamodel; - }; -/* End XCVersionGroup section */ - }; - rootObject = 33A83AB123E9411D00E1BF8C /* Project object */; -} diff --git a/Lesson14/Lesson14.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lesson14/Lesson14.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index b54aacd..0000000 --- a/Lesson14/Lesson14.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Lesson14/Lesson14.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson14/Lesson14.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson14/Lesson14.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson14/Lesson14.xcworkspace/contents.xcworkspacedata b/Lesson14/Lesson14.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index a1b7cc6..0000000 --- a/Lesson14/Lesson14.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - diff --git a/Lesson14/Lesson14.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lesson14/Lesson14.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Lesson14/Lesson14.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Lesson14/Lesson14/AppDelegate.swift b/Lesson14/Lesson14/AppDelegate.swift deleted file mode 100644 index 3823d84..0000000 --- a/Lesson14/Lesson14/AppDelegate.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// AppDelegate.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import CoreData - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { - - var window: UIWindow? - - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - return true - } - - // MARK: UISceneSession Lifecycle - - @available(iOS 13.0, *) - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) - } - - @available(iOS 13.0, *) - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. - } - - // MARK: - Core Data stack - - lazy var persistentContainer: NSPersistentContainer = { - /* - The persistent container for the application. This implementation - creates and returns a container, having loaded the store for the - application to it. This property is optional since there are legitimate - error conditions that could cause the creation of the store to fail. - */ - let container = NSPersistentContainer(name: "Lesson14") - container.loadPersistentStores(completionHandler: { (storeDescription, error) in - if let error = error as NSError? { - // Replace this implementation with code to handle the error appropriately. - // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. - - /* - Typical reasons for an error here include: - * The parent directory does not exist, cannot be created, or disallows writing. - * The persistent store is not accessible, due to permissions or data protection when the device is locked. - * The device is out of space. - * The store could not be migrated to the current model version. - Check the error message to determine what the actual problem was. - */ - fatalError("Unresolved error \(error), \(error.userInfo)") - } - }) - return container - }() - - // MARK: - Core Data Saving support - - func saveContext () { - let context = persistentContainer.viewContext - if context.hasChanges { - do { - try context.save() - } catch { - // Replace this implementation with code to handle the error appropriately. - // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. - let nserror = error as NSError - fatalError("Unresolved error \(nserror), \(nserror.userInfo)") - } - } - } - -} - diff --git a/Lesson14/Lesson14/Assets.xcassets/AppIcon.appiconset/Contents.json b/Lesson14/Lesson14/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index d8db8d6..0000000 --- a/Lesson14/Lesson14/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "76x76", - "scale" : "2x" - }, - { - "idiom" : "ipad", - "size" : "83.5x83.5", - "scale" : "2x" - }, - { - "idiom" : "ios-marketing", - "size" : "1024x1024", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson14/Lesson14/Assets.xcassets/Contents.json b/Lesson14/Lesson14/Assets.xcassets/Contents.json deleted file mode 100644 index da4a164..0000000 --- a/Lesson14/Lesson14/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Lesson14/Lesson14/Base.lproj/LaunchScreen.storyboard b/Lesson14/Lesson14/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 865e932..0000000 --- a/Lesson14/Lesson14/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson14/Lesson14/Base.lproj/Main.storyboard b/Lesson14/Lesson14/Base.lproj/Main.storyboard deleted file mode 100644 index 0e48a63..0000000 --- a/Lesson14/Lesson14/Base.lproj/Main.storyboard +++ /dev/null @@ -1,184 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Lesson14/Lesson14/CoreDataToDoListTableViewCell.swift b/Lesson14/Lesson14/CoreDataToDoListTableViewCell.swift deleted file mode 100644 index f702848..0000000 --- a/Lesson14/Lesson14/CoreDataToDoListTableViewCell.swift +++ /dev/null @@ -1,141 +0,0 @@ -// -// CoreDataToDoListTableViewCell.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTModelStorage -import SnapKit -import RxSwift - -class CoreDataToDoListTableViewCell: UITableViewCell, ModelTransfer { - typealias ModelType = TaskCoreDataEntity - var model: ModelType! - - private let disableColor: UIColor = UIColor.black.withAlphaComponent(0.1) - - private var isComplite = false { - didSet { - if isComplite { - nameTaskLabel.attributedText = setStruckThroughText(text: nameTaskLabel.text) - dateCreateTaskLabel.attributedText = setStruckThroughText(text: dateCreateTaskLabel.text) - descriptionTaskTextView.isEditable = false - descriptionTaskTextView.backgroundColor = disableColor - compliteTaskButton.isEnabled = false - compliteTaskButton.setTitleColor(.black, for: .normal) - compliteTaskButton.backgroundColor = disableColor - } - } - } - - var disposeBag = DisposeBag() - - private lazy var nameTaskLabel = UILabel() - private lazy var dateCreateTaskLabel = UILabel() - - lazy var descriptionTaskTextView: UITextView = { - let textView = UITextView() - textView.layer.borderWidth = 1 - textView.layer.borderColor = UIColor.black.cgColor - return textView - }() - - lazy var compliteTaskButton: UIButton = { - let button = UIButton() - button.setTitle("✓", for: .normal) - button.setTitleColor(.white, for: .normal) - button.backgroundColor = .systemBlue - button.layer.cornerRadius = 15 - return button - }() - - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { - super.init(style: style, reuseIdentifier: reuseIdentifier) - - setupCell() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupCell() { - contentView.addSubview(nameTaskLabel) - contentView.addSubview(dateCreateTaskLabel) - contentView.addSubview(descriptionTaskTextView) - contentView.addSubview(compliteTaskButton) - - setupConstraint() - } - - private func setStruckThroughText(text: String?) -> NSAttributedString? { - guard let text = text else { - return nil - } - let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text) - attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) - return attributeString - } - - func update(with model: TaskCoreDataEntity) { - self.model = model - nameTaskLabel.text = self.model.name - dateCreateTaskLabel.text = convertDate(date: self.model.createdAt) - descriptionTaskTextView.text = self.model.notes - isComplite = self.model.isCompleted - } - - func setComplite() { - isComplite = true - } - - private func convertDate(date dateInput: Date?) -> String { - let date = dateInput ?? Date() - let formatter = DateFormatter() - // initially set the format based on your datepicker date / server String - formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - - let myString = formatter.string(from: date as Date) // string purpose I add here - // convert your string to date - let yourDate = formatter.date(from: myString) - //then again set the date format whhich type of output you need - formatter.dateFormat = "dd MMMM yyyy HH:mm" - // again convert your date to string - return formatter.string(from: yourDate!) - } - - private func setupConstraint() { - nameTaskLabel.snp.makeConstraints { make in - make.top.leading.equalToSuperview().inset(16) - } - - compliteTaskButton.snp.makeConstraints { make in - make.top.equalTo(nameTaskLabel.snp.top) - make.trailing.equalToSuperview().inset(16) - make.leading.greaterThanOrEqualTo(nameTaskLabel.snp.trailing).offset(16) - make.bottom.lessThanOrEqualTo(descriptionTaskTextView.snp.top).offset(-8) - make.height.width.equalTo(30) - } - - dateCreateTaskLabel.snp.makeConstraints { make in - make.top.equalTo(nameTaskLabel.snp.bottom).offset(8) - make.trailing.equalTo(nameTaskLabel.snp.trailing) - make.leading.equalToSuperview().inset(16) - } - - descriptionTaskTextView.snp.makeConstraints { make in - make.top.equalTo(dateCreateTaskLabel.snp.bottom).offset(8) - make.leading.trailing.bottom.equalToSuperview().inset(16) - make.height.equalTo(100) - } - } - - override func prepareForReuse() { - super.prepareForReuse() - - disposeBag = DisposeBag() - } -} diff --git a/Lesson14/Lesson14/CoreDataViewController.swift b/Lesson14/Lesson14/CoreDataViewController.swift deleted file mode 100644 index ea49964..0000000 --- a/Lesson14/Lesson14/CoreDataViewController.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// CoreDataViewController.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import CoreData -import DTTableViewManager - -class CoreDataViewController: UIViewController, DTTableViewManageable { - - @IBOutlet weak var tableView: UITableView! - @IBOutlet weak var addTaskButton: UIButton! - - private var counterTask: Int = 1 - - override func viewDidLoad() { - super.viewDidLoad() - - manager.memoryStorage.setItems(CoreDataPersistence.storage.getAllTask()) - counterTask = CoreDataPersistence.storage.getCountTasks() + 1 - - manager.register(CoreDataToDoListTableViewCell.self) - configureCells() - addTaskButton.layer.cornerRadius = addTaskButton.bounds.width / 2 - } - - private func configureCells() { - manager.configure(CoreDataToDoListTableViewCell.self) { cell, _, indexPath in - cell.compliteTaskButton.rx.controlEvent(.touchUpInside).subscribe(onNext: { [unowned cell] _ in - cell.setComplite() - CoreDataPersistence.storage.changeTask(index: indexPath.row, description: nil, isComplited: true) - }).disposed(by: cell.disposeBag) - - cell.descriptionTaskTextView.rx.text.asObservable().subscribe(onNext: { text in - CoreDataPersistence.storage.changeTask(index: indexPath.row, description: text, isComplited: nil) - }).disposed(by: cell.disposeBag) - } - - manager.didSelect(CoreDataToDoListTableViewCell.self) { cell, _, _ in - cell.setSelected(false, animated: true) - } - } - - @IBAction func addButtonClick(_ sender: Any) { - let name = "Задача №\(counterTask)" - counterTask += 1 - manager.memoryStorage.addItem(CoreDataPersistence.storage.addTask(name: name)) - } -} diff --git a/Lesson14/Lesson14/Info.plist b/Lesson14/Lesson14/Info.plist deleted file mode 100644 index 2a3483c..0000000 --- a/Lesson14/Lesson14/Info.plist +++ /dev/null @@ -1,64 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - UISceneConfigurations - - UIWindowSceneSessionRoleApplication - - - UISceneConfigurationName - Default Configuration - UISceneDelegateClassName - $(PRODUCT_MODULE_NAME).SceneDelegate - UISceneStoryboardFile - Main - - - - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Lesson14/Lesson14/Lesson14.xcdatamodeld/.xccurrentversion b/Lesson14/Lesson14/Lesson14.xcdatamodeld/.xccurrentversion deleted file mode 100644 index a8709f7..0000000 --- a/Lesson14/Lesson14/Lesson14.xcdatamodeld/.xccurrentversion +++ /dev/null @@ -1,8 +0,0 @@ - - - - - _XCCurrentVersionName - Lesson14.xcdatamodel - - diff --git a/Lesson14/Lesson14/Lesson14.xcdatamodeld/Lesson14.xcdatamodel/contents b/Lesson14/Lesson14/Lesson14.xcdatamodeld/Lesson14.xcdatamodel/contents deleted file mode 100644 index 176f48e..0000000 --- a/Lesson14/Lesson14/Lesson14.xcdatamodeld/Lesson14.xcdatamodel/contents +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/Lesson14/Lesson14/Persistence/CoreDataPersistence.swift b/Lesson14/Lesson14/Persistence/CoreDataPersistence.swift deleted file mode 100644 index 966c6d0..0000000 --- a/Lesson14/Lesson14/Persistence/CoreDataPersistence.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// CoreDataPersistence.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import CoreData -import UIKit - -class CoreDataPersistence { - static var storage = CoreDataPersistence() - - private let appDelegate = UIApplication.shared.delegate as! AppDelegate - private lazy var managedContext = self.appDelegate.persistentContainer.viewContext - private lazy var entity = NSEntityDescription.entity(forEntityName: "TaskCoreDataEntity", - in: self.managedContext)! - - private lazy var tasks: [TaskCoreDataEntity] = try! self.managedContext.fetch(NSFetchRequest(entityName: "TaskCoreDataEntity")) - - func addTask(name: String) -> TaskCoreDataEntity { - let task = TaskCoreDataEntity(entity: entity, - insertInto: managedContext) - - task.setValue(name, forKeyPath: "name") - task.setValue(Date(), forKey: "createdAt") - - do { - try managedContext.save() - tasks.append(task) - } catch let error as NSError { - print("Could not save. \(error), \(error.userInfo)") - } - return task - } - - /// Save description or isComplited nil if you do not want to change these parameters - func changeTask(index: Int, description descriptionInput: String? = nil, isComplited isComplitedInput: Bool? = nil) { - let description: String = descriptionInput ?? tasks[index].value(forKey: "notes") as! String - let isComplited: Bool = isComplitedInput ?? tasks[index].value(forKey: "isCompleted") as! Bool - - do { - tasks[index].setValue(description, forKey: "notes") - tasks[index].setValue(isComplited, forKey: "isCompleted") - try managedContext.save() - } catch let error as NSError { - print("Could not change. \(error), \(error.userInfo)") - } - } - - func getAllTask() -> [TaskCoreDataEntity] { - return tasks - } - - func getCountTasks() -> Int { - return tasks.count - } -} diff --git a/Lesson14/Lesson14/Persistence/Realm/Entity/TaskRealmEntity.swift b/Lesson14/Lesson14/Persistence/Realm/Entity/TaskRealmEntity.swift deleted file mode 100644 index 998ca48..0000000 --- a/Lesson14/Lesson14/Persistence/Realm/Entity/TaskRealmEntity.swift +++ /dev/null @@ -1,17 +0,0 @@ -// -// TaskRealmEntity.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import RealmSwift - -class TaskRealmEntity: Object { - - @objc dynamic var name = "" - @objc dynamic var createdAt = NSDate() - @objc dynamic var notes = "" - @objc dynamic var isCompleted = false -} diff --git a/Lesson14/Lesson14/Persistence/Realm/RealmPersistence.swift b/Lesson14/Lesson14/Persistence/Realm/RealmPersistence.swift deleted file mode 100644 index d342688..0000000 --- a/Lesson14/Lesson14/Persistence/Realm/RealmPersistence.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// RealmPersistence.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import RealmSwift - -class RealmPersistence { - static var storage = RealmPersistence() - - private let realm = try! Realm() - - func addTask(task: TaskRealmEntity) { - try! realm.write { - realm.add(task) - } - } - - /// Save description or isComplited nil if you do not want to change these parameters - func changeTask(task: TaskRealmEntity, description descriptionInput: String? = nil, isComplited isComplitedInput: Bool? = nil) { - let description: String = descriptionInput ?? task.notes - let isComplited: Bool = isComplitedInput ?? task.isCompleted - - try! realm.write { - task.notes = description - task.isCompleted = isComplited - } - } - - func getAllTask() -> [TaskRealmEntity] { - var arrayTask: [TaskRealmEntity] = [] - for task in realm.objects(TaskRealmEntity.self) { - arrayTask.append(task) - } - return arrayTask - } - - func getCountTasks() -> Int { - return realm.objects(TaskRealmEntity.self).count - } -} diff --git a/Lesson14/Lesson14/Persistence/UserDefaultsPersistence.swift b/Lesson14/Lesson14/Persistence/UserDefaultsPersistence.swift deleted file mode 100644 index c213bdb..0000000 --- a/Lesson14/Lesson14/Persistence/UserDefaultsPersistence.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// UserDefaultsPersistence.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import Foundation - -class UserDefaultsPersistence { - static var storage = UserDefaultsPersistence() - - private let kFirstNameKey: String = "UserDefaultsPersistence.kFirstNameKey" - var firstName: String? { - set { - UserDefaults.standard.set(newValue, forKey: kFirstNameKey) - } - get { - return UserDefaults.standard.string(forKey: kFirstNameKey) - } - } - - private let kLastNameKey: String = "UserDefaultsPersistence.kLastNameKey" - var lastName: String? { - set { - UserDefaults.standard.set(newValue, forKey: kLastNameKey) - } - get { - return UserDefaults.standard.string(forKey: kLastNameKey) - } - } -} diff --git a/Lesson14/Lesson14/RealmViewController.swift b/Lesson14/Lesson14/RealmViewController.swift deleted file mode 100644 index 4028b17..0000000 --- a/Lesson14/Lesson14/RealmViewController.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// RealmViewController.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTTableViewManager -import RxSwift -import RxCocoa - -class RealmViewController: UIViewController, DTTableViewManageable { - - @IBOutlet weak var tableView: UITableView! - @IBOutlet weak var addTaskButton: UIButton! - - private var counterTask: Int = 1 - - override func viewDidLoad() { - super.viewDidLoad() - - manager.memoryStorage.setItems(RealmPersistence.storage.getAllTask()) - counterTask = RealmPersistence.storage.getCountTasks() + 1 - - manager.register(ToDoListTableViewCell.self) - configureCells() - addTaskButton.layer.cornerRadius = addTaskButton.bounds.width / 2 - } - - private func configureCells() { - manager.configure(ToDoListTableViewCell.self) { cell, model, _ in - cell.compliteTaskButton.rx.controlEvent(.touchUpInside).subscribe(onNext: { [unowned cell, unowned model] _ in - cell.setComplite() - RealmPersistence.storage.changeTask(task: model, description: nil, isComplited: true) - }).disposed(by: cell.disposeBag) - - cell.descriptionTaskTextView.rx.text.asObservable().subscribe(onNext: { [unowned model] text in - RealmPersistence.storage.changeTask(task: model, description: text, isComplited: nil) - }).disposed(by: cell.disposeBag) - } - - manager.didSelect(ToDoListTableViewCell.self) { cell, _, _ in - cell.setSelected(false, animated: true) - } - } - - @IBAction func addButtonClick(_ sender: Any) { - let task = TaskRealmEntity() - task.name = "Задача №\(counterTask)" - counterTask += 1 - manager.memoryStorage.addItem(task) - RealmPersistence.storage.addTask(task: task) - } -} diff --git a/Lesson14/Lesson14/SceneDelegate.swift b/Lesson14/Lesson14/SceneDelegate.swift deleted file mode 100644 index 67e8e45..0000000 --- a/Lesson14/Lesson14/SceneDelegate.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// SceneDelegate.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - - var window: UIWindow? - - - @available(iOS 13.0, *) - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). - guard let _ = (scene as? UIWindowScene) else { return } - } - - @available(iOS 13.0, *) - func sceneDidDisconnect(_ scene: UIScene) { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). - } - - @available(iOS 13.0, *) - func sceneDidBecomeActive(_ scene: UIScene) { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. - } - - @available(iOS 13.0, *) - func sceneWillResignActive(_ scene: UIScene) { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). - } - - @available(iOS 13.0, *) - func sceneWillEnterForeground(_ scene: UIScene) { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. - } - - @available(iOS 13.0, *) - func sceneDidEnterBackground(_ scene: UIScene) { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. - - // Save changes in the application's managed object context when the application transitions to the background. - (UIApplication.shared.delegate as? AppDelegate)?.saveContext() - } - - -} - diff --git a/Lesson14/Lesson14/ToDoListTableViewCell.swift b/Lesson14/Lesson14/ToDoListTableViewCell.swift deleted file mode 100644 index df36d43..0000000 --- a/Lesson14/Lesson14/ToDoListTableViewCell.swift +++ /dev/null @@ -1,140 +0,0 @@ -// -// ToDoListTableViewCell.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit -import DTModelStorage -import SnapKit -import RxSwift - -class ToDoListTableViewCell: UITableViewCell, ModelTransfer { - typealias ModelType = TaskRealmEntity - var model: ModelType! - - private let disableColor: UIColor = UIColor.black.withAlphaComponent(0.1) - - private var isComplite = false { - didSet { - if isComplite { - nameTaskLabel.attributedText = setStruckThroughText(text: nameTaskLabel.text) - dateCreateTaskLabel.attributedText = setStruckThroughText(text: dateCreateTaskLabel.text) - descriptionTaskTextView.isEditable = false - descriptionTaskTextView.backgroundColor = disableColor - compliteTaskButton.isEnabled = false - compliteTaskButton.setTitleColor(.black, for: .normal) - compliteTaskButton.backgroundColor = disableColor - } - } - } - - var disposeBag = DisposeBag() - - private lazy var nameTaskLabel = UILabel() - private lazy var dateCreateTaskLabel = UILabel() - - lazy var descriptionTaskTextView: UITextView = { - let textView = UITextView() - textView.layer.borderWidth = 1 - textView.layer.borderColor = UIColor.black.cgColor - return textView - }() - - lazy var compliteTaskButton: UIButton = { - let button = UIButton() - button.setTitle("✓", for: .normal) - button.setTitleColor(.white, for: .normal) - button.backgroundColor = .systemBlue - button.layer.cornerRadius = 15 - return button - }() - - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { - super.init(style: style, reuseIdentifier: reuseIdentifier) - - setupCell() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupCell() { - contentView.addSubview(nameTaskLabel) - contentView.addSubview(dateCreateTaskLabel) - contentView.addSubview(descriptionTaskTextView) - contentView.addSubview(compliteTaskButton) - - setupConstraint() - } - - private func setStruckThroughText(text: String?) -> NSAttributedString? { - guard let text = text else { - return nil - } - let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text) - attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length)) - return attributeString - } - - func update(with model: TaskRealmEntity) { - self.model = model - nameTaskLabel.text = self.model.name - dateCreateTaskLabel.text = convertDate(date: self.model.createdAt) - descriptionTaskTextView.text = self.model.notes - isComplite = self.model.isCompleted - } - - func setComplite() { - isComplite = true - } - - private func convertDate(date: NSDate) -> String { - let formatter = DateFormatter() - // initially set the format based on your datepicker date / server String - formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - - let myString = formatter.string(from: date as Date) // string purpose I add here - // convert your string to date - let yourDate = formatter.date(from: myString) - //then again set the date format whhich type of output you need - formatter.dateFormat = "dd MMMM yyyy HH:mm" - // again convert your date to string - return formatter.string(from: yourDate!) - } - - private func setupConstraint() { - nameTaskLabel.snp.makeConstraints { make in - make.top.leading.equalToSuperview().inset(16) - } - - compliteTaskButton.snp.makeConstraints { make in - make.top.equalTo(nameTaskLabel.snp.top) - make.trailing.equalToSuperview().inset(16) - make.leading.greaterThanOrEqualTo(nameTaskLabel.snp.trailing).offset(16) - make.bottom.lessThanOrEqualTo(descriptionTaskTextView.snp.top).offset(-8) - make.height.width.equalTo(30) - } - - dateCreateTaskLabel.snp.makeConstraints { make in - make.top.equalTo(nameTaskLabel.snp.bottom).offset(8) - make.trailing.equalTo(nameTaskLabel.snp.trailing) - make.leading.equalToSuperview().inset(16) - } - - descriptionTaskTextView.snp.makeConstraints { make in - make.top.equalTo(dateCreateTaskLabel.snp.bottom).offset(8) - make.leading.trailing.bottom.equalToSuperview().inset(16) - make.height.equalTo(100) - } - } - - override func prepareForReuse() { - super.prepareForReuse() - - disposeBag = DisposeBag() - } -} diff --git a/Lesson14/Lesson14/ViewController.swift b/Lesson14/Lesson14/ViewController.swift deleted file mode 100644 index 6e3e827..0000000 --- a/Lesson14/Lesson14/ViewController.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// ViewController.swift -// Lesson14 -// -// Created by Михаил Беленко on 04.02.2020. -// Copyright © 2020 Михаил Беленко. All rights reserved. -// - -import UIKit - -class ViewController: UIViewController { - - @IBOutlet weak var lastNameTextField: UITextField! - @IBOutlet weak var firstNameTextField: UITextField! - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - lastNameTextField.text = UserDefaultsPersistence.storage.lastName - firstNameTextField.text = UserDefaultsPersistence.storage.firstName - } - - @IBAction func lastNameChange(_ sender: Any) { - UserDefaultsPersistence.storage.lastName = lastNameTextField.text - } - - @IBAction func firstNameChange(_ sender: Any) { - UserDefaultsPersistence.storage.firstName = firstNameTextField.text - } -} - diff --git a/Lesson14/Pods/DTModelStorage/LICENSE b/Lesson14/Pods/DTModelStorage/LICENSE deleted file mode 100644 index d94be90..0000000 --- a/Lesson14/Pods/DTModelStorage/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Denys Telezhkin - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Lesson14/Pods/DTModelStorage/README.md b/Lesson14/Pods/DTModelStorage/README.md deleted file mode 100644 index e3f1049..0000000 --- a/Lesson14/Pods/DTModelStorage/README.md +++ /dev/null @@ -1,310 +0,0 @@ -[![Build Status](https://travis-ci.org/DenTelezhkin/DTModelStorage.svg?branch=master)](https://travis-ci.org/DenTelezhkin/DTModelStorage) -[![codecov.io](http://codecov.io/github/DenTelezhkin/DTModelStorage/coverage.svg?branch=master)](http://codecov.io/github/DenTelezhkin/DTModelStorage?branch=master) -[![CocoaPods compatible](https://img.shields.io/cocoapods/v/DTModelStorage.svg)](https://cocoapods.org/pods/DTModelStorage) -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg)]() - -DTModelStorage -================ - -> This project is used as a dependency by [DTTableViewManager](https://github.com/DenTelezhkin/DTTableViewManager) and [DTCollectionViewManager](https://github.com/DenTelezhkin/DTCollectionViewManager) - great tools for UITableView and UICollectionView management. - -- [x] Support for any data structure - class, struct, enum, tuple -- [x] Support for automatic diffing in section -- [x] Support for diffable datasources in iOS 13 -- [x] Protocol-oriented implementation with generic and associated types -- [x] Powerful events system for storage consumers. -- [x] High test coverage -- [x] [Complete documentation](https://dentelezhkin.github.io/DTModelStorage/) - -What this is all about? -============== - -The goal of the project is to provide storage classes for datasource based controls. Let's take UITableView, for example. It's datasource methods mostly relates on following: - -* sections -* items in sections -* section headers and footers - -Now, if we look on `UICollectionView`, that stuff does not change. And probably any kind of datasource based control can be adapted to use the same terminology. So, instead of reinventing the wheel every time, let's try to implement universal storage classes, that would fit any control. - -`DTModelStorage` supports 5 storage classes: -* Single section storage -* Memory storage -* CoreData storage -* Realm storage -* Storage for diffable datasources - -`DTModelStorage` provides convenience methods to be used with `UITableView` or `UICollectionView`, but does not force any specific use, and does not imply, which UI components are compatible with it. However, storage classes are designed to work with "sections" and "items", which generally means some kind of table or collection of items. - -`DTModelStorage` defines `ModelTransfer` protocol, that allows transferring your data model to interested parties. This can be used for example for updating `UITableViewCell`. Thanks to associated `ModelType` of the protocol it is possible to transfer your model without any type casts. - -Requirements -============ - -* Xcode 10 and higher -* Swift 4.1 and higher -* iOS 8 and higher / tvOS 9.0 and higher - -Installation -=========== - -### Swift Package Manager (requires Xcode 11) - -* Add package into Project settings -> Swift Packages - -### [CocoaPods](https://cocoapods.org): - -pod 'DTModelStorage', '~> 8.0' - -### [Carthage](https://github.com/Carthage/Carthage) - -github "DenTelezhkin/DTModelStorage" "8.0" - -MemoryStorage -================ -`MemoryStorage` encapsulates storage of data models in memory. It's basically Array of `SectionModel` items, which contain array of items for current section. - -```swift -let storage = MemoryStorage() -``` - -#### Adding items - -```swift -storage.addItem(model) -storage.addItem(model, toSection: 0) - -storage.addItems([model1,model2]) -storage.addItems([model1,model2], toSection:0) - -try? storage.insertItem(model, to: indexPath) -``` - -#### Remove / replace / Reload - -```swift -try? storage.removeItem(model) -storage.removeItems([model1,model2]) -storage.removeItems(at:indexPaths) - -try? storage.replaceItem(model1, with: model2) - -storage.reloadItem(model1) -``` - -#### Managing sections - -```swift -storage.deleteSections(NSIndexSet(index: 1)) -``` - -#### Retrieving items - -```swift -let item = storage.item(at:NSIndexPath(forItem:1, inSection:0) - -let indexPath = storage.indexPath(forItem:model) - -let itemsInSection = storage.items(inSection:0) - -let section = storage.section(atIndex:0) -``` - -#### Updating manually - -Sometimes you may need to update batch of sections, remove all items, and add new ones. For those massive updates you don't actually need to update interface until update is finished. Wrap your updates in single block and pass it to updateWithoutAnimations method: - -```swift -storage.updateWithoutAnimations { - // Add multiple rows, or another batch of edits -} -// Calling reloadData is mandatory after calling this method. or you will get crash runtime -``` - -For reordering of items, when animation is not needed, you can call `moveItemWithoutAnimation(from:to:)` method: - -```swift -storage.moveItemWithoutAnimation(from: sourceIndexPath, to: destinationIndexPath) -``` - -## Supplementary model providers - -All 5 implemented storages have a single supplementary model provider API, that consists of three closures: - -* `headerModelProvider` -* `footerModelProvider` -* `supplementaryModelProvider` - -`supplementaryModelProvider` closure setter has been overridden to allow calling `headerModelProvider` and `footerModelProvider`. So, for example, if closures are setup in the following way: - -```swift -storage.headerModelProvider = { index in [1,2,3][index] } -storage.supplementaryModelProvider = { kind, index in [4,5,6][index.item] } -storage.supplementaryHeaderKind = "Foo" -``` - -Then supplementary providers will work as shown below: - -```swift -storage.supplementaryModel(ofKind: "Foo", forSectionAt: IndexPath(item: 0, section:0)) // 1 -storage.supplementaryModel(ofKind: "Bar", forSectionAt: IndexPath(item: 0, section:0)) // 4 -``` - -ProxyDiffableDataSourceStorage -================ - -`ProxyDiffableDataSourceStorage` is a proxy class used by `DTTableViewManager/DTCollectionViewManager` frameworks to support diffable datasources in iOS 13. - -All it does, it contain wrapper closures, that redirect datasource questions to diffable datasource object. Additionally, It has the same supplementary model provider logic that all storages have. - -SingleSectionStorage -================ - -While sometimes you need such fine-grained control, that `MemoryStorage` provides, the most often use case for this library is just showing a collection of items, for example array of posts from social network, or search results with a single entity. - -In this case, mostly used methods from `MemoryStorage` are `setItems` and `addItems`, because in this case you probably don't need any other methods. What you may want, however, is an ability to automatically calculate diffs between old and new state to be able to animate UI without the need to call `reloadData`. That's where `SingleSectionStorage` comes in. - -But before showing any usage examples, let's talk about diffing a little bit. There are a lot of great collection differs outhere, and `DTModelStorage` is not aimed to providing another one. Instead, it provides an API to work with currently available differs. - -#### Algorithms - -There are a lot of community-built algorithms to compute diff between two collections, for example here's list of frameworks that are built using Paul Heckel's `A Technique for Isolating Differences Between Files`: - -- [HeckelDiff](https://github.com/mcudich/HeckelDiff) -- [ListDiff](https://github.com/lxcid/ListDiff) - port of [IGListKit's diffing algorithm](https://github.com/Instagram/IGListKit) to Swift -- [PHDiff](https://github.com/andre-alves/PHDiff) - -There are other algorithms and implementations available, for example: - -- [Dwifft](https://github.com/jflinter/Dwifft) - Longest common subsequence algorithm -- [Differ](https://github.com/tonyarnold/Differ) - Longest common subsequence algorithm -- [Changeset](https://github.com/osteslag/Changeset) - Wagner-Fischer algorithm (specific implementation of Levenstein algorithm). - -Because algorithms are built differently, but have some common traits, `SingleSectionStorage` implements two concrete subclasses, that work with algorithms with `Equatable` elements and algorithms that work with `Hashable` elements - `SingleSectionEquatableStorage` and `SingleSectionHashableStorage`. - -#### Algorithm adapter - -To work with specific algorithm, you would need to create a thin adapter, that converts results of algorithm work to models, compatible with `DTModelStorage`. Here are some examples of how this can be done: - -- [Adapter for Dwifft](https://github.com/DenTelezhkin/DTModelStorage/blob/master/Tests/Specs/SingleSectionStorageTestCase.swift#L18-L30) -- [Adapter for HeckelDiff](https://github.com/DenTelezhkin/DTModelStorage/blob/master/Tests/Specs/SingleSectionStorageTestCase.swift#L32-L48) -- [Adapter for Changeset](https://github.com/DenTelezhkin/DTTableViewManager/blob/master/Example/Example%20controllers/AutoDiffSearchViewController.swift#L14-L26) - -#### Example - -After adapter has been built, you need to implement `EntityIdentifiable` protocol on your data models to provide way to identify models: - -```swift -extension Post : EntityIdentifiable { - public var identifier: AnyHashable { return id } -} -``` - -Create storage: - -```swift -let storage = SingleSectionEquatableStorage(items: arrayOfPosts, differ: ChangesetDiffer()) -``` - -Set new array of items and automatically calculate all diffs: - -```swift -storage.setItems(newPosts) -``` - -Full example of automatically animating items in `UITableView` can be seen in [DTTableViewManager repo](https://github.com/DenTelezhkin/DTTableViewManager/blob/master/Example/Example%20controllers/AutoDiffSearchViewController.swift) - -#### Adding items - -When you show list of items, common task is to add new loaded items to this list (for example load more content). Doing that is really simple: - -```swift -storage.addItems(newItems) -``` - -Sometimes you may want to customize how items are accumulated in resulting collection of items. For example when content changed in time between first page request and second page request in load-more scenario. If back-end does not handle this for iOS side, you may want to build handling of such cases on client side. To do that, `DTModelStorage` provides `AccumulationStrategy` protocol, that consists of single method: - -```swift -protocol AccumulationStrategy { - func accumulate(oldItems: [T], newItems: [T]) -> [T] -} -``` - -This strategy determines how new collection of items will be formed. `DTModelStorage` provides three concrete implementations of this protocol: - -- `AdditiveAccumulationStrategy` - default strategy, that simply adds oldItems to newItemsArray. -- `UpdateOldValuesAccumulationStrategy` - replaces old values with new values from `newItems` array - uniqueness is determined by `Identifiable` `identifier` property -- `DeleteOldValuesAccumulationStrategy` - deletes old items, new values remain in new location as returned by `newArray` - uniqueness is determined by `EntityIdentifiable` `identifier` property. - -To use any of the strategies, just call `addItems` method with additional parameter: - -```swift -storage.addItems(newItems, UpdateOldValuesAccumulationStrategy()) -``` - -#### Several model types in SingleSectionStorage - -`SingleSectionStorage` class uses generics to determine it's item type. While it provides compile-time guarantees for item type, it unfortunately prevents using several model types in `SingleSectionStorage` using `Any` type or a protocol. To do that, Swift needs to implement feature called [Generalized existentials](https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#existentials). Unfortunately, at the moment of writing (Xcode 10, Swift 4.2) this feature is not implemented. - -Therefore, to support several data models type in `SingleSection` we can use technique called type-erasing. We can build generic wrapper class, that implements all protocols that are required, but actually accepts `Any` value: - -```swift -struct AnyIdentifiableEquatable: Identifiable, Equatable { - let value : Any - let equals: (Any) -> Bool - let identifier: AnyHashable - - init(_ value: T) { - self.value = value - equals = { - guard let instance = $0 as? T else { return false } - return instance == value - } - identifier = value.identifier - } - - static func == (lhs: AnyIdentifiableEquatable, rhs: AnyIdentifiableEquatable) -> Bool { - return lhs.equals(rhs.value) || rhs.equals(lhs.value) - } -} -``` - -This way you can create a storage, that accepts any number of data models: - -```swift -let typeErasedInstances = [AnyIdentifiableEquatable(Foo()), AnyIdentifiableEquatable(Bar())] -let storage = SingleSectionEquatableStorage(items: typeErasedInstances, differ: DwifftDiffer()) -``` - -Quite ugly, I know. But that seems like the only option that is possible today. - -CoreDataStorage -================ - -`CoreDataStorage` is meant to be used with `NSFetchedResultsController`. It automatically monitors all `NSFetchedResultsControllerDelegate` methods and and calls delegate with appropriate updates. - -```swift -let storage = CoreDataStorage(fetchedResultsController: controller) -``` - -Any section in `CoreDataStorage` conform to `NSFetchedResultsSectionInfo` protocol, however `DTModelStorage` extends them to be `Section` protocol compatible. This way CoreData sections and memory sections have the same interface. - -## RealmStorage - -`RealmStorage` class is made to work with [realm.io](https://realm.io) databases. It works with sections, that contain Realm.Results object. - -Creating storage and filling it with results is very easy: - -``` -let results = try! Realm().objects(Dog) - -let storage = RealmStorage() -storage.addSection(with:results) -``` - -That's it! Results are automatically monitored, and refreshed, if Realm objects change. - -**Note** You should not use RealmStorage with multiple sections, because it may lead to crashes when simultaneous UI updates make UI state inconsistent(https://github.com/DenTelezhkin/DTModelStorage/issues/21). - -One possible solution to this are diffable datasources in iOS 13, where you should be able to construct all sections manually thus avoiding crashes. diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift deleted file mode 100644 index 8f5ebca..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AccumulationStrategy.swift +++ /dev/null @@ -1,128 +0,0 @@ -// -// AccumulationStrategy.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 21.09.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// Strategy to accumulate `oldItems` and `newItems` into resulting array. -public protocol AccumulationStrategy { - - /// Accumulate `oldItems` and `newItems` into resulting array. - /// - /// - Parameters: - /// - oldItems: array of items, already present in storage - /// - newItems: array of items, that will be accumulated - /// - Returns: Accumulated items array. - func accumulate(oldItems: [T], newItems: [T]) -> [T] -} - -/// Strategy, that adds new items to old items, without comparing their identifiers. -/// This strategy is used by default by `addItems` method of `SingleSectionStorage`. -public struct AdditiveAccumulationStrategy: AccumulationStrategy { - - /// Creates additive accumulation strategy - public init() {} - - /// Accumulate `oldItems` and `newItems` into resulting array by appending `newItems` to `oldItems`. - /// - /// - Parameters: - /// - oldItems: array of items, already present in storage - /// - newItems: array of items, that will be accumulated - /// - Returns: Array, that consists of old items and new items. - public func accumulate(oldItems: [T], newItems: [T]) -> [T] where T : EntityIdentifiable { - return oldItems + newItems - } -} - -/// Strategy to update old values with a new ones, using old items position. -public struct UpdateOldValuesAccumulationStrategy: AccumulationStrategy { - - /// Creates update old values accumulation strategy - public init() {} - - /// Accumulate `oldItems` and `newItems` into resulting array by updating old items with new values, using old item positions in collection. - /// Identity of item is determined by `identifier` property. - /// - /// - Parameters: - /// - oldItems: array of items, already present in storage - /// - newItems: array of items, that will be accumulated - /// - Returns: Accumulated items array, that contains old items updated with new values and new unique values. - public func accumulate(oldItems: [T], newItems: [T]) -> [T] where T : EntityIdentifiable { - var newArray = oldItems - var existingIdentifiers = [AnyHashable:Int]() - for (index, oldItem) in oldItems.enumerated() { - existingIdentifiers[oldItem.identifier] = index - } - for (index, newItem) in newItems.enumerated() { - let newIdentifier = newItem.identifier - if let oldIndex = existingIdentifiers[newIdentifier] { - // Detected duplicate - newArray[oldIndex] = newItem - } else { - existingIdentifiers[newIdentifier] = index - newArray.append(newItem) - } - } - return newArray - } -} - -/// Strategy to delete old values when accumulating newItems -public struct DeleteOldValuesAccumulationStrategy: AccumulationStrategy { - - /// Creates strategy - public init() {} - - /// Accumulate `oldItems` and `newItems` into resulting array by deleting old items, that have new values in `newItems`, from `oldItems`. - /// This way old duplicated values are basically moved to their location in `newItems` and updated with new data. - /// - /// - Parameters: - /// - oldItems: array of items, already present in storage - /// - newItems: array of items, that will be accumulated - /// - Returns: Accumulated items array. - public func accumulate(oldItems: [T], newItems: [T]) -> [T] where T : EntityIdentifiable { - var newArray = oldItems - var existingIdentifiers = [AnyHashable:Int]() - var indexesToDelete = [Int]() - for (index, oldItem) in oldItems.enumerated() { - existingIdentifiers[oldItem.identifier] = index - } - for (index, newItem) in newItems.enumerated() { - let newIdentifier = newItem.identifier - if let oldIndex = existingIdentifiers[newIdentifier] { - // Detected duplicate - newArray.append(newItem) - - // Old item will be deleted later - indexesToDelete.append(oldIndex) - } else { - existingIdentifiers[newIdentifier] = index - newArray.append(newItem) - } - } - - indexesToDelete.sorted().reversed().forEach { newArray.remove(at: $0) } - return newArray - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift deleted file mode 100644 index 08589e4..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/AnomalyHandler.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// AnomalyHandler.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 28.04.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// `AnomalyHandler` protocol serves as interface for various anomaly handlers. -/// - SeeAlso: `MemoryStorageAnomaly`, `DTTableViewManagerAnomaly`, `DTCollectionViewManagerAnomaly`. -public protocol AnomalyHandler: class { - associatedtype Anomaly : Equatable, CustomDebugStringConvertible - var anomalyAction : (Anomaly) -> Void { get set } - func reportAnomaly(_ anomaly: Anomaly) - func silenceAnomaly(_ anomaly: Anomaly) -} - -extension AnomalyHandler { - /// Executes anomalyAction for each reported anomaly. - public func reportAnomaly(_ anomaly: Anomaly) { - anomalyAction(anomaly) - } - - /// Silences specific anomaly, anomalyHandler for it will never be called. - public func silenceAnomaly(_ anomalyToSilence: Anomaly) { - let tempAnomalyAction = anomalyAction - anomalyAction = { anomaly in - if anomaly == anomalyToSilence { return } - tempAnomalyAction(anomaly) - } - } - - /// Silences anomalies, based on provided `condition`. If this condition returns true, anomalyHandler will not be called for this anomaly. - public func silenceAnomaly(usingCondition condition: @escaping (Anomaly) -> Bool) { - let tempAnomalyAction = anomalyAction - anomalyAction = { anomaly in - if condition(anomaly) { return } - tempAnomalyAction(anomaly) - } - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift deleted file mode 100644 index d36129f..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/BaseStorage.swift +++ /dev/null @@ -1,137 +0,0 @@ -// -// BaseStorage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -/// Suggested supplementary kind for UITableView header -public let DTTableViewElementSectionHeader = "DTTableViewElementSectionHeader" -/// Suggested supplementary kind for UITableView footer -public let DTTableViewElementSectionFooter = "DTTableViewElementSectionFooter" - -/// `BaseSupplementaryStorage` is a base class, that implements common functionality for `SupplementaryStorage` protocol and serves as a base class for `MemoryStorage`, `CoreDataStorage`, `SingleSectionStorage`, `RealmStorage`. -open class BaseSupplementaryStorage: NSObject, SupplementaryStorage { - - /// Returns a header model for specified section index or nil. - open var headerModelProvider: ((Int) -> Any?)? - - /// Returns a footer model for specified section index or nil - open var footerModelProvider: ((Int) -> Any?)? - - private lazy var _supplementaryModelProvider: ((String, IndexPath) -> Any?)? = { [weak self] kind, indexPath in - if let headerModel = self?.headerModelProvider, self?.supplementaryHeaderKind == kind { - return headerModel(indexPath.section) - } - if let footerModel = self?.footerModelProvider, self?.supplementaryFooterKind == kind { - return footerModel(indexPath.section) - } - return nil - } - - /// Returns supplementary model for specified section indexPath and supplementary kind, or nil. Setter for this property is overridden to allow calling `headerModelProvider` and `footerModelProvider` closures. - open var supplementaryModelProvider: ((String, IndexPath) -> Any?)? { - get { - return _supplementaryModelProvider - } - set { - _supplementaryModelProvider = { [weak self] kind, indexPath in - if let headerModel = self?.headerModelProvider, self?.supplementaryHeaderKind == kind { - return headerModel(indexPath.section) - } - if let footerModel = self?.footerModelProvider, self?.supplementaryFooterKind == kind { - return footerModel(indexPath.section) - } - return newValue?(kind, indexPath) - } - } - } - - /// Supplementary kind for header in current storage - open var supplementaryHeaderKind: String? - - /// Supplementary kind for footer in current storage - open var supplementaryFooterKind: String? -} - -/// `StorageUpdating` protocol is used to transfer data storage updates. -public protocol StorageUpdating : class -{ - /// Transfers data storage updates. - /// - /// Object, that implements this method, may react to received update by updating UI for current storage. - func storageDidPerformUpdate(_ update: StorageUpdate) - - /// Method is called when UI needs to be fully updated for data storage changes. - func storageNeedsReloading() -} - -/// Base class for storage classes -open class BaseUpdateDeliveringStorage: BaseSupplementaryStorage -{ - /// Current update - open var currentUpdate: StorageUpdate? - - /// Batch updates are in progress. If true, update will not be finished. - open var batchUpdatesInProgress = false - - /// Delegate for storage updates - open weak var delegate: StorageUpdating? - - /// Performs update `block` in storage. After update is finished, delegate will be notified. - /// Parameter block: Block to execute - /// - Note: This method allows to execute several updates in a single batch. It is similar to UICollectionView method `performBatchUpdates:`. - /// - Warning: Performing mutually exclusive updates inside block can cause application crash. - open func performUpdates( _ block: () -> Void) { - batchUpdatesInProgress = true - startUpdate() - block() - batchUpdatesInProgress = false - finishUpdate() - } - - /// Starts update in storage. - /// - /// This creates StorageUpdate instance and stores it into `currentUpdate` property. - open func startUpdate(){ - if self.currentUpdate == nil { - self.currentUpdate = StorageUpdate() - } - } - - /// Finishes update. - /// - /// Method verifies, that update is not empty, and sends updates to the delegate. After this method finishes, `currentUpdate` property is nilled out. - open func finishUpdate() - { - guard batchUpdatesInProgress == false else { return } - defer { currentUpdate = nil } - if let update = currentUpdate { - if update.isEmpty { - return - } - delegate?.storageDidPerformUpdate(update) - } - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift deleted file mode 100644 index f4c907f..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/CoreDataStorage.swift +++ /dev/null @@ -1,162 +0,0 @@ -// -// CoreDataStorage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import CoreData -import UIKit - -#if swift(>=4.2) -/// Compatibility constant to support Swift 4.2 and higher -public let DTCollectionViewElementSectionHeader = UICollectionView.elementKindSectionHeader -/// Compatibility constant to support Swift 4.2 and higher -public let DTCollectionViewElementSectionFooter = UICollectionView.elementKindSectionFooter -#else -/// Compatibility constant to support Swift 4.1 and lower -public let DTCollectionViewElementSectionHeader = UICollectionElementKindSectionHeader -/// Compatibility constant to support Swift 4.1 and lower -public let DTCollectionViewElementSectionFooter = UICollectionElementKindSectionFooter -#endif - -/// This class represents model storage in CoreData -/// It uses NSFetchedResultsController to monitor all changes in CoreData and automatically notify delegate of any changes -open class CoreDataStorage : BaseUpdateDeliveringStorage, Storage, NSFetchedResultsControllerDelegate -{ - /// Fetched results controller of storage - public let fetchedResultsController: NSFetchedResultsController - - @available(*, unavailable, message: "Please use storage.supplementaryModel closure to customize section supplementaries") - /// Property, which defines, for which supplementary kinds NSFetchedResultsController section name should be used. - /// Defaults to [DTTableViewElementSectionHeader,UICollectionElementKindSectionHeader] - /// - Discussion: This is useful, for example, if you want section footers intead of headers to have section name in them. - open var displaySectionNameForSupplementaryKinds = [DTTableViewElementSectionHeader, DTCollectionViewElementSectionHeader] - - /// Initialize CoreDataStorage with NSFetchedResultsController - /// - Parameter fetchedResultsController: fetch results controller - public init(fetchedResultsController: NSFetchedResultsController) - { - self.fetchedResultsController = fetchedResultsController - super.init() - self.fetchedResultsController.delegate = self - headerModelProvider = { index in - if let sections = self.fetchedResultsController.sections - { - return sections[index].name - } - return nil - } - } - - /// Returns number of sections in storage. - open func numberOfSections() -> Int { - return fetchedResultsController.sections?.count ?? 0 - } - - /// Returns number of items in a given section - /// - Parameter section: given section. - open func numberOfItems(inSection section: Int) -> Int { - if (fetchedResultsController.sections?.count ?? 0) > section { - return fetchedResultsController.sections?[section].numberOfObjects ?? 0 - } - return 0 - } - - // MARK: - Storage - - /// Retrieve object at index path from `CoreDataStorage` - /// - Parameter indexPath: IndexPath for object - /// - Returns: model at indexPath or nil, if item not found - open func item(at indexPath: IndexPath) -> Any? { - return fetchedResultsController.object(at: indexPath) - } - - // MARK: - NSFetchedResultsControllerDelegate - - /// NSFetchedResultsController is about to start changing content - we'll start monitoring for updates. - @objc open func controllerWillChangeContent(_ controller: NSFetchedResultsController) { - self.startUpdate() - } - - /// React to specific change in NSFetchedResultsController - @objc open func controller(_ controller: NSFetchedResultsController, - didChange anObject: Any, - at indexPath: IndexPath?, - for type: NSFetchedResultsChangeType, - newIndexPath: IndexPath?) - { - switch type - { - case .insert: - if let new = newIndexPath { - currentUpdate?.objectChanges.append((.insert, [new])) - } - case .delete: - if let indexPath = indexPath { - currentUpdate?.objectChanges.append((.delete, [indexPath])) - } - case .move: - if let indexPath = indexPath, let newIndexPath = newIndexPath { - if indexPath != newIndexPath { - currentUpdate?.objectChanges.append((.delete, [indexPath])) - currentUpdate?.objectChanges.append((.insert, [newIndexPath])) - } else { - currentUpdate?.objectChanges.append((.update, [indexPath])) - currentUpdate?.updatedObjects[indexPath] = anObject - } - } - case .update: - if let indexPath = indexPath { - if let newIndexPath = newIndexPath, indexPath != newIndexPath { - currentUpdate?.objectChanges.append((.delete, [indexPath])) - currentUpdate?.objectChanges.append((.insert, [newIndexPath])) - } else { - currentUpdate?.objectChanges.append((.update, [indexPath])) - currentUpdate?.updatedObjects[indexPath] = anObject - } - } - default: () - } - } - - - @objc - /// React to changed section in NSFetchedResultsController. - open func controller(_ controller: NSFetchedResultsController, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) - { - switch type { - case .insert: - currentUpdate?.sectionChanges.append((.insert, [sectionIndex])) - case .delete: - currentUpdate?.sectionChanges.append((.delete, [sectionIndex])) - case .update: - currentUpdate?.sectionChanges.append((.update, [sectionIndex])) - default: () - } - } - - /// Finish update from NSFetchedResultsController - @objc open func controllerDidChangeContent(_ controller: NSFetchedResultsController) { - self.finishUpdate() - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift deleted file mode 100644 index 1f5e342..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/EventReactions.swift +++ /dev/null @@ -1,188 +0,0 @@ -// -// UIReactions.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 29.11.15. -// Copyright © 2015 Denys Telezhkin. All rights reserved. -// -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -//swiftlint:disable large_tuple - -/// Data holder for reaction -open class EventReaction { - - /// view -> model mapping of this reaction - public let viewModelMapping: ViewModelMapping - - /// 3 arguments reaction block with all arguments type-erased. - open var reaction : ((Any, Any, Any) -> Any)? - - /// Objective-C method signature - public let methodSignature: String - - /// Creates reaction with `signature`. - public init(signature: String, viewType: ViewType, viewClass: T.Type) { - self.methodSignature = signature - viewModelMapping = ViewModelMapping(viewType: viewType, viewClass: T.self, mappingBlock: nil) - } - - /// Creates reaction with `signature`, `viewType` and `modelType`. - public init(signature: String, viewType: ViewType, modelType: T.Type) { - self.methodSignature = signature - viewModelMapping = ViewModelMapping.eventsModelMapping(viewType: viewType, modelClass: T.self) - } - - /// Creates reaction with type-erased T and T.ModelType into Any types. - open func makeReaction(_ block: @escaping (T, T.ModelType, IndexPath) -> U) { - reaction = { cell, model, indexPath in - guard let model = model as? T.ModelType, - let indexPath = indexPath as? IndexPath, - let cell = cell as? T - else { - return 0 - } - return block(cell, model, indexPath) - } - } - - /// Creates reaction with type-erased T into Any type. - open func makeReaction(_ block: @escaping (T, IndexPath) -> U) { - reaction = { cell, model, indexPath in - guard let model = model as? T, - let indexPath = indexPath as? IndexPath else { - return 0 - } - return block(model, indexPath) - } - } - - /// Performs reaction with `arguments`. - open func performWithArguments(_ arguments: (Any, Any, Any)) -> Any { - return reaction?(arguments.0, arguments.1, arguments.2) ?? 0 - } -} - -/// Subclass of `EventReaction`, tuned to work with 4 arguments. -open class FourArgumentsEventReaction: EventReaction { - - /// Type-erased reaction with 4 arguments - open var reaction4Arguments : ((Any, Any, Any, Any) -> Any)? - - /// Makes 4 argument reaction based on `View`. - open func make4ArgumentsReaction(_ block: @escaping (Argument, View, View.ModelType, IndexPath) -> ReturnType) { - reaction4Arguments = { argument, view, model, indexPath in - guard let model = model as? View.ModelType, - let indexPath = indexPath as? IndexPath, - let argument = argument as? Argument, - let view = view as? View else { return 0 } - return block(argument, view, model, indexPath) - } - } - - /// Creates FourArgumentsEventReaction for `viewClass` - public override init(signature: String, viewType: ViewType, viewClass: T.Type) { - super.init(signature: signature, viewType: viewType, viewClass: viewClass) - } - - /// Creates FourArgumentsEventReaction for `modelType` - public override init(signature: String, viewType: ViewType, modelType: T.Type) { - super.init(signature: signature, viewType: viewType, modelType: modelType) - } - - /// Performs reaction with `arguments`. - open func performWithArguments(_ arguments: (Any, Any, Any, Any)) -> Any { - return reaction4Arguments?(arguments.0, arguments.1, arguments.2, arguments.3) ?? 0 - } -} - -/// Subclass of `EventReaction`, tuned to work with 5 arguments. -open class FiveArgumentsEventReaction: EventReaction { - - /// Type-erased reaction with 5 arguments - open var reaction5Arguments : ((Any, Any, Any, Any, Any) -> Any)? - - /// Makes 5 argument reaction based on `View`. - open func make5ArgumentsReaction(_ block: @escaping (ArgumentOne, ArgumentTwo, View, View.ModelType, IndexPath) -> ReturnType) { - reaction5Arguments = { argumentOne, argumentTwo, view, model, indexPath in - guard let model = model as? View.ModelType, - let indexPath = indexPath as? IndexPath, - let argument1 = argumentOne as? ArgumentOne, - let argument2 = argumentTwo as? ArgumentTwo, - let view = view as? View else { return 0 } - return block(argument1, argument2, view, model, indexPath) - } - } - - /// Creates FiveArgumentsEventReaction for `viewClass` - public override init(signature: String, viewType: ViewType, viewClass: T.Type) { - super.init(signature: signature, viewType: viewType, viewClass: viewClass) - } - - /// Creates FiveArgumentsEventReaction for `modelType` - public override init(signature: String, viewType: ViewType, modelType: T.Type) { - super.init(signature: signature, viewType: viewType, modelType: modelType) - } - - /// Performs reaction with `arguments`. - open func performWithArguments(_ arguments: (Any, Any, Any, Any, Any)) -> Any { - return reaction5Arguments?(arguments.0, arguments.1, arguments.2, arguments.3, arguments.4) ?? 0 - } -} - -extension Sequence where Self.Iterator.Element: EventReaction { - /// Searches for reaction using specified parameters. - public func reaction(of type: ViewType, - signature: String, - forModel model: Any, - view: UIView?) -> EventReaction? { - return first(where: { reaction in - guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { return false } - return reaction.viewModelMapping.viewType == type && - reaction.viewModelMapping.modelTypeCheckingBlock(unwrappedModel) && - view?.isKind(of: reaction.viewModelMapping.viewClass) ?? true && - reaction.methodSignature == signature - }) - } - - /// Performs reaction of `type`, `signature`, with `view`, `model` in `location`. - public func performReaction(of type: ViewType, signature: String, view: Any?, model: Any, location: Any) -> Any { - guard let reaction = reaction(of: type, signature: signature, forModel: model, view: view as? UIView) else { - return 0 - } - return reaction.performWithArguments((view ?? 0, model, location)) - } - - //swiftlint:disable function_parameter_count - /// Performs reaction of `type`, `signature`, with `argument`, `view`, `model` in `location`. - public func perform4ArgumentsReaction(of type: ViewType, signature: String, argument: Any, view: Any?, model: Any, location: Any) -> Any { - guard let reaction = reaction(of: type, signature: signature, forModel: model, view: view as? UIView) as? FourArgumentsEventReaction else { return 0 } - return reaction.performWithArguments((argument, view ?? 0, model, location)) - } - - /// Performs reaction of `type`, `signature`, with `firstArgument`, `secondArgument`, `view`, `model` in `location`. - public func perform5ArgumentsReaction(of type: ViewType, signature: String, firstArgument: Any, secondArgument: Any, view: Any?, model: Any, location: Any) -> Any { - guard let reaction = reaction(of: type, signature: signature, forModel: model, view: view as? UIView) as? FiveArgumentsEventReaction else { return 0 } - return reaction.performWithArguments((firstArgument, secondArgument, view ?? 0, model, location)) - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift deleted file mode 100644 index 01ca155..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage+UpdateWithoutAnimations.swift +++ /dev/null @@ -1,53 +0,0 @@ -// -// MemoryStorage+UpdateWithoutAnimations.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 11.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -extension MemoryStorage -{ - /// Runs `block` of actions without notifying self.delegate. - /// - /// You can think of this method as a way of "manual" management for memory storage. Typical usage would be multiple insertions/deletions etc., if you don't need any animations. You can batch any changes in block, and call reloadData on your UI component after this method was call. - /// - Note: You must call reloadData after calling this method, or you will get NSInternalInconsistencyException runtime, thrown by either UITableView or UICollectionView. - open func updateWithoutAnimations(_ block: () -> Void) - { - let delegate = self.delegate - let recordingDelegate = RecordingDelegate() - self.delegate = recordingDelegate - block() - recordingDelegate.updates.forEach { - $0.applyDeferredDatasourceUpdates() - } - self.delegate = delegate - } -} - -private class RecordingDelegate: StorageUpdating { - var updates: [StorageUpdate] = [] - - func storageDidPerformUpdate(_ update: StorageUpdate) { - updates.append(update) - } - - func storageNeedsReloading() {} -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift deleted file mode 100644 index 36fc0ab..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/MemoryStorage.swift +++ /dev/null @@ -1,660 +0,0 @@ -// -// MemoryStorage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 10.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// `MemoryStorageAnomaly` represents various errors and unwanted behaviors that can happen when using `MemoryStorage` class. -/// - SeeAlso: `DTTableViewManagerAnomaly`, `DTCollectionViewManagerAnomaly` -public enum MemoryStorageAnomaly: Equatable, CustomStringConvertible, CustomDebugStringConvertible { - - /// When inserting item to `indexPath`, there were only `countOfElementsInSection` items in section - case insertionIndexPathTooBig(indexPath: IndexPath, countOfElementsInSection: Int) - - /// When inserting batch of items, number of items and number of indexPaths was different - case batchInsertionItemCountMismatch(itemsCount: Int, indexPathsCount: Int) - - /// Attempt to replace item, that is not found in storage - case replaceItemFailedItemNotFound(itemDescription: String) - - /// Attempt to remove item, that is not found in storage - case removeItemFailedItemNotFound(itemDescription: String) - - /// Attempt to move item, that is not found in storage - case moveItemFailedItemNotFound(indexPath: IndexPath) - - /// Attempt to move item to too big `indexPath`. - case moveItemFailedIndexPathTooBig(indexPath: IndexPath, countOfElementsInSection: Int) - - /// Inconsistent indexPaths when moving item from `sourceIndexPath` to `destinationIndexPath`. - case moveItemFailedInvalidIndexPaths(sourceIndexPath: IndexPath, destinationIndexPath: IndexPath, sourceElementsInSection: Int, destinationElementsInSection: Int) - - /// Debug information for `MemoryStorageAnomaly`. - public var debugDescription: String { - switch self { - case .insertionIndexPathTooBig(indexPath: let indexPath, countOfElementsInSection: let count): - return "⚠️ [MemoryStorage] Failed to insert item into IndexPath: \(indexPath), count of elements in the section: \(count)" - case .batchInsertionItemCountMismatch(itemsCount: let itemsCount, indexPathsCount: let indexPathsCount): - return "⚠️ [MemoryStorage] Failed to insert batch of items, items count: \(itemsCount), indexPaths count: \(indexPathsCount)" - case .replaceItemFailedItemNotFound(itemDescription:let description): - return "⚠️ [MemoryStorage] Failed to find item for replacement: \(description)" - case .removeItemFailedItemNotFound(itemDescription: let description): - return "⚠️ [MemoryStorage] Failed to find item for removal: \(description)" - case .moveItemFailedItemNotFound(indexPath: let indexPath): - return "⚠️ [MemoryStorage] Failed to find item for moving at indexPath: \(indexPath)" - case .moveItemFailedIndexPathTooBig(indexPath: let indexPath, countOfElementsInSection: let count): - return "⚠️ [MemoryStorage] Failed to move item, destination indexPath is too big: \(indexPath), number of items in section after removing source item: \(count)" - case .moveItemFailedInvalidIndexPaths(sourceIndexPath: let source, destinationIndexPath: let destination, sourceElementsInSection: let sourceCount, destinationElementsInSection: let destinationCount): - return "⚠️ [MemoryStorage] Failed to move item, sourceIndexPath: \(source), destination indexPath: \(destination), number of items in source section: \(sourceCount), number of items in destination section after removing source item: \(destinationCount)" - } - } - - /// Short description for `MemoryStorageAnomaly`. Useful for sending to analytics, which might have character limit. - public var description: String { - switch self { - case .insertionIndexPathTooBig(indexPath: let indexPath, countOfElementsInSection: let count): return "MemoryStorageAnomaly.insertionIndexPathTooBig(\(indexPath), \(count))" - case .batchInsertionItemCountMismatch(itemsCount: let itemsCount, indexPathsCount: let indexPathsCount): return "MemoryStorageAnomaly.batchInsertionItemCountMismatch(\(itemsCount), \(indexPathsCount))" - case .replaceItemFailedItemNotFound(itemDescription: let itemDescription): return "MemoryStorageAnomaly.replaceItemFailedItemNotFound(\(itemDescription))" - case .removeItemFailedItemNotFound(itemDescription: let itemDescription): return "MemoryStorageAnomaly.removeItemFailedItemNotFound(\(itemDescription))" - case .moveItemFailedItemNotFound(indexPath: let indexPath): return "MemoryStorageAnomaly.moveItemFailedItemNotFound(\(indexPath))" - case .moveItemFailedIndexPathTooBig(indexPath: let indexPath, countOfElementsInSection: let count): return "MemoryStorageAnomaly.moveItemFailedIndexPathTooBig(\(indexPath), \(count))" - case .moveItemFailedInvalidIndexPaths(sourceIndexPath: let source, destinationIndexPath: let destination, sourceElementsInSection: let sourceCount, destinationElementsInSection: let destinationCount): - return "MemoryStorageAnomaly.moveItemFailedInvalidIndexPaths(\(source), \(destination), \(sourceCount), \(destinationCount))" - } - } -} - -/// `MemoryStorageAnomalyHandler` handles anomalies from `MemoryStorage`. -open class MemoryStorageAnomalyHandler : AnomalyHandler { - - /// Default action to perform when anomaly is detected. Prints debugDescription of anomaly by default. - public static var defaultAction : (MemoryStorageAnomaly) -> Void = { - #if DEBUG - print($0.debugDescription) - #endif - } - - /// Action to perform when anomaly is detected. Defaults to `defaultAction`. - open var anomalyAction: (MemoryStorageAnomaly) -> Void = MemoryStorageAnomalyHandler.defaultAction - - /// Creates `MemoryStorageAnomalyHandler`. - public init() {} -} - -/// This struct contains error types that can be thrown for various MemoryStorage errors -public enum MemoryStorageError: LocalizedError -{ - /// Errors that can happen when inserting items into memory storage - `insertItem(_:to:)` method - public enum InsertionReason - { - case indexPathTooBig(IndexPath) - } - - /// Errors that can happen when replacing item in memory storage - `replaceItem(_:with:)` method - public enum SearchReason - { - case itemNotFound(item: Any) - - var localizedDescription: String { - guard case let SearchReason.itemNotFound(item: item) = self else { - return "" - } - return "Failed to find \(item) in MemoryStorage" - } - } - - case insertionFailed(reason: InsertionReason) - case searchFailed(reason: SearchReason) - - /// Description of error - public var localizedDescription: String { - switch self { - case .insertionFailed(reason: _): - return "IndexPath provided was bigger then existing section or item" - case .searchFailed(reason: let reason): - return reason.localizedDescription - } - } -} - -/// Storage of models in memory. -/// -/// `MemoryStorage` stores data models using array of `SectionModel` instances. It has various methods for changing storage contents - add, remove, insert, replace e.t.c. -/// - Note: It also notifies it's delegate about underlying changes so that delegate can update interface accordingly -/// - SeeAlso: `SectionModel` -open class MemoryStorage: BaseUpdateDeliveringStorage, Storage, SectionLocationIdentifyable -{ - /// When enabled, datasource updates are not applied immediately and saved inside `StorageUpdate` `enqueuedDatasourceUpdates` property. - /// Call `StorageUpdate.applyDeferredDatasourceUpdates` method to apply all deferred changes. - /// Defaults to `true`. - /// - SeeAlso: https://github.com/DenTelezhkin/DTCollectionViewManager/issues/27 - open var defersDatasourceUpdates: Bool = true - - /// Anomaly handler, that handles reported by `MemoryStorage` anomalies. - open var anomalyHandler : MemoryStorageAnomalyHandler = .init() - - /// sections of MemoryStorage - open var sections: [Section] = [SectionModel]() { - didSet { - sections.forEach { - ($0 as? SectionModel)?.sectionLocationDelegate = self - } - } - } - - /// Returns number of sections in storage - open func numberOfSections() -> Int { - return sections.count - } - - /// Returns number of items in a given section - /// - Parameter section: given section - open func numberOfItems(inSection section: Int) -> Int { - guard sections.count > section else { return 0 } - return sections[section].numberOfItems - } - - func performDatasourceUpdate(_ block: @escaping (StorageUpdate) throws -> Void) { - if defersDatasourceUpdates { - currentUpdate?.enqueueDatasourceUpdate(block) - } else { - if let update = currentUpdate { - try? block(update) - } - } - } - - /// Returns index of `section` or nil, if section is now found - open func sectionIndex(for section: Section) -> Int? { - return sections.firstIndex(where: { - return ($0 as? SectionModel) === (section as? SectionModel) - }) - } - - /// Returns total number of items contained in all `MemoryStorage` sections - /// - /// - Complexity: O(n) where n - number of sections - open var totalNumberOfItems: Int { - return sections.reduce(0) { sum, section in - return sum + section.numberOfItems - } - } - - /// Returns item at `indexPath` or nil, if it is not found. - open func item(at indexPath: IndexPath) -> Any? { - guard indexPath.section < sections.count else { return nil } - guard indexPath.item < sections[indexPath.section].numberOfItems else { return nil } - return sections[indexPath.section].item(at: indexPath.item) - } - - /// Sets `items` for section at `index`. - /// - /// - Note: This will reload UI after updating. - open func setItems(_ items: [T], forSection index: Int = 0) - { - let section = self.getValidSection(index, collectChangesIn: nil) - section.items.removeAll(keepingCapacity: false) - section.items = items.map { $0 } - self.delegate?.storageNeedsReloading() - } - - /// Sets `items` for sections in memory storage. This method creates all required sections, if necessary. - /// - /// - Note: This will reload UI after updating. - open func setItemsForAllSections(_ items: [[T]]) { - sections.removeAll() - for (index, array) in items.enumerated() { - let section = getValidSection(index, collectChangesIn: nil) - section.items.removeAll() - section.items = array.map { $0 } - } - delegate?.storageNeedsReloading() - } - - /// Sets `section` for `index`. This will reload UI after updating - /// - /// - Parameter section: SectionModel to set - /// - Parameter index: index of section - open func setSection(_ section: SectionModel, forSection index: Int) - { - _ = self.getValidSection(index, collectChangesIn: nil) - sections.replaceSubrange(index...index, with: [section as Section]) - delegate?.storageNeedsReloading() - } - - /// Inserts `section` at `sectionIndex`. - /// - /// - Parameter section: section to insert - /// - Parameter sectionIndex: index of section to insert. - /// - Discussion: this method is assumed to be used, when you need to insert section with items and supplementaries in one batch operation. If you need to simply add items, use `addItems` or `setItems` instead. - /// - Note: If `sectionIndex` is larger than number of sections, method does nothing. - open func insertSection(_ section: SectionModel, atIndex sectionIndex: Int) { - guard sectionIndex <= sections.count else { return } - startUpdate() - performDatasourceUpdate { [weak self] update in - self?.sections.insert(section, at: sectionIndex) - update.sectionChanges.append((.insert, [sectionIndex])) - for item in 0..(_ items: [T], toSection index: Int = 0) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - let section = self?.getValidSection(index, collectChangesIn: update) - - for item in items { - let numberOfItems = section?.numberOfItems ?? 0 - section?.items.append(item) - update.objectChanges.append((.insert, [IndexPath(item: numberOfItems, section: index)])) - } - } - finishUpdate() - } - - /// Adds `item` to section with section `index`. - /// - /// - Parameter item: item to add - /// - Parameter toSection: index of section to add item - open func addItem(_ item: T, toSection index: Int = 0) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - let section = self?.getValidSection(index, collectChangesIn: update) - let numberOfItems = section?.numberOfItems ?? 0 - section?.items.append(item) - update.objectChanges.append((.insert, [IndexPath(item: numberOfItems, section: index)])) - } - finishUpdate() - } - - /// Inserts `item` to `indexPath`. - /// - /// This method creates all sections prior to indexPath.section, unless they are already created. - /// - Throws: if indexPath is too big, will throw MemoryStorageErrors.Insertion.IndexPathTooBig - open func insertItem(_ item: T, to indexPath: IndexPath) throws - { - startUpdate() - performDatasourceUpdate { [weak self] update in - let section = self?.getValidSection(indexPath.section, collectChangesIn: update) - - guard (section?.items.count ?? 0) >= indexPath.item else { - self?.anomalyHandler.reportAnomaly(MemoryStorageAnomaly.insertionIndexPathTooBig(indexPath: indexPath, countOfElementsInSection: section?.items.count ?? 0)) - throw MemoryStorageError.insertionFailed(reason: .indexPathTooBig(indexPath)) - } - - section?.items.insert(item, at: indexPath.item) - update.objectChanges.append((.insert, [indexPath])) - } - finishUpdate() - } - - /// Inserts `items` to `indexPaths` - /// - /// This method creates sections prior to maximum indexPath.section in `indexPaths`, unless they are already created. - /// - Throws: if items.count is different from indexPaths.count, will throw MemoryStorageErrors.BatchInsertion.ItemsCountMismatch - open func insertItems(_ items: [T], to indexPaths: [IndexPath]) throws - { - if items.count != indexPaths.count { - anomalyHandler.reportAnomaly(.batchInsertionItemCountMismatch(itemsCount: items.count, indexPathsCount: indexPaths.count)) - return - } - if defersDatasourceUpdates { - performDatasourceUpdate { [weak self] update in - indexPaths.enumerated().forEach { (arg) in - let (itemIndex, indexPath) = arg - let section = self?.getValidSection(indexPath.section, collectChangesIn: update) - guard (section?.items.count ?? 0) >= indexPath.item else { - return - } - section?.items.insert(items[itemIndex], at: indexPath.item) - update.objectChanges.append((.insert, [indexPath])) - } - } - } else { - performUpdates { - indexPaths.enumerated().forEach { (arg) in - let (itemIndex, indexPath) = arg - let section = getValidSection(indexPath.section, collectChangesIn: currentUpdate) - guard section.items.count >= indexPath.item else { - return - } - section.items.insert(items[itemIndex], at: indexPath.item) - currentUpdate?.objectChanges.append((.insert, [indexPath])) - } - } - } - } - - /// Reloads `item`. - open func reloadItem(_ item: T) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - if let indexPath = self?.indexPath(forItem: item) { - update.objectChanges.append((.update, [indexPath])) - update.updatedObjects[indexPath] = item - } - } - finishUpdate() - } - - /// Replace item `itemToReplace` with `replacingItem`. - /// - /// - Throws: if `itemToReplace` is not found, will throw MemoryStorageErrors.Replacement.ItemNotFound - open func replaceItem(_ itemToReplace: T, with replacingItem: Any) throws - { - startUpdate() - defer { self.finishUpdate() } - - performDatasourceUpdate { [weak self] update in - guard let originalIndexPath = self?.indexPath(forItem: itemToReplace) else { - self?.anomalyHandler.reportAnomaly(MemoryStorageAnomaly.replaceItemFailedItemNotFound(itemDescription: String(describing: itemToReplace))) - throw MemoryStorageError.searchFailed(reason: .itemNotFound(item: itemToReplace)) - } - - let section = self?.getValidSection(originalIndexPath.section, collectChangesIn: update) - section?.items[originalIndexPath.item] = replacingItem - - update.objectChanges.append((.update, [originalIndexPath])) - update.updatedObjects[originalIndexPath] = replacingItem - } - } - - /// Removes `item`. - /// - /// - Throws: if item is not found, will throw MemoryStorageErrors.Removal.ItemNotFound - open func removeItem(_ item: T) throws - { - startUpdate() - defer { self.finishUpdate() } - - performDatasourceUpdate { [weak self] update in - guard let indexPath = self?.indexPath(forItem: item) else { - self?.anomalyHandler.reportAnomaly(MemoryStorageAnomaly.removeItemFailedItemNotFound(itemDescription: String(describing: item))) - throw MemoryStorageError.searchFailed(reason: .itemNotFound(item: item)) - } - self?.getValidSection(indexPath.section, collectChangesIn: update).items.remove(at: indexPath.item) - update.objectChanges.append((.delete, [indexPath])) - } - } - - /// Removes `items` from storage. - /// - /// Any items that were not found, will be skipped. Items are deleted in reverse order, starting from largest indexPath to prevent unintended gaps. - /// - SeeAlso: `removeItems(at:)` - open func removeItems(_ items: [T]) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - let indexPaths = self?.indexPathArray(forItems: items) ?? [] - for indexPath in MemoryStorage.sortedArrayOfIndexPaths(indexPaths, ascending: false) - { - self?.getValidSection(indexPath.section, collectChangesIn: update).items.remove(at: indexPath.item) - } - indexPaths.forEach { - update.objectChanges.append((.delete, [$0])) - } - } - finishUpdate() - } - - /// Removes items at `indexPaths`. - /// - /// Any indexPaths that will not be found, will be skipped. Items are deleted in reverse order, starting from largest indexPath to prevent unintended gaps. - /// - SeeAlso: `removeItems(_:)` - open func removeItems(at indexPaths: [IndexPath]) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - let reverseSortedIndexPaths = MemoryStorage.sortedArrayOfIndexPaths(indexPaths, ascending: false) - for indexPath in reverseSortedIndexPaths - { - if let _ = self?.item(at: indexPath) - { - self?.getValidSection(indexPath.section, collectChangesIn: update).items.remove(at: indexPath.item) - update.objectChanges.append((.delete, [indexPath])) - } - } - } - finishUpdate() - } - - /// Deletes `indexes` from storage. - /// - /// Sections will be deleted in backwards order, starting from the last one. - open func deleteSections(_ indexes: IndexSet) - { - startUpdate() - performDatasourceUpdate { [weak self] update in - var markedForDeletion = [Int]() - for section in indexes where section < (self?.sections.count ?? 0) { - markedForDeletion.append(section) - } - for section in markedForDeletion.sorted().reversed() { - self?.sections.remove(at: section) - } - markedForDeletion.forEach { - update.sectionChanges.append((.delete, [$0])) - } - } - finishUpdate() - } - - /// Moves section from `sourceSectionIndex` to `destinationSectionIndex`. - /// - /// Sections prior to `sourceSectionIndex` and `destinationSectionIndex` will be automatically created, unless they already exist. - open func moveSection(_ sourceSectionIndex: Int, toSection destinationSectionIndex: Int) { - startUpdate() - performDatasourceUpdate { [weak self] update in - guard let validSectionFrom = self?.getValidSection(sourceSectionIndex, collectChangesIn: update) else { return } - _ = self?.getValidSection(destinationSectionIndex, collectChangesIn: update) - self?.sections.remove(at: sourceSectionIndex) - self?.sections.insert(validSectionFrom, at: destinationSectionIndex) - update.sectionChanges.append((.move, [sourceSectionIndex, destinationSectionIndex])) - } - finishUpdate() - } - - /// Moves item from `source` indexPath to `destination` indexPath. - /// - /// Sections prior to `source`.section and `destination`.section will be automatically created, unless they already exist. If source item or destination index path are unreachable(too large), this method does nothing. - open func moveItem(at source: IndexPath, to destination: IndexPath) - { - startUpdate() - defer { self.finishUpdate() } - - performDatasourceUpdate { [weak self] update in - guard let sourceItem = self?.item(at: source) else { - self?.anomalyHandler.reportAnomaly(MemoryStorageAnomaly.moveItemFailedItemNotFound(indexPath: source)) - return - } - let sourceSection = self?.getValidSection(source.section, collectChangesIn: update) - let destinationSection = self?.getValidSection(destination.section, collectChangesIn: update) - - let destinationSectionItemsCount = destinationSection?.items.count ?? 0 - - let numberOfItemsInSectionAfterRemovingSource = source.section == destination.section ? destinationSectionItemsCount - 1 : destinationSectionItemsCount - if numberOfItemsInSectionAfterRemovingSource < destination.row { - self?.anomalyHandler.reportAnomaly(MemoryStorageAnomaly.moveItemFailedIndexPathTooBig(indexPath: destination, countOfElementsInSection: numberOfItemsInSectionAfterRemovingSource)) - return - } - sourceSection?.items.remove(at: source.row) - destinationSection?.items.insert(sourceItem, at: destination.item) - update.objectChanges.append((.move, [source, destination])) - } - } - - /// Moves item from `sourceIndexPath` to `destinationIndexPath` without animations. - /// - /// - Note: This method can be used inside `tableView(UITableView, moveRowAt: IndexPath, to: IndexPath)` to update datasource without UI animation since UI animation has already happened. This is also useful for iOS 11 Drop reordering, that behaves the same way. - /// - Precondition: This method will check for existance of sections and number of items in both source and destination section prior to actually moving item. If sections do not exist, or have insufficient number of items to perform an operation, this method won't do anything. - /// - Parameters: - /// - sourceIndexPath: source indexPath to move item from - /// - destinationIndexPath: destination indexPath to move item to. - open func moveItemWithoutAnimation(from sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) - { - if let from = section(atIndex: sourceIndexPath.section), - let to = section(atIndex: destinationIndexPath.section) - { - let destinationSectionItemCountAfterRemoval = sourceIndexPath.section == destinationIndexPath.section ? to.items.count - 1: to.items.count - if from.items.count > sourceIndexPath.row, destinationSectionItemCountAfterRemoval >= destinationIndexPath.row { - let item = from.items[sourceIndexPath.row] - from.items.remove(at: sourceIndexPath.row) - to.items.insert(item, at: destinationIndexPath.row) - } else { - anomalyHandler.reportAnomaly(MemoryStorageAnomaly.moveItemFailedInvalidIndexPaths(sourceIndexPath: sourceIndexPath, - destinationIndexPath: destinationIndexPath, - sourceElementsInSection: from.items.count, - destinationElementsInSection: destinationSectionItemCountAfterRemoval)) - } - } - } - - /// Removes all items from storage. - /// - /// - Note: method will call .storageNeedsReloading() when it finishes. - open func removeAllItems() - { - for section in self.sections { - (section as? SectionModel)?.items.removeAll(keepingCapacity: false) - } - delegate?.storageNeedsReloading() - } - - /// Remove items from section with `sectionIndex`. - /// - /// If section at `sectionIndex` does not exist, this method does nothing. - open func removeItems(fromSection sectionIndex: Int) { - startUpdate() - defer { finishUpdate() } - - performDatasourceUpdate { [weak self] update in - guard let section = self?.section(atIndex: sectionIndex) else { return } - - for index in section.items.indices { - update.objectChanges.append((.delete, [IndexPath(item: index, section: sectionIndex)])) - } - section.items.removeAll() - } - } - - // MARK: - Searching in storage - - /// Returns items in section with section `index`, or nil if section does not exist - open func items(inSection index: Int) -> [Any]? - { - if sections.count > index { - let indexes = (0...sections[index].numberOfItems) - return indexes.reduce(into: []) { result, row in - item(at: IndexPath(row: row, section: index)).map { - result?.append($0) - } - } - } - return nil - } - - /// Returns indexPath of `searchableItem` in MemoryStorage or nil, if it's not found. - open func indexPath(forItem searchableItem: T) -> IndexPath? - { - for sectionIndex in 0.. SectionModel? - { - if sections.count > sectionIndex { - return sections[sectionIndex] as? SectionModel - } - return nil - } - - /// Finds-or-creates section at `sectionIndex` - /// - /// - Note: This method finds or create a SectionModel. It means that if you create section 2, section 0 and 1 will be automatically created. - /// - Returns: SectionModel - final func getValidSection(_ sectionIndex: Int, collectChangesIn update: StorageUpdate?) -> SectionModel - { - if sectionIndex < self.sections.count - { - //swiftlint:disable:next force_cast - return sections[sectionIndex] as! SectionModel - } else { - for i in sections.count...sectionIndex { - sections.append(SectionModel()) - update?.sectionChanges.append((.insert, [i])) - } - } - //swiftlint:disable:next force_cast - return sections.last as! SectionModel - } - - /// Returns index path array for `items` - /// - /// - Parameter items: items to find in storage - /// - Returns: Array of IndexPaths for found items - /// - Complexity: O(N^2*M) where N - number of items in storage, M - number of items. - final func indexPathArray(forItems items: [T]) -> [IndexPath] - { - var indexPaths = [IndexPath]() - - for index in 0.. [IndexPath] - { - let unsorted = NSMutableArray(array: indexPaths) - let descriptor = NSSortDescriptor(key: "self", ascending: ascending) - return unsorted.sortedArray(using: [descriptor]) as? [IndexPath] ?? [] - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift deleted file mode 100644 index 389968f..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ModelTransfer.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// ModelTransfer.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// Protocol used to pass `model` data to your cell or supplementary view. Every cell or supplementary view you have should conform to this protocol. -/// -/// `ModelType` is associated type, that works as generic constraint for specific cell or view. When implementing this method, use model type, that you wish to transfer to cell. -/// -/// For example: -/// class PostTableViewCell: UITableViewCell, ModelTransfer { -/// func update(with: Post) { -/// } -/// } -public protocol ModelTransfer : class -{ - /// Type of model that is being transferred - associatedtype ModelType - - /// Updates view with `model`. - func update(with model: ModelType) -} - -extension ModelTransfer { - /// Returns custom MappingCondition that allows to customize mappings based on IndexPath and ModelType. - public static func modelCondition(_ condition: @escaping (IndexPath, ModelType) -> Bool) -> MappingCondition { - return .custom { indexPath, model in - guard let model = model as? ModelType else { return false } - return condition(indexPath, model) - } - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift deleted file mode 100644 index 34a3d4c..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ProxyDiffableDataSourceStorage.swift +++ /dev/null @@ -1,114 +0,0 @@ -// -// ProxyDiffableDatasourceStorage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 7/23/19. -// Copyright © 2019 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -#if compiler(>=5.1) -@available(iOS 13, tvOS 13, *) -/// `ProxyDiffableDataSourceStorage` serves as a bridge between `DTTableViewManager`/`DTCollectionViewManager` and diffable datasource classes for UITableView/UICollectionView(`UITableViewDiffableDataSource`\`UICollectionViewDiffableDataSource`). -public class ProxyDiffableDataSourceStorage: BaseSupplementaryStorage, Storage { - private let _numberOfSections: () -> Int - private let numberOfItemsInSection: (Int) -> Int - private let itemAtIndexPath: (IndexPath) -> Any? - - /// Returns number of sections in storage. - public func numberOfSections() -> Int { - return _numberOfSections() - } - - /// Returns number of items in section. - public func numberOfItems(inSection section: Int) -> Int { - return numberOfItemsInSection(section) - } - - /// Returns item at concrete indexPath. - public func item(at indexPath: IndexPath) -> Any? { - return itemAtIndexPath(indexPath) - } - - /// Creates `ProxyDiffableDataSourceStorage`. - /// - Parameter tableView: UITableView instance to use with diffable datasource - /// - Parameter dataSource: Diffable datasource that will be queried for datasource information. - /// - Parameter modelProvider: Closure, that provides data model for given indexPath and item identifier. - public init(tableView: UITableView, dataSource: UITableViewDiffableDataSource, modelProvider: @escaping (IndexPath, ItemIdentifier) -> Any) { - _numberOfSections = { dataSource.numberOfSections(in: tableView) } - numberOfItemsInSection = { dataSource.tableView(tableView, numberOfRowsInSection: $0) } - itemAtIndexPath = { - guard let itemIdentifier = dataSource.itemIdentifier(for: $0) else { - return nil - } - return modelProvider($0, itemIdentifier) - } - } - - /// Creates `ProxyDiffableDataSourceStorage`. - /// - Parameter tableView: UITableView instance to use with diffable datasource - /// - Parameter dataSource: Diffable datasource that will be queried for datasource information. - /// - Parameter modelProvider: Closure, that provides data model for given indexPath and item identifier. - public init(tableView: UITableView, dataSource: UITableViewDiffableDataSourceReference, modelProvider: @escaping (IndexPath, Any) -> Any) { - _numberOfSections = { dataSource.numberOfSections(in: tableView) } - numberOfItemsInSection = { dataSource.tableView(tableView, numberOfRowsInSection: $0) } - itemAtIndexPath = { - guard let itemIdentifier = dataSource.itemIdentifier(for: $0) else { - return nil - } - return modelProvider($0, itemIdentifier) - } - } - - /// Creates `ProxyDiffableDataSourceStorage`. - /// - Parameter collectionView: UICollectionView instance to use with diffable datasource - /// - Parameter dataSource: Diffable datasource that will be queried for datasource information. - /// - Parameter modelProvider: Closure, that provides data model for given indexPath and item identifier. - public init(collectionView: UICollectionView, dataSource: UICollectionViewDiffableDataSource, modelProvider: @escaping (IndexPath, ItemIdentifier) -> Any) { - _numberOfSections = { dataSource.numberOfSections(in: collectionView) } - numberOfItemsInSection = { dataSource.collectionView(collectionView, numberOfItemsInSection: $0) } - itemAtIndexPath = { - guard let itemIdentifier = dataSource.itemIdentifier(for: $0) else { - return nil - } - return modelProvider($0, itemIdentifier) - } - } - - /// Creates `ProxyDiffableDataSourceStorage`. - /// - Parameter collectionView: UICollectionView instance to use with diffable datasource - /// - Parameter dataSource: Diffable datasource that will be queried for datasource information. - /// - Parameter modelProvider: Closure, that provides data model for given indexPath and item identifier. - public init(collectionView: UICollectionView, dataSource: UICollectionViewDiffableDataSourceReference, - modelProvider: @escaping (IndexPath, Any) -> Any) - { - _numberOfSections = { dataSource.numberOfSections(in: collectionView) } - numberOfItemsInSection = { dataSource.collectionView(collectionView, numberOfItemsInSection: $0) } - itemAtIndexPath = { - guard let itemIdentifier = dataSource.itemIdentifier(for: $0) else { - return nil - } - return modelProvider($0, itemIdentifier) - } - } -} -#endif diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift deleted file mode 100644 index 06d7abb..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/RuntimeHelper.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// RuntimeHelper.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 15.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// This class is used to introspect Swift and Objective-C types, providing necessary mapping information. -public enum RuntimeHelper -{ - /// Returns recursively unwrapped `any` optional. - /// - /// This is helpful when dealing with double optionals. - public static func recursivelyUnwrapAnyValue(_ any: Any) -> Any? - { - let mirror = Mirror(reflecting: any) - if mirror.displayStyle != .optional - { - return any - } - if let child = mirror.children.first { - let (_, some) = child - return recursivelyUnwrapAnyValue(some) - } - return nil - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift deleted file mode 100644 index 7c7d2b5..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/Section.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// Section.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// `Section` protocol defines an interface for sections returned by DTModelStorage object. -/// For `MemoryStorage`, `SectionModel` is the object, conforming to current protocol. -/// For `CoreDataStorage` NSFetchedResultsController returns `NSFetchedResultsSectionInfo` object, that also conforms to current protocol. -public protocol Section -{ - /// Returns an item at index, if it exists in Section. - /// - Parameter index: index to search for. - func item(at index: Int) -> Any? - - /// Number of items in current section. - var numberOfItems: Int { get } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift deleted file mode 100644 index d342e1a..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionModel.swift +++ /dev/null @@ -1,76 +0,0 @@ -// -// SectionModel.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 10.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// Data holder for single section in `MemoryStorage`. -open class SectionModel: Section, SectionLocatable -{ - - /// Returns item at index, if it exists, nil otherwise. - /// - Parameter index: Index to search for. - open func item(at index: Int) -> Any? { - guard items.count > index else { return nil } - return items[index] - } - - /// Items for current section - /// - Warning: If you try to set new array to this property [T], the only way to do this without exception is to wrap it into items.map { $0 }. This is a workaround that exists because of Swift inability to cast [T] to [Any]. You can call `setItems` method instead of doing so. - /// - SeeAlso: `setItems:` - open var items = [Any]() - - /// delegate, that knows about current section index in storage. - open weak var sectionLocationDelegate: SectionLocationIdentifyable? - - /// section index of current section in `MemoryStorage`. - open var currentSectionIndex: Int? { - return sectionLocationDelegate?.sectionIndex(for: self) - } - - @available(*, unavailable, message: "Please use storage.supplementaryModelProvider as a replacement.") - /// Supplementaries dictionary. - open var supplementaries = [String: [Int: Any]]() - - /// Creates empty section model. - public init() {} - - /// Set items of specific time to items property. - /// - Note: This method exists because of inability of Swift to cast [T] to [Any]. It uses simple map underneath. - open func setItems(_ items: [T]) - { - self.items = items.map { $0 } - } - - /// Returns items of `type` in current section - open func items(ofType type: T.Type) -> [T] - { - return items.compactMap { $0 as? T } - } - - /// Number of items in current section - open var numberOfItems: Int { - return items.count - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift deleted file mode 100644 index 55ffb76..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SectionProtocols.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// SectionProtocols.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// Identifies index of section in storage -public protocol SectionLocationIdentifyable : class { - /// Returns section index for section, or nil if section was not found. - func sectionIndex(for: Section) -> Int? -} - -/// Allows access to supplementaries for specific section -public protocol SectionLocatable : class { - - /// Section index for current section - var currentSectionIndex: Int? { get } - - /// delegate, that knows about current section index in storage. - var sectionLocationDelegate: SectionLocationIdentifyable? { get set } -} - -extension SectionLocatable { - - @available(*, unavailable, message: "Please use storage.supplementaryModelProvider closure to provide supplementaries.") - /// Supplementaries dictionary - var supplementaries: [String: [Int:Any]] { return [:] } - - @available(*, unavailable, message: "Please use storage.supplementaryModelProvider closure to provide supplementaries.") - /// Returns supplementary model of `kind` at `index` or nil, if it was not found - public func supplementaryModel(ofKind kind: String, atIndex index: Int) -> Any? - { - return nil - } - - @available(*, unavailable, message: "Please use storage.supplementaryModelProvider closure to provide supplementaries.") - /// Sets supplementary `model` for `kind` at `index` - public func setSupplementaryModel(_ model : Any?, forKind kind: String, atIndex index: Int) - { - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift deleted file mode 100644 index 4bb777f..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionDiffing.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// SingleSectionDiffing.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 21.09.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// A type that can be identified by `identifier`. -public protocol EntityIdentifiable { - - /// Unique identifier of object. It must never change for this specific object. - var identifier: AnyHashable { get } -} - -/// Edit operation in single section. -/// -/// - delete: item is deleted at index -/// - insert: item is inserted at index -/// - move: item is moved `from` index `to` index. -/// - update: item is updated at index. -public enum SingleSectionOperation { - case delete(Int) - case insert(Int) - case move(from: Int, to: Int) - case update(Int) -} - -/// Algorithm that requires elements in collection to be `Hashable` -public protocol HashableDiffingAlgorithm { - func diff(from: [T], to: [T]) -> [SingleSectionOperation] -} - -/// Algorithm that requires elements in collection to be `Equatable` -public protocol EquatableDiffingAlgorithm { - func diff(from: [T], to: [T]) -> [SingleSectionOperation] -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift deleted file mode 100644 index 35dba96..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/SingleSectionStorage.swift +++ /dev/null @@ -1,180 +0,0 @@ -// -// SingleSectionStorage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 13.09.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// `SingleSectionStorage` that requires all it's elements to be `Equatable`. -open class SingleSectionEquatableStorage : SingleSectionStorage { - - /// Diffing algorithm that requires all it's elements to be `Equatable`. - public let differ: EquatableDiffingAlgorithm - - /// Creates storage with `items` and concrete implementation of `EquatableDiffingAlgorithm` - `differ`. - /// - /// - Parameters: - /// - items: starting items in storage - /// - differ: concrete diffing implementation - public init(items: [T], differ: EquatableDiffingAlgorithm) { - self.differ = differ - super.init(items: items) - } - - /// Calculate diffs between `items` and `newItems`. - /// - /// - Parameter newItems: new items collection - /// - Returns: Array of changes between `items` and `newItems`. - open override func calculateDiffs(to newItems: [T]) -> [SingleSectionOperation] { - return differ.diff(from: items, to: newItems) - } -} - -/// `SingleSectionStorage` that requires all it's elements to be `Hashable`. -open class SingleSectionHashableStorage : SingleSectionStorage { - - /// Diffing algorithm that requires all it's elements to be `Hashable`. - public let differ: HashableDiffingAlgorithm - - /// Creates storage with `items` and concrete implementation of `HashableDiffingAlgorithm` - `differ`. - /// - /// - Parameters: - /// - items: starting items in storage - /// - differ: concrete diffing implementation - public init(items: [T], differ: HashableDiffingAlgorithm) { - self.differ = differ - super.init(items: items) - } - - /// Calculate diffs between `items` and `newItems`. - /// - /// - Parameter newItems: new items collection - /// - Returns: Array of changes between `items` and `newItems`. - open override func calculateDiffs(to newItems: [T]) -> [SingleSectionOperation] { - return differ.diff(from: items, to: newItems) - } -} - -/// Abstract base class that represents a single section of items. Supports supplementary items to allow representing supplementary views in section. -/// - SeeAlso: `SingleSectionHashableStorage` -/// - SeeAlso: `SingleSectionEquatableStorage` -open class SingleSectionStorage : BaseUpdateDeliveringStorage, Storage { - - /// Returns number of sections in a storage - open func numberOfSections() -> Int { - return 1 - } - - /// Returns number of items in a given section - /// - Parameter section: given section index. - open func numberOfItems(inSection section: Int) -> Int { - guard section == 0 else { return 0 } - return items.count - } - - /// Array of items, that section contains. - open var items : [T] { - get { return section.items(ofType: T.self) } - set { section.setItems(newValue) } - } - - /// Internal representation of a single section - private var section : SectionModel - - /// Creates storage with array of items. Do not call this method directly. Instead use concrete subclasses of `SingleSectionStorage`, such as `SingleSectionEquatableStorage`. - /// - /// - Parameter items: array of starting items in section. - public init(items: [T]) { - let sectionModel = SectionModel() - sectionModel.setItems(items) - section = sectionModel - } - - // Storage - - /// Retrieve item at given `indexPath`. - /// - /// - Parameter indexPath: indexPath of item in storage - /// - Returns: item at specified indexPath, or nil if indexPath is out of bounds. - public func item(at indexPath: IndexPath) -> Any? { - guard indexPath.section == 0 else { return nil } - guard indexPath.item < section.items.count else { return nil } - return section.items[indexPath.item] - } - - // Diffing and updates - - /// Abstract method to calculate diffs. Do not use this method directly. Instead, use subclassed method, for example `SingleSectionEquatableStorage.calculateDiffs(to:)`. - /// - SeeAlso: `setItems` - /// - SeeAlso: `addItems` - /// - /// - Parameter newItems: new array, to which diffs are calculated - /// - Returns: Array of changes between `items` and `newItems`. - open func calculateDiffs(to newItems: [T]) -> [SingleSectionOperation] { - fatalError("This method needs to be overridden in subclasses") - } - - /// Replaces `items` with `newItems`, collecting changes along the way. Changes are calculated using `calculateDiffs(to:)` method and delivered to `StorageUpdating` delegate, which can animate changes in resulting UI(for example UITableView or UICollectionView). - /// - /// - Parameter newItems: new array of items - public func setItems(_ newItems: [T]) { - let diffs = calculateDiffs(to: newItems) - collectChanges(diffs, to: newItems) - } - - /// Adds `newItems` on top of `items`, using specified accumulation strategy. - /// - /// - Parameters: - /// - newItems: new items array - /// - strategy: strategy to use when accumulating items. Defaults to AdditiveAccumulationStrategy. - public func addItems(_ newItems: [T], _ strategy: AccumulationStrategy = AdditiveAccumulationStrategy()) { - let accumulatedItems = strategy.accumulate(oldItems: items, newItems: newItems) - let diffs = calculateDiffs(to: accumulatedItems) - collectChanges(diffs, to: accumulatedItems) - } - - /// Convert `changes` to `StorageUpdate` and deliver it to `StorageUpdating` delegate. - /// - /// - Parameters: - /// - changes: changes to collect - /// - new: new collection of items - func collectChanges(_ changes: [SingleSectionOperation], to new: [T]) { - let update = StorageUpdate() - update.enqueueDatasourceUpdate { [weak self] _ in - self?.section.setItems(new) - } - for diff in changes { - switch diff { - case .delete(let item): - update.objectChanges.append((.delete, [IndexPath(item: item, section: 0)])) - case .insert(let item): - update.objectChanges.append((.insert, [IndexPath(item: item, section: 0)])) - case .update(let item): - update.objectChanges.append((.update, [IndexPath(item: item, section: 0)])) - case .move(let from, let to): - update.objectChanges.append((.move, [IndexPath(item: from, section: 0), IndexPath(item: to, section: 0)])) - } - } - delegate?.storageDidPerformUpdate(update) - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift deleted file mode 100644 index 0c46748..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageProtocols.swift +++ /dev/null @@ -1,138 +0,0 @@ -// -// Storage.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -/// `Storage` protocol is used to define common interface for storage classes. -public protocol Storage : class -{ - /// Returns number of sections in storage. - func numberOfSections() -> Int - - /// Returns number of items in section. - func numberOfItems(inSection section: Int) -> Int - - /// Returns item at concrete indexPath. - func item(at indexPath: IndexPath) -> Any? -} - -/// `SupplementaryStorage` is used to handle header/footer and supplementary models in storage. -public protocol SupplementaryStorage : class -{ - /// Returns a header model for specified section index or nil. - var headerModelProvider: ((_ sectionIndex: Int) -> Any?)? { get set } - - /// Returns a footer model for specified section index or nil - var footerModelProvider: ((_ sectionIndex: Int) -> Any?)? { get set } - - /// Returns supplementary model for specified section indexPath and supplementary kind, or nil. - var supplementaryModelProvider: ((_ kind: String, _ sectionIndexPath: IndexPath) -> Any?)? { get set } - - /// Supplementary kind for header in current storage - var supplementaryHeaderKind: String? { get set } - - /// Supplementary kind for footer in current storage - var supplementaryFooterKind: String? { get set } -} - -extension SupplementaryStorage { - /// Configures storage for using with UITableView - public func configureForTableViewUsage() - { - supplementaryHeaderKind = DTTableViewElementSectionHeader - supplementaryFooterKind = DTTableViewElementSectionFooter - } - - /// Configures storage for using with UICollectionViewFlowLayout - public func configureForCollectionViewFlowLayoutUsage() - { - supplementaryHeaderKind = DTCollectionViewElementSectionHeader - supplementaryFooterKind = DTCollectionViewElementSectionFooter - } - -/// Returns header model from section with section `index` or nil, if it was not set. - /// - Requires: supplementaryHeaderKind to be set prior to calling this method - public func headerModel(forSection index: Int) -> Any? { - return headerModelProvider?(index) - } - - /// Returns footer model from section with section `index` or nil, if it was not set. - /// - Requires: supplementaryFooterKind to be set prior to calling this method - public func footerModel(forSection index: Int) -> Any? { - return footerModelProvider?(index) - } - - /// Returns supplementary model of `kind` for section at `indexPath`. - public func supplementaryModel(ofKind kind: String, forSectionAt indexPath: IndexPath) -> Any? { - return supplementaryModelProvider?(kind, indexPath) - } -} - -extension SupplementaryStorage { - @available(*, unavailable, message: "Please use storage.supplementaryModel closure instead.") - /// Sets supplementaries `models`, using `kind`. - public func setSupplementaries(_ models: [[Int: Any]], forKind kind: String) - { - } - - /// Sets section header `models`, using `supplementaryHeaderKind`. - public func setSectionHeaderModels(_ models: [T]) - { - headerModelProvider = { index in - guard index < models.count else { return nil } - return models[index] - } - } - - /// Sets section footer `models`, using `supplementaryFooterKind`. - public func setSectionFooterModels(_ models: [T]) - { - footerModelProvider = { index in - guard index < models.count else { return nil } - return models[index] - } - } - - @available(*, unavailable, message: "Please use storage.headerModelProvider closure instead.") - /// Sets section header `model` for section at `sectionIndex` - /// - /// This method calls delegate?.storageNeedsReloading() method at the end, causing UI to be updated. - /// - SeeAlso: `configureForTableViewUsage` - /// - SeeAlso: `configureForCollectionViewUsage` - public func setSectionHeaderModel(_ model: T?, forSection sectionIndex: Int) - { - } - - @available(*, unavailable, message: "Please use storage.footerModelProvider closure instead.") - /// Sets section footer `model` for section at `sectionIndex` - /// - /// This method calls delegate?.storageNeedsReloading() method at the end, causing UI to be updated. - /// - SeeAlso: `configureForTableViewUsage` - /// - SeeAlso: `configureForCollectionViewUsage` - public func setSectionFooterModel(_ model: T?, forSection sectionIndex: Int) - { - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift deleted file mode 100644 index 4ea5f75..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/StorageUpdate.swift +++ /dev/null @@ -1,120 +0,0 @@ -// -// StorageUpdate.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 06.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// Possible change types for objects and sections -public enum ChangeType: String { - case delete - case move - case insert - case update -} - -/// Object representing update in storage. -public class StorageUpdate: Equatable, CustomStringConvertible -{ - /// Object changes in update, in order of occurence - public var objectChanges = [(ChangeType, [IndexPath])]() - - /// Section changes in update, in order of occurence - public var sectionChanges = [(ChangeType, [Int])]() - - /// Objects that were updated, with initial index paths - /// Discussion: This is done because UITableView and UICollectionView defer updating of items after all insertions and deletions are made. - /// Therefore, resulting indexPaths are shifted, and update may be called on wrong indexPath. By storing objects from initial update call, we ensure, that objects used in update are correct. - public var updatedObjects = [IndexPath: Any]() - - /// If update contains deferred datasource updates, they need to be applied before applying any animations. - /// SeeAlso: - `applyDeferredDatasourceUpdates` method. - public var containsDeferredDatasourceUpdates : Bool { - return enqueuedDatasourceUpdates.count > 0 - } - - /// Enqueued datasource updates for later execution. This can be used by `UICollectionView` and `UITableView` batch updates mechanisms to update datasources inside of `performBatchUpdates(_:completion:)` method. - /// - Note: Appropriate way of doing so is checking `containsDeferredDatasourceUpdates` property and calling `applyDeferredDatasourceUpdates(_:)` method. - public var enqueuedDatasourceUpdates = [(StorageUpdate) throws -> Void]() - - /// Create an empty update. - public init(){} - - /// Returns true, if update is empty. - public var isEmpty: Bool { - return objectChanges.isEmpty && sectionChanges.isEmpty && enqueuedDatasourceUpdates.isEmpty - } - - /// Call this method to apply all deferred datasource updates. - /// This method works only when using `MemoryStorage` with `defersDatasourceUpdates` flag turned on. - public func applyDeferredDatasourceUpdates() { - enqueuedDatasourceUpdates.forEach { try? $0(self) } - enqueuedDatasourceUpdates = [] - } - - /// Enqueues datasource update for later execution into `enqueuedDatasourceUpdates` property. This can be used by `UICollectionView` and `UITableView` batch updates mechanisms to update datasources inside of `performBatchUpdates(_:completion:)` method. - /// - Note: Appropriate way of doing so is checking `containsDeferredDatasourceUpdates` property and calling `applyDeferredDatasourceUpdates(_:)` method. - /// - /// - Parameter update: datasource update. - public func enqueueDatasourceUpdate(_ update: @escaping (StorageUpdate) throws -> Void) { - enqueuedDatasourceUpdates.append(update) - } - - /// Compare StorageUpdates - static public func == (left: StorageUpdate, right: StorageUpdate) -> Bool - { - if left.objectChanges.count != right.objectChanges.count || - left.sectionChanges.count != right.sectionChanges.count { - return false - } - - for index in left.objectChanges.indices { - if left.objectChanges[index].0 != right.objectChanges[index].0 || - left.objectChanges[index].1 != right.objectChanges[index].1 - { - return false - } - } - for index in left.sectionChanges.indices { - if left.sectionChanges[index].0 != right.sectionChanges[index].0 || - left.sectionChanges[index].1 != right.sectionChanges[index].1 - { - return false - } - } - return left.enqueuedDatasourceUpdates.count == right.enqueuedDatasourceUpdates.count - } - - /// Description of object changes - public var description: String { - let objectChangesString = "Object changes: \n" + objectChanges.compactMap({ (arg) -> String? in - let (change, indexPaths) = arg - return change.rawValue.capitalized + " \(indexPaths) " - }).reduce("", +) - let sectionChangesString = "Section changes:" + sectionChanges.compactMap({ (arg) -> String? in - let (change, index) = arg - return change.rawValue.capitalized + " \(index)) " - }).reduce("", +) - return objectChangesString + "\n" + sectionChangesString - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift deleted file mode 100644 index e98e62b..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/UINib+Existance.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// UINib+Existance.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 15.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -extension UINib { - /// Returns true, if nib file with `nibName` exists in `bundle`. - public class func nibExists(withNibName nibName: String, - inBundle bundle: Bundle = Bundle.main) -> Bool - { - return bundle.path(forResource: nibName, ofType: "nib") != nil - } -} diff --git a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift b/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift deleted file mode 100644 index 176364b..0000000 --- a/Lesson14/Pods/DTModelStorage/Sources/DTModelStorage/ViewModelMapping.swift +++ /dev/null @@ -1,158 +0,0 @@ -// -// ViewModelMapping.swift -// DTModelStorage -// -// Created by Denys Telezhkin on 27.11.15. -// Copyright © 2015 Denys Telezhkin. All rights reserved. -// -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -/// ViewType enum allows differentiating between mappings for different kinds of views. For example, UICollectionView headers might use ViewType.supplementaryView(UICollectionElementKindSectionHeader) value. -public enum ViewType: Equatable -{ - case cell - case supplementaryView(kind: String) - - /// Returns supplementaryKind for .supplementaryView case, nil for .cell case. - /// - Returns supplementaryKind string - public func supplementaryKind() -> String? - { - switch self - { - case .cell: return nil - case .supplementaryView(let kind): return kind - } - } - - // Compares view types, `Equatable` protocol. - static public func == (left: ViewType, right: ViewType) -> Bool { - switch (left, right) { - case (.cell, .cell): return true - case (.supplementaryView(let leftKind), .supplementaryView(let rightKind)): return leftKind == rightKind - default: return false - } - } -} - - -/// Defines condition, under which mapping is going to be applied. -public enum MappingCondition { - - // Mapping is applicable at all times - case none - - // Mapping is applicable only in specific section - case section(Int) - - // Mapping is applicable only under custom condition - case custom((_ indexPath: IndexPath, _ model: Any) -> Bool) - - - /// Defines whether mapping is compatible with `model` at `indexPath`. - /// - /// - Parameters: - /// - indexPath: location of the model in storage - /// - model: model to apply mapping to - /// - Returns: whether current mapping condition is applicable. - func isCompatible(with indexPath: IndexPath, model: Any) -> Bool { - switch self { - case .none: return true - case .section(let section): return indexPath.section == section - case .custom(let condition): return condition(indexPath, model) - } - } -} - -/// `ViewModelMapping` struct serves to store mappings, and capture model and cell types. Due to inability of moving from dynamic types to compile-time types, we are forced to use (Any,Any) closure and force cast types when mapping is performed. -open class ViewModelMapping -{ - /// View type for this mapping - public let viewType: ViewType - - /// View class, that will be used for current mapping - public let viewClass: AnyClass - - /// Xib name for mapping. This value will not be nil only if XIBs are used for this particular mapping. - public var xibName: String? - - /// Bundle in which resources for this mapping will be searched for. For example, `DTTableViewManager` uses this property to get bundle, from which xib file for `UITableViewCell` will be retrieved. Defaults to `Bundle(for: T.self)`. - /// When used for events that rely on modelClass(`.eventsModelMapping(viewType: modelClass:` method) defaults to `Bundle.main`. - public var bundle: Bundle - - /// Type checking block, that will verify whether passed model should be mapped to `viewClass`. - public let modelTypeCheckingBlock: (Any) -> Bool - - /// Type-erased update block, that will be called when `ModelTransfer` `update(with:)` method needs to be executed. - public let updateBlock : (Any, Any) -> Void - - /// Mapping condition, under which this mapping is going to work. Defaults to .none. - public var condition: MappingCondition = .none - - /// Reuse identifier to be used for reusable views. - public var reuseIdentifier : String - - /// Creates `ViewModelMapping` for `viewClass` - public init(viewType: ViewType, viewClass: T.Type, xibName: String? = nil, mappingBlock: ((ViewModelMapping) -> Void)?) { - self.viewType = viewType - self.viewClass = viewClass - self.xibName = xibName - self.reuseIdentifier = String(describing: T.self) - modelTypeCheckingBlock = { $0 is T.ModelType } - updateBlock = { view, model in - guard let view = view as? T, let model = model as? T.ModelType else { return } - view.update(with: model) - } - bundle = Bundle(for: T.self) - mappingBlock?(self) - } - - /// Creates `ViewModelMapping` for `modelType` - public static func eventsModelMapping(viewType: ViewType, modelClass: T.Type) -> ViewModelMapping { - return ViewModelMapping(viewType: viewType, modelClass: modelClass) - } - - private init(viewType: ViewType, modelClass: T.Type) { - self.viewType = viewType - viewClass = NSObject.self - modelTypeCheckingBlock = { $0 is T } - updateBlock = { _, _ in } - reuseIdentifier = "" - xibName = nil - bundle = Bundle.main - } -} - -extension RangeReplaceableCollection where Self.Iterator.Element == ViewModelMapping { - - /// Returns mappings candidates of correct `viewType`, for which `modelTypeCheckingBlock` with `model` returns true. - /// - Returns: Array of view model mappings - /// - Note: Usually returned array will consist of 0 or 1 element. Multiple candidates will be returned when several mappings correspond to current model - this can happen in case of protocol or subclassed model. - /// - SeeAlso: `addMappingForViewType(_:viewClass:)` - public func mappingCandidates(for viewType: ViewType, withModel model: Any, at indexPath: IndexPath) -> [ViewModelMapping] { - return filter { mapping -> Bool in - guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { return false } - return viewType == mapping.viewType && - mapping.modelTypeCheckingBlock(unwrappedModel) && - mapping.condition.isCompatible(with: indexPath, model: model) - } - } -} diff --git a/Lesson14/Pods/DTTableViewManager/LICENSE b/Lesson14/Pods/DTTableViewManager/LICENSE deleted file mode 100644 index 0131a92..0000000 --- a/Lesson14/Pods/DTTableViewManager/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012 Denys Telezhkin (http://github.com/DenTelezhkin/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/Lesson14/Pods/DTTableViewManager/README.md b/Lesson14/Pods/DTTableViewManager/README.md deleted file mode 100644 index eaaae3a..0000000 --- a/Lesson14/Pods/DTTableViewManager/README.md +++ /dev/null @@ -1,452 +0,0 @@ -[![Build Status](https://travis-ci.org/DenTelezhkin/DTTableViewManager.svg?branch=master)](https://travis-ci.org/DenTelezhkin/DTTableViewManager) -[![codecov.io](http://codecov.io/github/DenTelezhkin/DTTableViewManager/coverage.svg?branch=master)](http://codecov.io/github/DenTelezhkin/DTTableViewManager?branch=master) -[![CocoaPods compatible](https://img.shields.io/cocoapods/v/DTTableViewManager.svg)](https://cocoapods.org/pods/DTTableViewManager) -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg)]() - -DTTableViewManager -================ -> This is a sister-project for [DTCollectionViewManager](https://github.com/DenTelezhkin/DTCollectionViewManager) - great tool for UICollectionView management, built on the same principles. - -Powerful generic-based UITableView management framework, written in Swift. - -- [Features](#features) -- [Requirements](#requirements) -- [Installation](#installation) -- [Quick start](#quick-start) -- [Usage](#usage) - - **Intro -** [Mapping and Registration](#mapping-and-registration), [Data Models](#data-models) - - **Storage classes -** [Memory Storage](#memorystorage), [CoreDataStorage](#coredatastorage), [RealmStorage](#realmstorage), [Diffable Datasources in iOS13](#diffable-datasources-in-ios-13) - - **Reacting to events -** [Event types](#event-types), [Events configuration](#events-configuration) -- [Advanced Usage](#advanced-usage) - - [Drag and Drop in iOS 11](#drag-and-drop-in-ios-11) - - [Reacting to content updates](#reacting-to-content-updates) - - [Customizing UITableView updates](#customizing-uitableview-updates) - - [Display header on empty section](#display-header-on-empty-section) - - [Conditional mappings](#conditional-mappings) - - [Anomaly handler](#anomaly-handler) - - [Unregistering mappings](#unregistering-mappings) -- [Thanks](#thanks) - -## Features - -- [x] Powerful mapping system between data models and cells, headers and footers -- [x] Support for all Swift types - classes, structs, enums, tuples, protocols -- [x] Support for diffable datasources in iOS 13 -- [x] Powerful events system, that covers all UITableView delegate and datasource methods -- [x] Views created from code, XIB, or storyboard -- [x] Flexible Memory/CoreData/Realm.io storage options -- [x] Automatic datasource and interface synchronization. -- [x] Automatic XIB registration and dequeue -- [x] Support for Drag&Drop API for iOS 11 and higher -- [x] Can be used with UITableViewController, or UIViewController with UITableView, or any other class, that contains UITableView -- [x] [Complete documentation](https://dentelezhkin.github.io/DTTableViewManager) - -## Requirements - -* Xcode 9 and higher -* iOS 8.0 and higher / tvOS 9.0 and higher -* Swift 4 and higher - -## Installation - -### Swift Package Manager(requires Xcode 11) - -Add package into Project settings -> Swift Packages - -### [CocoaPods](http://www.cocoapods.org): - - pod 'DTTableViewManager' - -### [Carthage](https://github.com/Carthage/Carthage): - - github "DenTelezhkin/DTTableViewManager" - -After running `carthage update` add DTTableViewManager.framework and DTModelStorage.framework to Xcode project embedded binaries. - -## Quick start - -`DTTableViewManager` framework has two parts - core framework, and storage classes. Import them both to your view controller class to start: - -```swift -import DTTableViewManager -import DTModelStorage -``` - -Let's say you have an array of Posts you want to display in UITableView. To quickly show them using DTTableViewManager, here's what you need to do: - -* Create UITableViewCell subclass, let's say PostCell. Adopt ModelTransfer protocol - -```swift -class PostCell : UITableViewCell, ModelTransfer { - func update(with model: Post) { - // Fill your cell with actual data - } -} -``` - -* Declare your class as `DTTableViewManageable`, and it will be automatically injected with `manager` property, that will hold an instance of `DTTableViewManager`. - -* Make sure your UITableView outlet is wired to your class and call registration methods: - -```swift -class PostsViewController: UIViewController, DTTableViewManageable { - - @IBOutlet weak var tableView: UITableView! - - override func viewDidLoad() { - super.viewDidLoad() - manager.register(PostCell.self) - } -} -``` - -ModelType will be automatically gathered from your `PostCell`. If you have a PostCell.xib file, it will be automatically registered for PostCell. If you have a storyboard with PostCell, set it's reuseIdentifier to be identical to class - "PostCell". - -* Add your posts! - -```swift - manager.memoryStorage.addItems(posts) -``` - -That's it! It's that easy! - -## Usage - -### Mapping and registration - -* `register(_:)` -* `registerNibNamed(_:for:)` -* `registerHeader(_:)` -* `registerNibNamed(_:forHeader:)` -* `registerFooter(_:)` -* `registerNibNamed(_:forFooter:)` -* `registerNiblessHeader(_:)` -* `registerNiblessFooter(_:)` - -By default, `DTTableViewManager` uses section titles and `tableView(_:titleForHeaderInSection:)` UITableViewDatasource methods. However, if you call any mapping methods for headers or footers, it will automatically switch to using `tableView(_:viewForHeaderInSection:)` methods and dequeue `UITableViewHeaderFooterView` instances. Make your `UITableViewHeaderFooterView` subclasses conform to `ModelTransfer` protocol to allow them participate in mapping. - -You can also use UIView subclasses for headers and footers. - -### Data models - -`DTTableViewManager` supports all Swift and Objective-C types as data models. This also includes protocols and subclasses. - -```swift -protocol Food {} -class Apple : Food {} -class Carrot: Food {} - -class FoodTableViewCell : UITableViewCell, ModelTransfer { - func update(with model: Food) { - // Display food in a cell - } -} -manager.register(FoodTableViewCell.self) -manager.memoryStorage.addItems([Apple(),Carrot()]) -``` - -## Storage classes - -[DTModelStorage](https://github.com/DenTelezhkin/DTModelStorage/) is a framework, that provides storage classes for `DTTableViewManager`. By default, storage property on `DTTableViewManager` holds a `MemoryStorage` instance. - -### MemoryStorage - -`MemoryStorage` is a class, that manages UITableView models in memory. It has methods for adding, removing, replacing, reordering table view models etc. You can read all about them in [DTModelStorage repo](https://github.com/DenTelezhkin/DTModelStorage#memorystorage). Basically, every section in `MemoryStorage` is an array of `SectionModel` objects, which itself is an object that contains array of table items. - -### CoreDataStorage - -`CoreDataStorage` is meant to be used with `NSFetchedResultsController`. It automatically monitors all NSFetchedResultsControllerDelegate methods and updates UI accordingly to it's changes. All you need to do to display CoreData models in your UITableView, is create CoreDataStorage object and set it on your `storage` property of `DTTableViewManager`. - -It also recommended to use built-in CoreData updater to properly update UITableView: - -```swift -manager.tableViewUpdater = manager.coreDataUpdater() -``` - -Standard flow for creating `CoreDataStorage` can be something like this: - -```swift -let request = NSFetchRequest() -request.entity = NSEntityDescription.entity(forEntityName: String(Post.self), in: context) -request.fetchBatchSize = 20 -request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] -let fetchResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) -_ = try? fetchResultsController.performFetch() - -manager.storage = CoreDataStorage(fetchedResultsController: fetchResultsController) -``` - -Keep in mind, that MemoryStorage is not limited to objects in memory. For example, if you have CoreData database, and you now for sure, that number of items is not big, you can choose not to use CoreDataStorage and NSFetchedResultsController. You can fetch all required models, and store them in MemoryStorage. - -### RealmStorage - -`RealmStorage` is a class, that is meant to be used with [realm.io](https://realm.io) databases. To use `RealmStorage` with `DTTableViewManager`, add following line to your Podfile: - -```ruby - pod 'DTModelStorage/Realm' -``` - -### Diffable datasources in iOS 13 - -Diffable datasources is a cool new feature, that is introduced in UIKit in iOS / tvOS 13. `DTTableViewManager 7` provides a powerful integration layer with it, but in order to understand how this layer works, it's highly recommended to check out great [Advances in UI Data Sources WWDC session](https://developer.apple.com/videos/play/wwdc2019/220/). - -If you don't use `DTTableViewManager`, you would typically create diffable datasource like so (taken from Apple's sample code on diffable datasources): - -```swift -dataSource = UICollectionViewDiffableDataSource - (collectionView: mountainsCollectionView) { - (collectionView: UICollectionView, indexPath: IndexPath, - mountain: MountainsController.Mountain) -> UICollectionViewCell? in - guard let mountainCell = collectionView.dequeueReusableCell( - withReuseIdentifier: LabelCell.reuseIdentifier, for: indexPath) as? LabelCell else { - fatalError("Cannot create new cell") } - mountainCell.label.text = mountain.name - return mountainCell -} -``` - -One of `DTTableViewManager`s main goals is to get rid of String identifiers, and to handle cell creation, as well as updating cell with it's model, for you. Which is why with DTTableViewManager 7 code, equivalent to one above, is the following: - -```swift -dataSource = manager.configureDiffableDataSource { indexPath, model in - return model -} -``` - -You should persist strong reference to `dataSource` object, and use it for constructing sections and items exactly as described in Apple documentation and WWDC session. - -Diffable datasources and `DTTableViewManager 7` are tightly integrated, so all events, even datasource ones like `manager.configure(_:)`, continue to work in the same way as they were working before. - -On top of that, there is an additional functionality, that currently `UITableViewDiffableDataSource` class does not provide. It's currently not possible to use it and have section titles/headers/footers in `UITableView`. With `DTTableViewManager` however, it works just as you would expect: - -```swift -manager.supplementaryStorage?.setSectionHeaderModels(["Foo"]) -``` - -Both events and section header/footer integration is possible, because `DTTableViewManager` injects a special `ProxyDiffableDataSourceStorage` object between `UITableViewDiffableDataSource` and `UITableView`. This storage does not store data models and just queries diffable data source to receive them. It does, however, implement section header and footer model providers, which unlocks possibility to have section titles/headers/footers when using diffable datasources. - -`DTTableViewManager` supports both generic `UITableViewDiffableDataSource` and non-generic `UITableViewDiffableDataSourceReference` with the same method name(`configureDiffableDataSource`). Resulting diffable datasource type is inferred from your declaration of the datasource. - -Keep in mind, that for diffable datasources, `tableViewUpdater` property will contain nil, since UI updates are handled by diffable datasource itself. - -## Reacting to events - -Event system in DTTableViewManager 5 allows you to react to `UITableViewDelegate` and `UITableViewDataSource` events based on view and model types, completely bypassing any switches or ifs when working with UITableView API. For example: - -```swift -manager.didSelect(PostCell.self) { cell, model, indexPath in - print("Selected PostCell with \(model) at \(indexPath)") -} -``` - -**Important** - -While it's possible to register multiple closures for a single event, only first closure will be called once event is fired. This means that if the same event has two closures for the same view/model type, last one will be ignored. You can still register multiple event handlers for a single event and different view/model types. You can see how reactions are being searched for in [DTModelStorage EventReaction extension](https://github.com/DenTelezhkin/DTModelStorage/blob/master/Sources/DTModelStorage/EventReactions.swift#L155-L166). - -### Event types - -There are two types of events: - -1. Event where we have underlying view at runtime -1. Event where we have only data model, because view has not been created yet. - -In the first case, we are able to check view and model types, and pass them into closure. In the second case, however, if there's no view, we can't make any guarantees of which type it will be, therefore it loses view generic type and is not passed to closure. These two types of events have different signature, for example: - -```swift -// Signature for didSelect event -// We do have a cell, when UITableView calls "tableView(_:didSelectRowAt:)" method -open func didSelect(_ cellClass: T.Type, _ closure: @escaping (T,T.ModelType, IndexPath) -> Void) where T:UITableViewCell - - -// Signature for heightForCell event -// When UITableView calls "tableView(_:heightForRowAt:)" method, cell is not created yet, so closure contains two arguments instead of three, and there are no guarantees made about cell type, only model type -open func heightForCell(withItem itemType: T.Type, _ closure: @escaping (T, IndexPath) -> CGFloat) -``` - -It's also important to understand, that event system is implemented using `responds(to:)` method override and is working on the following rules: - -* If `DTTableViewManageable` is implementing delegate method, `responds(to:)` returns true -* If `DTTableViewManager` has events tied to selector being called, `responds(to:)` also returns true - -What this approach allows us to do, is configuring UITableView knowledge about what delegate method is implemented and what is not. For example, `DTTableViewManager` is implementing `tableView(_:heightForRowAt:)` method, however if you don't call `heightForCell(withItem:_:)` method, you are safe to use self-sizing cells in UITableView. While all delegate methods are implemented, only those that have events or are implemented by delegate will be called by `UITableView`. - -`DTTableViewManager` has the same approach for handling each delegate and datasource method: - -* Try to execute event, if cell and model type satisfy requirements -* Try to call delegate or datasource method on `DTTableViewManageable` instance -* If two previous scenarios fail, fallback to whatever default `UITableView` has for this delegate or datasource method - -### Events configuration - -To have compile safety when registering events, you can use `configureEvents` method: - -```swift -manager.configureEvents(for: IntCell.self) { cellType, modelType in - manager.register(cellType) - manager.estimatedHeight(for: modelType) { _,_ in - return 44 - } -} -``` - -## Advanced usage - -### Drag and Drop in iOS 11 - -There is a [dedicated repo](https://github.com/DenTelezhkin/DTDragAndDropExample), containing Apple's sample on Drag&Drop, enhanced with `DTTableViewManager` and `DTCollectionViewManager`. Most of the stuff is just usual drop and drag delegate events, but there is also special support for UITableView and UICollectionView placeholders, that makes sure calls are dispatched to main thread, and if you use `MemoryStorage`, performs datasource updates automatically. - -### Reacting to content updates - -Sometimes it's convenient to know, when data is updated, for example to hide UITableView, if there's no data. `TableViewUpdater` has `willUpdateContent` and `didUpdateContent` properties, that can help: - -```swift -updater.willUpdateContent = { update in - print("UI update is about to begin") -} - -updater.didUpdateContent = { update in - print("UI update finished") -} -``` - -### Customizing UITableView updates - -`DTTableViewManager` uses `TableViewUpdater` class by default. However for `CoreData` you might want to tweak UI updating code. For example, when reloading cell, you might want animation to occur, or you might want to silently update your cell. This is actually how [Apple's guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/nsfetchedresultscontroller.html) for `NSFetchedResultsController` suggests you should do. Another interesting thing it suggests that .Move event reported by NSFetchedResultsController should be animated not as a move, but as deletion of old index path and insertion of new one. - -If you want to work with CoreData and NSFetchedResultsController, just call: - -```swift -manager.tableViewUpdater = manager.coreDataUpdater() -``` - -`TableViewUpdater` constructor allows customizing it's basic behaviour: - -```swift -let updater = TableViewUpdater(tableView: tableView, reloadRow: { indexPath in - // Reload row -}, animateMoveAsDeleteAndInsert: false) -``` - -These are all default options, however you might implement your own implementation of `TableViewUpdater`, the only requirement is that object needs to conform to `StorageUpdating` protocol. This gives you full control on how and when `DTTableViewManager` will update `UITableView`. - -`TableViewUpdater` also contains all animation options, that can be changed, for example: - -```swift -updater.deleteSectionAnimation = UITableViewRowAnimation.fade -updater.insertRowAnimation = UITableViewRowAnimation.automatic -``` - -### Display header on empty section - -By default, headers are displayed if there's header model for them in section, even if there are no items in section. This behaviour can be changed: - -```swift -manager.configuration.displayHeaderOnEmptySection = false -// or -manager.configuration.displayFooterOnEmptySection = false -``` - -Also you can use simple String models for header and footer models, without any registration, and they will be used in `tableView(_:titleForHeaderInSection:)` method automatically. - -### Conditional mappings - -There can be cases, where you might want to customize mappings based on some criteria. For example, you might want to display model in several kinds of cells for different sections: - -```swift -class FoodTextCell: UITableViewCell, ModelTransfer { - func update(with model: Food) { - // Text representation - } -} - -class FoodImageCell: UITableViewCell, ModelTransfer { - func update(with model: Food) { - // Photo representation - } -} - -manager.register(FoodTextCell.self) { mapping in mapping.condition = .section(0) } -manager.register(FoodImageCell.self) { mapping in mapping.condition = .section(1) } -``` - -Or you may implement completely custom conditions: - -```swift -manager.register(FooCell.self) { mapping in - mapping.condition = .custom({ indexPath, model in - guard let model = model as? Int else { return false } - return model > 2 - }) -} -``` - -You can also change reuseIdentifier to be used: - -```swift -manager.register(NibCell.self) { mapping in - mapping.condition = .section(0) - mapping.reuseIdentifier = "NibCell One" -} -controller.manager.registerNibNamed("CustomNibCell", for: NibCell.self) { mapping in - mapping.condition = .section(1) - mapping.reuseIdentifier = "NibCell Two" -} -``` - -### Anomaly handler - -`DTTableViewManager` is built on some conventions. For example, your cell needs to have reuseIdentifier that matches the name of your class, XIB files need to be named also identical to the name of your class(to work with default mapping without customization). However when those conventions are not followed, or something unexpected happens, your app may crash or behave inconsistently. Most of the errors are reported by `UITableView` API, but there's space to improve. - - `DTTableViewManager` as well as `DTCollectionViewManager` and `DTModelStorage` have dedicated anomaly analyzers, that try to find inconsistencies and programmer errors when using those frameworks. They detect stuff like missing mappings, inconsistencies in xib files, and even unused events. By default, detected anomalies will be printed in console while you are debugging your app. For example, if you try to register an empty xib to use for your cell, here's what you'll see in console: - -``` -⚠️[DTTableViewManager] Attempted to register xib EmptyXib for PostCell, but this xib does not contain any views. -``` - -Messages are prefixed, so for `DTCollectionViewManager` messages will have `[DTCollectionViewManager]` prefix. - -By default, anomaly handler only prints information into console and does not do anything beyond that, but you can change it's behavior by assigning a custom handler for anomalies: - -```swift -manager.anomalyHandler.anomalyAction = { anomaly in - // invoke custom action -} -``` - -For example, you may want to send all detected anomalies to analytics you have in your app. For this case anomalies implement shorter description, that is more suitable for analytics, that often have limits for amount of data you can put in. To do that globally for all instances of `DTTableViewManager` that will be created during runtime of your app, set default action: - -```swift -DTTableViewManagerAnomalyHandler.defaultAction = { anomaly in - print(anomaly.debugDescription) - - analytics.postEvent("DTTableViewManager", anomaly.description) -} -``` - -If you use `DTTableViewManager` and `DTCollectionViewManager`, you can override 3 default actions for both manager frameworks and `DTModelStorage`, presumably during app initialization, before any views are loaded: - -```swift -DTTableViewManagerAnomalyHandler.defaultAction = { anomaly in } -DTCollectionViewManagerAnomalyHandler.defaultAction = { anomaly in } -MemoryStorageAnomalyHandler.defaultAction = { anomaly in } -``` - -### Unregistering mappings - -You can unregister cells, headers and footers from `DTTableViewManager` and `UITableView` by calling: - -```swift -manager.unregister(FooCell.self) -manager.unregisterHeader(HeaderView.self) -manager.unregisterFooter(FooterView.self) -``` - -This is equivalent to calling `tableView(register:nil,forCellWithReuseIdenfier: "FooCell")` - -## Thanks - -* [Alexey Belkevich](https://github.com/belkevich) for providing initial implementation of CellFactory. -* [Michael Fey](https://github.com/MrRooni) for providing insight into NSFetchedResultsController updates done right. -* [Nickolay Sheika](https://github.com/hawk-ukr) for great feedback, that helped shaping 3.0 release. -* [Artem Antihevich](https://github.com/sinarionn) for great discussions about Swift generics and type capturing. diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift deleted file mode 100644 index 6eec3b4..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/BackwardsCompatibility.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// BackwardsCompatibility.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 30.03.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension DTTableViewManager { -#if swift(>=4.2) - @available(*, unavailable, message: "This method was removed, please use editingStyle(forItem:,_:) instead.") - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:editingStyleForRowAt:)` method is called for `cellClass`. - open func editingStyle(for cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> UITableViewCell.EditingStyle) where T: UITableViewCell {} -#else - @available(*, unavailable, message: "This method was removed, please use editingStyle(forItem:,_:) instead.") - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:editingStyleForRowAt:)` method is called for `cellClass`. - open func editingStyle(for cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> UITableViewCellEditingStyle) where T: UITableViewCell {} -#endif - -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift deleted file mode 100644 index fded2c2..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDataSource.swift +++ /dev/null @@ -1,140 +0,0 @@ -// -// DTTableViewDataSource.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 13.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import DTModelStorage - -/// Object, that implements `UITableViewDataSource` methods for `DTTableViewManager`. -open class DTTableViewDataSource : DTTableViewDelegateWrapper, UITableViewDataSource { - - override func delegateWasReset() { - tableView?.dataSource = nil - tableView?.dataSource = self - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return storage?.numberOfItems(inSection: section) ?? 0 - } - - /// Implementation for `UITableViewDataSource` protocol - open func numberOfSections(in tableView: UITableView) -> Int { - return storage?.numberOfSections() ?? 0 - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - guard let model = RuntimeHelper.recursivelyUnwrapAnyValue(storage?.item(at: indexPath) as Any) else { - manager?.anomalyHandler.reportAnomaly(.nilCellModel(indexPath)) - return UITableViewCell() - } - guard let cell = viewFactory?.cellForModel(model, atIndexPath: indexPath) else { - return UITableViewCell() - } - _ = tableViewEventReactions.performReaction(of: .cell, signature: EventMethodSignature.configureCell.rawValue, view: cell, model: model, location: indexPath) - return cell - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { - if configuration?.sectionHeaderStyle == .view { return nil } - - return headerModel(forSection: section) as? String - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { - if configuration?.sectionFooterStyle == .view { return nil } - - return footerModel(forSection: section) as? String - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { - _ = perform4ArgumentCellReaction(.moveRowAtIndexPathToIndexPath, - argument: destinationIndexPath, - location: sourceIndexPath, - provideCell: true) - (delegate as? UITableViewDataSource)?.tableView?(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath) - } - -#if swift(>=4.2) - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { - defer { (delegate as? UITableViewDataSource)?.tableView?(tableView, commit: editingStyle, forRowAt: indexPath) } - _ = perform4ArgumentCellReaction(.commitEditingStyleForRowAtIndexPath, - argument: editingStyle, - location: indexPath, - provideCell: true) - } -#else - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - defer { (delegate as? UITableViewDataSource)?.tableView?(tableView, commit: editingStyle, forRowAt: indexPath) } - _ = perform4ArgumentCellReaction(.commitEditingStyleForRowAtIndexPath, - argument: editingStyle, - location: indexPath, - provideCell: true) - } -#endif - - - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { - if let canEdit = performCellReaction(.canEditRowAtIndexPath, location: indexPath, provideCell: false) as? Bool { - return canEdit - } - return (delegate as? UITableViewDataSource)?.tableView?(tableView, canEditRowAt: indexPath) ?? false - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { - if let canMove = performCellReaction(.canMoveRowAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return canMove - } - return (delegate as? UITableViewDataSource)?.tableView?(tableView, canMoveRowAt: indexPath) ?? false - } - - #if os(iOS) - /// Implementation for `UITableViewDataSource` protocol - open func sectionIndexTitles(for tableView: UITableView) -> [String]? { - if let _ = tableViewEventReactions.first(where: { $0.methodSignature == EventMethodSignature.sectionIndexTitlesForTableView.rawValue }) { - return performNonCellReaction(.sectionIndexTitlesForTableView) as? [String] - } - return (delegate as? UITableViewDataSource)?.sectionIndexTitles?(for: tableView) ?? nil - } - - /// Implementation for `UITableViewDataSource` protocol - open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { - if let section = performNonCellReaction(.sectionForSectionIndexTitleAtIndex, - argumentOne: title, - argumentTwo: index) as? Int { - return section - } - return (delegate as? UITableViewDataSource)?.tableView?(tableView, sectionForSectionIndexTitle: title, at: index) ?? 0 - } - #endif -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift deleted file mode 100644 index ed38d33..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegate.swift +++ /dev/null @@ -1,521 +0,0 @@ -// -// DTTableViewDelegate.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 13.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import DTModelStorage - -/// Object, that implements `UITableViewDelegate` for `DTTableViewManager`. -open class DTTableViewDelegate : DTTableViewDelegateWrapper, UITableViewDelegate { - override func delegateWasReset() { - tableView?.delegate = nil - tableView?.delegate = self - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) - { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, willDisplay: cell, forRowAt: indexPath) } - guard let model = storage?.item(at: indexPath) else { return } - _ = tableViewEventReactions.performReaction(of: .cell, signature: EventMethodSignature.willDisplayCellForRowAtIndexPath.rawValue, view: cell, model: model, location: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, willDisplayHeaderView: view, forSection: section) } - guard let model = headerModel(forSection: section) else { return } - _ = tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionHeader), signature: EventMethodSignature.willDisplayHeaderForSection.rawValue, view: view, model: model, location: IndexPath(item: 0, section: section)) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, willDisplayFooterView: view, forSection: section) } - guard let model = footerModel(forSection: section) else { return } - _ = tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionFooter), signature: EventMethodSignature.willDisplayFooterForSection.rawValue, view: view, model: model, location: IndexPath(item: 0, section: section)) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { - if configuration?.sectionHeaderStyle == .title { return nil } - let viewKind = ViewType.supplementaryView(kind: DTTableViewElementSectionHeader) - if let model = headerModel(forSection:section) { - if let createdView = viewFactory?.headerFooterView(of: viewKind, model: model, atIndexPath: IndexPath(index: section)) - { - _ = tableViewEventReactions.performReaction(of: viewKind, - signature: EventMethodSignature.configureHeader.rawValue, - view: createdView, model: model, - location: IndexPath(item: 0, section: section)) - return createdView - } - } else { - if let view = (delegate as? UITableViewDelegate)?.tableView?(tableView, viewForHeaderInSection: section) { - return view - } - if shouldDisplayHeaderView(forSection: section) { - manager?.anomalyHandler.reportAnomaly(.nilHeaderModel(section)) - } - } - return nil - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { - if configuration?.sectionFooterStyle == .title { return nil } - let viewKind = ViewType.supplementaryView(kind: DTTableViewElementSectionFooter) - if let model = footerModel(forSection: section) { - if let createdView = viewFactory?.headerFooterView(of: viewKind, model: model, atIndexPath: IndexPath(index: section)) - { - _ = tableViewEventReactions.performReaction(of: viewKind, - signature: EventMethodSignature.configureFooter.rawValue, - view: createdView, model: model, location: IndexPath(item: 0, section: section)) - return createdView - } - } else { - if let view = (delegate as? UITableViewDelegate)?.tableView?(tableView, viewForFooterInSection: section) { - return view - } - if shouldDisplayFooterView(forSection: section) { - manager?.anomalyHandler.reportAnomaly(.nilFooterModel(section)) - } - } - return nil - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { - guard shouldDisplayHeaderView(forSection: section) else { - return configuration?.minimalHeaderHeightForTableView(tableView) ?? .zero - } - if let height = performHeaderReaction(.heightForHeaderInSection, location: section, provideView: false) as? CGFloat { - return height - } - if let height = (delegate as? UITableViewDelegate)?.tableView?(tableView, heightForHeaderInSection: section) { - return height - } - if configuration?.sectionHeaderStyle == .title { - if let _ = headerModel(forSection:section) - { - #if swift(>=4.2) - return UITableView.automaticDimension - #else - return UITableViewAutomaticDimension - #endif - } - return configuration?.minimalHeaderHeightForTableView(tableView) ?? .zero - } - if let _ = headerModel(forSection:section) { - return tableView.sectionHeaderHeight - } - return configuration?.minimalHeaderHeightForTableView(tableView) ?? .zero - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { - if let height = performHeaderReaction(.estimatedHeightForHeaderInSection, location: section, provideView: false) as? CGFloat { - return height - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, estimatedHeightForHeaderInSection: section) ?? tableView.estimatedSectionHeaderHeight - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { - guard shouldDisplayFooterView(forSection: section) else { - return configuration?.minimalFooterHeightForTableView(tableView) ?? .zero - } - if let height = performFooterReaction(.heightForFooterInSection, location: section, provideView: false) as? CGFloat { - return height - } - if let height = (delegate as? UITableViewDelegate)?.tableView?(tableView, heightForFooterInSection: section) { - return height - } - if configuration?.sectionFooterStyle == .title { - if let _ = footerModel(forSection:section) { - #if swift(>=4.2) - return UITableView.automaticDimension - #else - return UITableViewAutomaticDimension - #endif - } - return configuration?.minimalFooterHeightForTableView(tableView) ?? .zero - } - - if let _ = footerModel(forSection:section) { - return tableView.sectionFooterHeight - } - return configuration?.minimalFooterHeightForTableView(tableView) ?? .zero - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { - if let height = performFooterReaction(.estimatedHeightForFooterInSection, location: section, provideView: false) as? CGFloat { - return height - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, estimatedHeightForFooterInSection: section) ?? tableView.estimatedSectionFooterHeight - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { - if let eventReaction = cellReaction(.willSelectRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(eventReaction, location: indexPath, provideCell: true) as? IndexPath - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, willSelectRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? { - if let eventReaction = cellReaction(.willDeselectRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(eventReaction, location: indexPath, provideCell: true) as? IndexPath - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, willDeselectRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - _ = performCellReaction(.didSelectRowAtIndexPath, location: indexPath, provideCell: true) - (self.delegate as? UITableViewDelegate)?.tableView?(tableView, didSelectRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { - _ = performCellReaction(.didDeselectRowAtIndexPath, location: indexPath, provideCell: true) - (self.delegate as? UITableViewDelegate)?.tableView?(tableView, didDeselectRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { - if let height = performCellReaction(.heightForRowAtIndexPath, location: indexPath, provideCell: false) as? CGFloat { - return height - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, heightForRowAt: indexPath) ?? tableView.rowHeight - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { - if let height = performCellReaction(.estimatedHeightForRowAtIndexPath, location: indexPath, provideCell: false) as? CGFloat { - return height - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, estimatedHeightForRowAt: indexPath) ?? tableView.estimatedRowHeight - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { - if let level = performCellReaction(.indentationLevelForRowAtIndexPath, location: indexPath, provideCell: false) as? Int { - return level - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, indentationLevelForRowAt: indexPath) ?? 0 - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { - _ = performCellReaction(.accessoryButtonTappedForRowAtIndexPath, location: indexPath, provideCell: true) - (delegate as? UITableViewDelegate)?.tableView?(tableView, accessoryButtonTappedForRowWith: indexPath) - } - -#if os(iOS) - @available(iOS, deprecated: 13.0) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { - if let eventReaction = cellReaction(.editActionsForRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(eventReaction, location: indexPath, provideCell: true) as? [UITableViewRowAction] - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, editActionsForRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { - _ = performCellReaction(.willBeginEditingRowAtIndexPath, location: indexPath, provideCell: true) - (delegate as? UITableViewDelegate)?.tableView?(tableView, willBeginEditingRowAt: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didEndEditingRowAt: indexPath) } - guard let indexPath = indexPath else { return } - _ = performCellReaction(.didEndEditingRowAtIndexPath, location: indexPath, provideCell: true) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { - if let eventReaction = cellReaction(.titleForDeleteButtonForRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(eventReaction, location: indexPath, provideCell: true) as? String - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, titleForDeleteConfirmationButtonForRowAt: indexPath) - } -#endif - -#if swift(>=4.2) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { - if let editingStyle = performCellReaction(.editingStyleForRowAtIndexPath, location: indexPath, provideCell: false) as? UITableViewCell.EditingStyle { - return editingStyle - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, editingStyleForRowAt: indexPath) ?? .none - } -#else - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { - if let editingStyle = performCellReaction(.editingStyleForRowAtIndexPath, location: indexPath, provideCell: false) as? UITableViewCellEditingStyle { - return editingStyle - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, editingStyleForRowAt: indexPath) ?? .none - } -#endif - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { - if let should = performCellReaction(.shouldIndentWhileEditingRowAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, shouldIndentWhileEditingRowAt: indexPath) ?? tableView.cellForRow(at: indexPath)?.shouldIndentWhileEditing ?? true - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didEndDisplaying: cell, forRowAt: indexPath) } - guard let model = storage?.item(at: indexPath) else { return } - _ = tableViewEventReactions.performReaction(of: .cell, signature: EventMethodSignature.didEndDisplayingCellForRowAtIndexPath.rawValue, view: cell, model: model, location: indexPath) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didEndDisplayingHeaderView: view, forSection: section) } - guard let model = headerModel(forSection: section) else { return } - _ = tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionHeader), signature: EventMethodSignature.didEndDisplayingHeaderViewForSection.rawValue, view: view, model: model, location: IndexPath(item: 0, section: section)) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didEndDisplayingFooterView: view, forSection: section) } - guard let model = footerModel(forSection: section) else { return } - _ = tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionFooter), signature: EventMethodSignature.didEndDisplayingFooterViewForSection.rawValue, view: view, model: model, location: IndexPath(item: 0, section: section)) - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { - if let should = performCellReaction(.shouldShowMenuForRowAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, shouldShowMenuForRowAt: indexPath) ?? false - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { - if let canPerform = perform5ArgumentCellReaction(.canPerformActionForRowAtIndexPath, - argumentOne: action, - argumentTwo: sender as Any, - location: indexPath, - provideCell: true) as? Bool { - return canPerform - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, canPerformAction: action, forRowAt: indexPath, withSender: sender) ?? false - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, performAction: action, forRowAt: indexPath, withSender: sender) } - _ = perform5ArgumentCellReaction(.performActionForRowAtIndexPath, - argumentOne: action, - argumentTwo: sender as Any, - location: indexPath, - provideCell: true) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { - if let should = performCellReaction(.shouldHighlightRowAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, shouldHighlightRowAt: indexPath) ?? true - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didHighlightRowAt: indexPath) } - _ = performCellReaction(.didHighlightRowAtIndexPath, location: indexPath, provideCell: true) - } - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) { - defer { (delegate as? UITableViewDelegate)?.tableView?(tableView, didUnhighlightRowAt: indexPath) } - _ = performCellReaction(.didUnhighlightRowAtIndexPath, location: indexPath, provideCell: true) - } - - @available(iOS 9.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { - if let should = performCellReaction(.canFocusRowAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, canFocusRowAt: indexPath) ?? tableView.cellForRow(at: indexPath)?.canBecomeFocused ?? true - } -#if os(iOS) - @available (iOS 11, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - if let reaction = cellReaction(.leadingSwipeActionsConfigurationForRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(reaction, location: indexPath, provideCell: true) as? UISwipeActionsConfiguration - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, - leadingSwipeActionsConfigurationForRowAt: indexPath) - } - - @available (iOS 11, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { - if let reaction = cellReaction(.trailingSwipeActionsConfigurationForRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(reaction, location: indexPath, provideCell: true) as? UISwipeActionsConfiguration - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, - trailingSwipeActionsConfigurationForRowAt: indexPath) - } - - @available (iOS 11, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldSpringLoadRowAt indexPath: IndexPath, with context: UISpringLoadedInteractionContext) -> Bool { - if let shouldSpringLoad = perform4ArgumentCellReaction(.shouldSpringLoadRowAtIndexPathWithContext, - argument: context, - location: indexPath, - provideCell: true) as? Bool { - return shouldSpringLoad - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, - shouldSpringLoadRowAt:indexPath, - with: context) ?? true - } -#endif - - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { - if let indexPath = perform4ArgumentCellReaction(.targetIndexPathForMoveFromRowAtIndexPath, - argument: proposedDestinationIndexPath, - location: sourceIndexPath, - provideCell: true) as? IndexPath { - return indexPath - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, - targetIndexPathForMoveFromRowAt: sourceIndexPath, - toProposedIndexPath: proposedDestinationIndexPath) ?? IndexPath(item: 0, section: 0) - } - - @available(iOS 9, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldUpdateFocusIn context: UITableViewFocusUpdateContext) -> Bool { - if let should = performNonCellReaction(.shouldUpdateFocusInContext, argument: context) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, shouldUpdateFocusIn:context) ?? true - } - - @available(iOS 9, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didUpdateFocusIn context: UITableViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { - _ = performNonCellReaction(.didUpdateFocusInContextWithAnimationCoordinator, - argumentOne: context, - argumentTwo: coordinator) - (delegate as? UITableViewDelegate)?.tableView?(tableView, - didUpdateFocusIn: context, - with: coordinator) - } - - @available(iOS 9, *) - /// Implementation for `UITableViewDelegate` protocol - open func indexPathForPreferredFocusedView(in tableView: UITableView) -> IndexPath? { - if let reaction = tableViewEventReactions.first(where: { $0.methodSignature == EventMethodSignature.indexPathForPreferredFocusedViewInTableView.rawValue }) { - return reaction.performWithArguments((0, 0, 0)) as? IndexPath - } - return (delegate as? UITableViewDelegate)?.indexPathForPreferredFocusedView?(in: tableView) - } - -#if compiler(>=5.1) && os(iOS) - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, shouldBeginMultipleSelectionInteractionAt indexPath: IndexPath) -> Bool { - if let should = performCellReaction(.shouldBeginMultipleSelectionInteractionAtIndexPath, location: indexPath, provideCell: true) as? Bool { - return should - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, shouldBeginMultipleSelectionInteractionAt: indexPath) ?? false - } - - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, didBeginMultipleSelectionInteractionAt indexPath: IndexPath) { - _ = performCellReaction(.didBeginMultipleSelectionInteractionAtIndexPath, location: indexPath, provideCell: true) - (delegate as? UITableViewDelegate)?.tableView?(tableView, didBeginMultipleSelectionInteractionAt: indexPath) - } - - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableViewDidEndMultipleSelectionInteraction(_ tableView: UITableView) { - _ = performNonCellReaction(.didEndMultipleSelectionInteraction) - (delegate as? UITableViewDelegate)?.tableViewDidEndMultipleSelectionInteraction?(tableView) - } - - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { - if let configuration = perform4ArgumentCellReaction(.contextMenuConfigurationForRowAtIndexPath, - argument: point, - location: indexPath, - provideCell: true) as? UIContextMenuConfiguration { - return configuration - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, - contextMenuConfigurationForRowAt: indexPath, - point: point) - } - - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - if let preview = performNonCellReaction(.previewForHighlightingContextMenu, argument: configuration) as? UITargetedPreview { - return preview - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, previewForHighlightingContextMenuWithConfiguration: configuration) - } - - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? { - if let preview = performNonCellReaction(.previewForDismissingContextMenu, argument: configuration) as? UITargetedPreview { - return preview - } - return (delegate as? UITableViewDelegate)?.tableView?(tableView, previewForDismissingContextMenuWithConfiguration: configuration) - } - #if compiler(<5.1.2) - @available(iOS 13.0, *) - /// Implementation for `UITableViewDelegate` protocol - open func tableView(_ tableView: UITableView, willCommitMenuWithAnimator animator: UIContextMenuInteractionCommitAnimating) { - _ = performNonCellReaction(.willCommitMenuWithAnimator, argument: animator) - (delegate as? UITableViewDelegate)?.tableView?(tableView, - willCommitMenuWithAnimator: animator) - } - #endif -#endif -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift deleted file mode 100644 index 5bc1ca1..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDelegateWrapper.swift +++ /dev/null @@ -1,304 +0,0 @@ -// -// File.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 13.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import DTModelStorage - -/// Base class for objects, that implement various datasource and delegate methods from `UITableView`. Even though this class is declared as `open`, subclassing it is discouraged. Please subsclass concrete subclass of this class, such as `DTTableViewDelegate`. -open class DTTableViewDelegateWrapper : NSObject { - weak var delegate: AnyObject? - var tableView: UITableView? { return manager?.tableView } - var viewFactory: TableViewFactory? { return manager?.viewFactory } - var storage: Storage? { return manager?.storage } - var configuration: TableViewConfiguration? { return manager?.configuration } - weak var manager: DTTableViewManager? - - /// Creates base wrapper for datasource and delegate implementations - public init(delegate: AnyObject?, tableViewManager: DTTableViewManager) { - self.delegate = delegate - manager = tableViewManager - } - - /// Array of `UITableViewDataSource` reactions for `DTTableViewDataSource` - /// - SeeAlso: `EventReaction`. - final var tableViewEventReactions = ContiguousArray() { - didSet { - delegateWasReset() - } - } - - func delegateWasReset() { - // Subclasses need to override this method, resetting `UITableView` delegate or datasource. - // Resetting delegate is needed, because UITableView caches results of `respondsToSelector` call, and never calls it again until `setDelegate` method is called. - // We force UITableView to flush that cache and query us again, because with new event we might have new delegate or datasource method to respond to. - } - - func shouldDisplayHeaderView(forSection index: Int) -> Bool { - guard let storage = storage, let configuration = configuration else { return false } - if storage.numberOfItems(inSection: index) == 0 && !configuration.displayHeaderOnEmptySection { - return false - } - return true - } - - func shouldDisplayFooterView(forSection index: Int) -> Bool { - guard let storage = storage, let configuration = configuration else { return false } - if storage.numberOfItems(inSection: index) == 0 && !configuration.displayFooterOnEmptySection { - return false - } - return true - } - - /// Returns header model for section at `index`, or nil if it is not found. - /// - /// If `TableViewConfiguration` `displayHeaderOnEmptySection` is false, this method also returns nil. - final func headerModel(forSection index: Int) -> Any? - { - if !shouldDisplayHeaderView(forSection: index) { return nil } - return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.headerModel(forSection: index) as Any) - } - - /// Returns footer model for section at `index`, or nil if it is not found. - /// - /// If `TableViewConfiguration` `displayFooterOnEmptySection` is false, this method also returns nil. - final func footerModel(forSection index: Int) -> Any? - { - if !shouldDisplayFooterView(forSection: index) { return nil } - return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.footerModel(forSection: index) as Any) - } - - final internal func appendReaction(for cellClass: T.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (T, T.ModelType, IndexPath) -> U) where T: ModelTransfer, T:UITableViewCell - { - let reaction = EventReaction(signature: signature.rawValue, viewType: .cell, viewClass: T.self) - reaction.makeReaction(closure) - tableViewEventReactions.append(reaction) - manager?.verifyViewEvent(for: T.self, methodName: methodName) - } - - final internal func append4ArgumentReaction - (for cellClass: CellClass.Type, - signature: EventMethodSignature, - methodName: String = #function, - closure: @escaping (Argument, CellClass, CellClass.ModelType, IndexPath) -> Result) - where CellClass: ModelTransfer, CellClass: UITableViewCell - { - let reaction = FourArgumentsEventReaction(signature: signature.rawValue, - viewType: .cell, - viewClass: CellClass.self) - reaction.make4ArgumentsReaction(closure) - tableViewEventReactions.append(reaction) - manager?.verifyViewEvent(for: CellClass.self, methodName: methodName) - } - - final internal func append5ArgumentReaction - (for cellClass: CellClass.Type, - signature: EventMethodSignature, - methodName: String = #function, - closure: @escaping (ArgumentOne, ArgumentTwo, CellClass, CellClass.ModelType, IndexPath) -> Result) - where CellClass: ModelTransfer, CellClass: UITableViewCell - { - let reaction = FiveArgumentsEventReaction(signature: signature.rawValue, - viewType: .cell, - viewClass: CellClass.self) - reaction.make5ArgumentsReaction(closure) - tableViewEventReactions.append(reaction) - manager?.verifyViewEvent(for: CellClass.self, methodName: methodName) - } - - final internal func appendReaction(for modelClass: T.Type, - signature: EventMethodSignature, - methodName: String = #function, - closure: @escaping (T, IndexPath) -> U) - { - let reaction = EventReaction(signature: signature.rawValue, viewType: .cell, modelType: T.self) - reaction.makeReaction(closure) - tableViewEventReactions.append(reaction) - manager?.verifyItemEvent(for: T.self, eventMethod: methodName) - } - - final func appendReaction(forSupplementaryKind kind: String, - supplementaryClass: T.Type, - signature: EventMethodSignature, - methodName: String = #function, - closure: @escaping (T, T.ModelType, Int) -> U) where T: ModelTransfer, T: UIView - { - let reaction = EventReaction(signature: signature.rawValue, viewType: .supplementaryView(kind: kind), viewClass: T.self) - let indexPathBlock : (T, T.ModelType, IndexPath) -> U = { cell, model, indexPath in - return closure(cell, model, indexPath.section) - } - reaction.makeReaction(indexPathBlock) - tableViewEventReactions.append(reaction) - manager?.verifyViewEvent(for: T.self, methodName: methodName) - } - - final func appendReaction(forSupplementaryKind kind: String, - modelClass: T.Type, - signature: EventMethodSignature, - methodName: String = #function, - closure: @escaping (T, Int) -> U) - { - let reaction = EventReaction(signature: signature.rawValue, viewType: .supplementaryView(kind: kind), modelType: T.self) - let indexPathBlock : (T, IndexPath) -> U = { model, indexPath in - return closure(model, indexPath.section) - } - reaction.makeReaction(indexPathBlock) - tableViewEventReactions.append(reaction) - manager?.verifyItemEvent(for: T.self, eventMethod: methodName) - } - - final func appendNonCellReaction(_ signature: EventMethodSignature, closure: @escaping () -> Any) { - let reaction = EventReaction(signature: signature.rawValue, viewType: .cell, modelType: Any.self) - reaction.reaction = { _, _, _ in - return closure() - } - tableViewEventReactions.append(reaction) - } - - final func appendNonCellReaction(_ signature: EventMethodSignature, closure: @escaping (Arg) -> Any) { - let reaction = EventReaction(signature: signature.rawValue, viewType: .cell, modelType: Any.self) - reaction.reaction = { arg, _, _ in - guard let arg = arg as? Arg else { return nil as Any? as Any } - return closure(arg) - } - tableViewEventReactions.append(reaction) - } - - final func appendNonCellReaction(_ signature: EventMethodSignature, closure: @escaping (Arg1, Arg2) -> Result) { - let reaction = EventReaction(signature: signature.rawValue, viewType: .cell, modelType: Any.self) - reaction.reaction = { arg1, arg2, _ in - guard let arg1 = arg1 as? Arg1, - let arg2 = arg2 as? Arg2 - else { return nil as Any? as Any } - return closure(arg1, arg2) - } - tableViewEventReactions.append(reaction) - } - - final func performCellReaction(_ signature: EventMethodSignature, location: IndexPath, provideCell: Bool) -> Any? { - var cell : UITableViewCell? - if provideCell { cell = tableView?.cellForRow(at: location) } - guard let model = storage?.item(at: location) else { return nil } - return tableViewEventReactions.performReaction(of: .cell, signature: signature.rawValue, view: cell, model: model, location: location) - } - - final func perform4ArgumentCellReaction(_ signature: EventMethodSignature, argument: Any, location: IndexPath, provideCell: Bool) -> Any? { - var cell : UITableViewCell? - if provideCell { cell = tableView?.cellForRow(at: location) } - guard let model = storage?.item(at: location) else { return nil } - return tableViewEventReactions.perform4ArgumentsReaction(of: .cell, - signature: signature.rawValue, - argument: argument, - view: cell, - model: model, - location: location) - } - - final func perform5ArgumentCellReaction(_ signature: EventMethodSignature, - argumentOne: Any, - argumentTwo: Any, - location: IndexPath, - provideCell: Bool) -> Any? { - var cell : UITableViewCell? - if provideCell { cell = tableView?.cellForRow(at: location) } - guard let model = storage?.item(at: location) else { return nil } - return tableViewEventReactions.perform5ArgumentsReaction(of: .cell, - signature: signature.rawValue, - firstArgument: argumentOne, - secondArgument: argumentTwo, - view: cell, - model: model, - location: location) - } - - final func performNillableCellReaction(_ reaction: EventReaction, location: IndexPath, provideCell: Bool) -> Any? { - var cell : UITableViewCell? - if provideCell { cell = tableView?.cellForRow(at: location) } - guard let model = storage?.item(at: location) else { return nil } - return reaction.performWithArguments((cell as Any, model, location)) - } - - final func cellReaction(_ signature: EventMethodSignature, location: IndexPath) -> EventReaction? { - guard let model = storage?.item(at: location) else { return nil } - return tableViewEventReactions.reaction(of: .cell, signature: signature.rawValue, forModel: model, view: nil) - } - - final func performHeaderReaction(_ signature: EventMethodSignature, location: Int, provideView: Bool) -> Any? { - var view : UIView? - if provideView { - view = tableView?.headerView(forSection: location) - } - guard let model = headerModel(forSection: location) else { return nil } - return tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionHeader), signature: signature.rawValue, view: view, model: model, location: IndexPath(item: 0, section: location)) - } - - final func performFooterReaction(_ signature: EventMethodSignature, location: Int, provideView: Bool) -> Any? { - var view : UIView? - if provideView { - view = tableView?.footerView(forSection: location) - } - guard let model = footerModel(forSection: location) else { return nil } - return tableViewEventReactions.performReaction(of: .supplementaryView(kind: DTTableViewElementSectionFooter), signature: signature.rawValue, view: view, model: model, location: IndexPath(item: 0, section: location)) - } - - func performNonCellReaction(_ signature: EventMethodSignature) -> Any? { - return tableViewEventReactions.first(where: { $0.methodSignature == signature.rawValue })? - .performWithArguments((0, 0, 0)) - } - - func performNonCellReaction(_ signature: EventMethodSignature, argument: T) -> Any? { - return tableViewEventReactions.first(where: { $0.methodSignature == signature.rawValue })? - .performWithArguments((argument, 0, 0)) - } - - func performNonCellReaction(_ signature: EventMethodSignature, argumentOne: T, argumentTwo: U) -> Any? { - return tableViewEventReactions.first(where: { $0.methodSignature == signature.rawValue })? - .performWithArguments((argumentOne, argumentTwo, 0)) - } - - // MARK: - Target Forwarding - - /// Forwards `aSelector`, that is not implemented by `DTTableViewManager` to delegate, if it implements it. - /// - /// - Returns: `DTTableViewManager` delegate - override open func forwardingTarget(for aSelector: Selector) -> Any? { - return delegate - } - - /// Returns true, if `DTTableViewManageable` implements `aSelector`, or `DTTableViewManager` has an event, associated with this selector. - /// - /// - SeeAlso: `EventMethodSignature` - override open func responds(to aSelector: Selector) -> Bool { - if delegate?.responds(to: aSelector) ?? false { - return true - } - if super.responds(to: aSelector) { - if let eventSelector = EventMethodSignature(rawValue: String(describing: aSelector)) { - return tableViewEventReactions.contains(where: { $0.methodSignature == eventSelector.rawValue }) - } - return true - } - return false - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift deleted file mode 100644 index df4ee62..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDragDelegate.swift +++ /dev/null @@ -1,112 +0,0 @@ -// -// DTTableViewDragDelegate.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 20.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import DTModelStorage - -#if os(iOS) - -@available(iOS 11.0, *) - -/// Object, that implements `UITableViewDragDelegate` methods for `DTTableViewManager`. -open class DTTableViewDragDelegate: DTTableViewDelegateWrapper, UITableViewDragDelegate { - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, - at indexPath: IndexPath) -> [UIDragItem] - { - if let items = perform4ArgumentCellReaction(.itemsForBeginningDragSession, - argument: session, - location: indexPath, - provideCell: true) as? [UIDragItem] - { - return items - } - return (delegate as? UITableViewDragDelegate)?.tableView(tableView, itemsForBeginning: session, at:indexPath) ?? [] - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, itemsForAddingTo session: UIDragSession, - at indexPath: IndexPath, - point: CGPoint) -> [UIDragItem] - { - if let items = perform5ArgumentCellReaction(.itemsForAddingToDragSession, - argumentOne: session, - argumentTwo: point, - location: indexPath, - provideCell: true) as? [UIDragItem] { - return items - } - return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, itemsForAddingTo: session, at: indexPath, point: point) ?? [] - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, dragPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? { - if let reaction = cellReaction(.dragPreviewParametersForRowAtIndexPath, location: indexPath) { - return performNillableCellReaction(reaction, location: indexPath, provideCell: true) as? UIDragPreviewParameters - } - return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragPreviewParametersForRowAt: indexPath) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) { - _ = performNonCellReaction(.dragSessionWillBegin, argument: session) - (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionWillBegin: session) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession) { - _ = performNonCellReaction(.dragSessionDidEnd, argument: session) - (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionDidEnd: session) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, dragSessionAllowsMoveOperation session: UIDragSession) -> Bool { - if let allows = performNonCellReaction(.dragSessionAllowsMoveOperation, argument: session) as? Bool { - return allows - } - return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionAllowsMoveOperation: session) ?? true - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDragDelegate` protocol - open func tableView(_ tableView: UITableView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession) -> Bool { - if let allows = performNonCellReaction(.dragSessionIsRestrictedToDraggingApplication, argument: session) as? Bool { - return allows - } - return (delegate as? UITableViewDragDelegate)?.tableView?(tableView, dragSessionIsRestrictedToDraggingApplication: session) ?? false - } - - override func delegateWasReset() { - tableView?.dragDelegate = nil - tableView?.dragDelegate = self - } -} -#endif diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift deleted file mode 100644 index 5d47bd1..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropDelegate.swift +++ /dev/null @@ -1,98 +0,0 @@ -// -// DTTableViewDropDelegate.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 20.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit - -#if os(iOS) -@available(iOS 11.0, *) - -/// Object, that implements `UITableViewDropDelegate` for `DTTableViewManager`. -open class DTTableViewDropDelegate: DTTableViewDelegateWrapper, UITableViewDropDelegate { - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) { - _ = performNonCellReaction(.performDropWithCoordinator, argument: coordinator) - (delegate as? UITableViewDropDelegate)?.tableView(tableView, performDropWith: coordinator) - } - - override func delegateWasReset() { - tableView?.dropDelegate = nil - tableView?.dropDelegate = self - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool { - if let canHandle = performNonCellReaction(.canHandleDropSession, argument: session) as? Bool { - return canHandle - } - return (delegate as? UITableViewDropDelegate)?.tableView?(tableView, canHandle: session) ?? true - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, dropSessionDidEnter session: UIDropSession) { - _ = performNonCellReaction(.dropSessionDidEnter, argument: session) - (delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnter: session) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal { - if let proposal = performNonCellReaction(.dropSessionDidUpdateWithDestinationIndexPath, - argumentOne: session, - argumentTwo: destinationIndexPath) as? UITableViewDropProposal { - return proposal - } - return (delegate as? UITableViewDropDelegate)?.tableView?(tableView, - dropSessionDidUpdate: session, - withDestinationIndexPath: destinationIndexPath) ?? UITableViewDropProposal(operation: .cancel) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, dropSessionDidExit session: UIDropSession) { - _ = performNonCellReaction(.dropSessionDidExit, argument: session) - (delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidExit: session) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession) { - _ = performNonCellReaction(.dropSessionDidEnd, argument: session) - (delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnd: session) - } - - @available(iOS 11.0, *) - /// Implementation for `UITableViewDropDelegate` protocol - open func tableView(_ tableView: UITableView, dropPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? { - if let reaction = tableViewEventReactions.first(where: { $0.methodSignature == EventMethodSignature.dropPreviewParametersForRowAtIndexPath.rawValue }) { - return reaction.performWithArguments((indexPath, 0, 0)) as? UIDragPreviewParameters - } - return (delegate as? UITableViewDropDelegate)?.tableView?(tableView, - dropPreviewParametersForRowAt: indexPath) - } -} -#endif diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift deleted file mode 100644 index 2bad322..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewDropPlaceholderContext.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// DTTableViewDropPlaceholderContext.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 27.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -#if os(iOS) -@available(iOS 11, *) - -/// Thin wrapper around `UITableViewDropPlaceholderContext`, which automates insertion of `dragItems` if you are using `MemoryStorage`. -/// Typically, you would not create this class directly, but use `DTTableViewManager.drop(_:to:with:)` convenience method. -open class DTTableViewDropPlaceholderContext { - - /// Drop context - public let context : UITableViewDropPlaceholderContext - - /// Storage, on which drop operation is performed - weak var storage: Storage? - - /// Creates `DTTableViewDropPlaceholderContext` with `context` and `storage` - public init(context: UITableViewDropPlaceholderContext, storage: Storage?) { - self.context = context - self.storage = storage - } - - /// Commits insertion of item, using `UITableViewDropPlaceholderContext.commitInsertion(_:)` method. Both commit and `insertionIndexPathClosure` will be automatically dispatched to `DispatchQueue.main`. - /// If you are using `MemoryStorage`, model will be automatically inserted, and no additional actions are required. - open func commitInsertion(ofItem item: T, _ insertionIndexPathClosure: ((IndexPath) -> Void)? = nil) { - DispatchQueue.main.async { [weak self] in - self?.context.commitInsertion { insertionIndexPath in - guard let storage = self?.storage else { return } - if let storage = storage as? MemoryStorage, - let section = storage.section(atIndex: insertionIndexPath.section), - section.items.count >= insertionIndexPath.item - { - section.items.insert(item, at: insertionIndexPath.row) - } - insertionIndexPathClosure?(insertionIndexPath) - } - } - } - - @discardableResult - /// Convenience method to call `context.deletePlaceholder`. - open func deletePlaceholder() -> Bool { - return context.deletePlaceholder() - } -} -#endif diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift deleted file mode 100644 index 076a73d..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+DataSource.swift +++ /dev/null @@ -1,103 +0,0 @@ -// -// DTTableViewManager+DataSource.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 26.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension DTTableViewManager -{ - /// Registers `closure` to be executed, when `UITableView` requests `cellClass` in `UITableViewDataSource.tableView(_:cellForRowAt:)` method and cell is being configured. - /// - /// This closure will be performed *after* cell is created and `update(with:)` method is called. - open func configure(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDataSource?.appendReaction(for: T.self, signature: .configureCell, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableView` requests `headerClass` in `UITableViewDelegate.tableView(_:viewForHeaderInSection:)` method and header is being configured. - /// - /// This closure will be performed *after* header is created and `update(with:)` method is called. - open func configureHeader(_ headerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionHeader, supplementaryClass: T.self, signature: .configureHeader, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableView` requests `footerClass` in `UITableViewDelegate.tableView(_:viewForFooterInSection:)` method and footer is being configured. - /// - /// This closure will be performed *after* footer is created and `update(with:)` method is called. - open func configureFooter(_ footerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionFooter, supplementaryClass: T.self, signature: .configureFooter, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:canMoveRowAt:)` method is called for `cellClass`. - open func canMove(_ cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell { - tableDataSource?.appendReaction(for: T.self, signature: EventMethodSignature.canMoveRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:moveRowAt:to:)` method is called for `cellClass`. - /// - warning: This method requires items to be moved without animations, since animation has already happened when user moved those cells. If you use `MemoryStorage`, it's appropriate to call `memoryStorage.moveItemWithoutAnimation(from:to:)` method to achieve desired behavior. - /// - SeeAlso: 'tableView:moveRowAt:to:' method - open func move(_ cellClass: T.Type, _ closure: @escaping (_ destinationIndexPath: IndexPath, T, T.ModelType, _ sourceIndexPath: IndexPath) -> Void) where T: UITableViewCell { - tableDataSource?.append4ArgumentReaction(for: T.self, - signature: .moveRowAtIndexPathToIndexPath, - closure: closure) - } - - #if os(iOS) - /// Registers `closure` to be executed, when `UITableViewDataSource.sectionIndexTitles(for:_) ` method is called. - open func sectionIndexTitles(_ closure: @escaping () -> [String]?) { - tableDataSource?.appendNonCellReaction(.sectionIndexTitlesForTableView, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDataSource.tableView(_:sectionForSectionIndexTitle:at:)` method is called. - open func sectionForSectionIndexTitle(_ closure: @escaping (String, Int) -> Int) { - tableDataSource?.appendNonCellReaction(.sectionForSectionIndexTitleAtIndex, closure: closure) - } - #endif - -#if swift(>=4.2) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:commitEditingStyle:forRowAt:)` method is called for `cellClass`. - open func commitEditingStyle(for cellClass: T.Type, _ closure: @escaping (UITableViewCell.EditingStyle, T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell { - tableDataSource?.append4ArgumentReaction(for: T.self, - signature: .commitEditingStyleForRowAtIndexPath, - closure: closure) - } -#else - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:commitEditingStyle:forRowAt:)` method is called for `cellClass`. - open func commitEditingStyle(for cellClass: T.Type, _ closure: @escaping (UITableViewCellEditingStyle, T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell { - tableDataSource?.append4ArgumentReaction(for: T.self, - signature: .commitEditingStyleForRowAtIndexPath, - closure: closure) - } -#endif - - - /// Registers `closure` to be executed in `UITableViewDelegate.tableView(_:canEditCellForRowAt:)` method, when it's called for cell which model is of `itemType`. - open func canEditCell(withItem itemType: T.Type, _ closure: @escaping (T, IndexPath) -> Bool) { - tableDataSource?.appendReaction(for: T.self, signature: EventMethodSignature.canEditRowAtIndexPath, closure: closure) - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift deleted file mode 100644 index a03f364..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Delegate.swift +++ /dev/null @@ -1,345 +0,0 @@ -// -// DTTableViewManager+Delegate.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 26.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension DTTableViewManager { - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didSelectRowAt:)` method is called for `cellClass`. - open func didSelect(_ cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T:UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .didSelectRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willSelectRowAt:)` method is called for `cellClass`. - open func willSelect(_ cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> IndexPath?) where T:UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .willSelectRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willDeselectRowAt:)` method is called for `cellClass`. - open func willDeselect(_ cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> IndexPath?) where T:UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .willDeselectRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didDeselectRowAt:)` method is called for `cellClass`. - open func didDeselect(_ cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T:UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .didDeselectRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed to determine cell height in `UITableViewDelegate.tableView(_:heightForRowAt:)` method, when it's called for cell which model is of `itemType`. - open func heightForCell(withItem itemType: T.Type, _ closure: @escaping (T, IndexPath) -> CGFloat) { - tableDelegate?.appendReaction(for: T.self, signature: .heightForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed to determine estimated cell height in `UITableViewDelegate.tableView(_:estimatedHeightForRowAt:)` method, when it's called for cell which model is of `itemType`. - open func estimatedHeightForCell(withItem itemType: T.Type, _ closure: @escaping (T, IndexPath) -> CGFloat) { - tableDelegate?.appendReaction(for: T.self, signature: .estimatedHeightForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed to determine indentation level in `UITableViewDelegate.tableView(_:indentationLevelForRowAt:)` method, when it's called for cell which model is of `itemType`. - open func indentationLevelForCell(withItem itemType: T.Type, _ closure: @escaping (T, IndexPath) -> CGFloat) { - tableDelegate?.appendReaction(for: T.self, signature: .indentationLevelForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willDisplayCell:forRowAt:)` method is called for `cellClass`. - open func willDisplay(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .willDisplayCellForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:accessoryButtonTappedForRowAt:)` method is called for `cellClass`. - open func accessoryButtonTapped(in cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .accessoryButtonTappedForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed to determine header height in `UITableViewDelegate.tableView(_:heightForHeaderInSection:)` method, when it's called for header which model is of `itemType`. - open func heightForHeader(withItem type: T.Type, _ closure: @escaping (T, Int) -> CGFloat) { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionHeader, modelClass: T.self, signature: .heightForHeaderInSection, closure: closure) - } - - /// Registers `closure` to be executed to determine estimated header height in `UITableViewDelegate.tableView(_:estimatedHeightForHeaderInSection:)` method, when it's called for header which model is of `itemType`. - open func estimatedHeightForHeader(withItem type: T.Type, _ closure: @escaping (T, Int) -> CGFloat) { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionHeader, modelClass: T.self, signature: .estimatedHeightForHeaderInSection, closure: closure) - } - - /// Registers `closure` to be executed to determine footer height in `UITableViewDelegate.tableView(_:heightForFooterInSection:)` method, when it's called for footer which model is of `itemType`. - open func heightForFooter(withItem type: T.Type, _ closure: @escaping (T, Int) -> CGFloat) { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionFooter, modelClass: T.self, signature: .heightForFooterInSection, closure: closure) - } - - /// Registers `closure` to be executed to determine estimated footer height in `UITableViewDelegate.tableView(_:estimatedHeightForFooterInSection:)` method, when it's called for footer which model is of `itemType`. - open func estimatedHeightForFooter(withItem type: T.Type, _ closure: @escaping (T, Int) -> CGFloat) { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionFooter, modelClass: T.self, signature: .estimatedHeightForFooterInSection, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willDisplayHeaderView:forSection:)` method is called for `headerClass`. - open func willDisplayHeaderView(_ headerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionHeader, supplementaryClass: T.self, signature: .willDisplayHeaderForSection, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willDisplayFooterView:forSection:)` method is called for `footerClass`. - open func willDisplayFooterView(_ footerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionFooter, supplementaryClass: T.self, signature: .willDisplayFooterForSection, closure: closure) - } - -#if os(iOS) - @available(iOS, deprecated: 13.0) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:editActionsForRowAt:)` method is called for `cellClass`. - open func editActions(for cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> [UITableViewRowAction]?) where T: UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .editActionsForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:willBeginEditingRowAt:)` method is called for `cellClass`. - open func willBeginEditing(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .willBeginEditingRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didEndEditingRowAt:)` method is called for `cellClass`. - open func didEndEditing(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .didEndEditingRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:titleForDeleteConfirmationButtonForRowAt:)` method is called for `cellClass`. - open func titleForDeleteConfirmationButton(in cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> String?) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .titleForDeleteButtonForRowAtIndexPath, closure: closure) - } -#endif - -#if swift(>=4.2) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:editingStyleForRowAt:)` method is called for cell that contains item `ofType` at `indexPath`. - open func editingStyle(forItem ofType:T.Type, _ closure: @escaping (T, IndexPath) -> UITableViewCell.EditingStyle) - { - tableDelegate?.appendReaction(for: T.self, signature: .editingStyleForRowAtIndexPath, closure: closure) - } -#else - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:editingStyleForRowAt:)` method is called for cell that contains item `ofType` at `indexPath`. - open func editingStyle(forItem ofType:T.Type, _ closure: @escaping (T, IndexPath) -> UITableViewCellEditingStyle) - { - tableDelegate?.appendReaction(for: T.self, signature: .editingStyleForRowAtIndexPath, closure: closure) - } -#endif - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:shouldIndentWhileEditingRowAt:)` method is called for `cellClass`. - open func shouldIndentWhileEditing(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .shouldIndentWhileEditingRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didEndDisplayingCell:forRowAt:)` method is called for `cellClass`. - open func didEndDisplaying(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell { - tableDelegate?.appendReaction(for: T.self, signature: .didEndDisplayingCellForRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didEndDisplayingHeaderView:forSection:)` method is called for `headerClass`. - open func didEndDisplayingHeaderView(_ headerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionHeader, supplementaryClass: T.self, signature: .didEndDisplayingHeaderViewForSection, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didEndDisplayingFooterView:forSection:)` method is called for `footerClass`. - open func didEndDisplayingFooterView(_ footerClass: T.Type, _ closure: @escaping (T, T.ModelType, Int) -> Void) where T: UIView - { - tableDelegate?.appendReaction(forSupplementaryKind: DTTableViewElementSectionFooter, supplementaryClass: T.self, signature: .didEndDisplayingFooterViewForSection, closure: closure) - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:shouldShowMenuForRowAt:)` method is called for `cellClass`. - open func shouldShowMenu(for cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .shouldShowMenuForRowAtIndexPath, closure: closure) - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:canPerformAction:forRowAt:withSender:)` method is called for `cellClass`. - open func canPerformAction(for cellClass: T.Type, _ closure: @escaping (Selector, Any?, T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell { - tableDelegate?.append5ArgumentReaction(for: T.self, - signature: .canPerformActionForRowAtIndexPath, - closure: closure) - } - - @available(iOS, deprecated: 13.0) - @available(tvOS, deprecated: 13.0) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:performAction:forRowAt:withSender:)` method is called for `cellClass`. - open func performAction(for cellClass: T.Type, _ closure: @escaping (Selector, Any?, T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell { - tableDelegate?.append5ArgumentReaction(for: T.self, - signature: .performActionForRowAtIndexPath, - closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:shouldHighlightRowAt:)` method is called for `cellClass`. - open func shouldHighlight(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .shouldHighlightRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didHighlightRowAt:)` method is called for `cellClass`. - open func didHighlight(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .didHighlightRowAtIndexPath, closure: closure) - } - - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:didUnhighlightRowAt:)` method is called for `cellClass`. - open func didUnhighlight(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .didUnhighlightRowAtIndexPath, closure: closure) - } - - @available(iOS 9.0, *) - /// Registers `closure` to be executed, when `UITableViewDelegate.tableView(_:canFocusRowAt:)` method is called for `cellClass`. - open func canFocus(_ cellClass:T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, signature: .canFocusRowAtIndexPath, closure: closure) - } - - @available(iOS 9.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:shouldUpdateFocusInContext:)` method is called. - open func shouldUpdateFocus(_ closure: @escaping (UITableViewFocusUpdateContext) -> Bool) - { - tableDelegate?.appendNonCellReaction(.shouldUpdateFocusInContext, closure: closure) - } - - @available(iOS 9.0, *) - /// Registers `closure` tp be executed when `UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)` method is called. - open func didUpdateFocus(_ closure: @escaping (UITableViewFocusUpdateContext, UIFocusAnimationCoordinator) -> Void) - { - tableDelegate?.appendNonCellReaction(.didUpdateFocusInContextWithAnimationCoordinator, closure: closure) - } - - @available(iOS 9.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.indexPathForPreferredFocusedView(in:)` method is called - open func indexPathForPreferredFocusedView(_ closure: @escaping () -> IndexPath?) - { - tableDelegate?.appendNonCellReaction(.indexPathForPreferredFocusedViewInTableView, closure: closure) - } - - /// Registers `closure` to be executed when `UITableViewDelegate.targetIndexPathForMoveFromRowAt(_:toProposed:)` method is called for `cellClass` - open func targetIndexPathForMove(_ cellClass: T.Type, _ closure: @escaping (IndexPath, T, T.ModelType, IndexPath) -> IndexPath) where T:UITableViewCell { - tableDelegate?.append4ArgumentReaction(for: T.self, - signature: .targetIndexPathForMoveFromRowAtIndexPath, - closure: closure) - } - -#if os(iOS) - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:leadingSwipeActionsConfigurationForRowAt:)` method is called for `cellClass` - open func leadingSwipeActionsConfiguration(for cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> UISwipeActionsConfiguration?) where T: UITableViewCell { - tableDelegate?.appendReaction(for: T.self, - signature: .leadingSwipeActionsConfigurationForRowAtIndexPath, - closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:trailingSwipeActionsConfigurationForRowAt:)` method is called for `cellClass` - open func trailingSwipeActionsConfiguration(for cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> UISwipeActionsConfiguration?) where T: UITableViewCell { - tableDelegate?.appendReaction(for: T.self, - signature: .trailingSwipeActionsConfigurationForRowAtIndexPath, - closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:shouldSpringLoadRowAt:)` method is called for `cellClass`. - open func shouldSpringLoad(_ cellClass: T.Type, _ closure: @escaping (UISpringLoadedInteractionContext, T, T.ModelType, IndexPath) -> Bool) where T: UITableViewCell { - tableDelegate?.append4ArgumentReaction(for: T.self, - signature: .shouldSpringLoadRowAtIndexPathWithContext, - closure: closure) - } - - #if compiler(>=5.1) - @available(iOS 13, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:shouldBeginMultipleSelectionInteractionAt:)`method is called for `cellClass`. - /// - Parameter Type: cell class to react for event - /// - Parameter closure: closure to run. - open func shouldBeginMultipleSelectionInteraction(for cellClass: T.Type, - _ closure: @escaping (T, T.ModelType, IndexPath) -> Bool) - where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, - signature: .shouldBeginMultipleSelectionInteractionAtIndexPath, - closure: closure) - } - - @available(iOS 13, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:didBeginMultipleSelectionInteractionAt:)`method is called for `cellClass`. - /// - Parameter Type: cell class to react for event - /// - Parameter closure: closure to run. - open func didBeginMultipleSelectionInteraction(for cellClass: T.Type, - _ closure: @escaping (T, T.ModelType, IndexPath) -> Void) - where T: UITableViewCell - { - tableDelegate?.appendReaction(for: T.self, - signature: .didBeginMultipleSelectionInteractionAtIndexPath, - closure: closure) - } - - @available(iOS 13.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableViewDidEndMultipleSelectionInteraction(_:)` method is called - open func didEndMultipleSelectionInteraction(_ closure: @escaping () -> Void) - { - tableDelegate?.appendNonCellReaction(.didEndMultipleSelectionInteraction, closure: closure) - } - - @available(iOS 13.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.contextMenuConfigurationForRowAt(_:point:)` method is called - open func contextMenuConfiguration(for cellClass: T.Type, - _ closure: @escaping (CGPoint, T, T.ModelType, IndexPath) -> UIContextMenuConfiguration?) - where T: UITableViewCell - { - tableDelegate?.append4ArgumentReaction(for: T.self, - signature: .contextMenuConfigurationForRowAtIndexPath, - closure: closure) - } - - @available(iOS 13.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:previewForHighlightingContextMenuWithConfiguration:)` method is called - open func previewForHighlightingContextMenu(_ closure: @escaping (UIContextMenuConfiguration) -> UITargetedPreview?) - { - tableDelegate?.appendNonCellReaction(.previewForHighlightingContextMenu, closure: closure) - } - - @available(iOS 13.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:previewForDismissingContextMenuWithConfiguration:)` method is called - open func previewForDismissingContextMenu(_ closure: @escaping (UIContextMenuConfiguration) -> UITargetedPreview?) - { - tableDelegate?.appendNonCellReaction(.previewForDismissingContextMenu, closure: closure) - } - #if compiler(<5.1.2) - @available(iOS 13.0, *) - /// Registers `closure` to be executed when `UITableViewDelegate.tableView(_:willCommitMenuWithAnimator:)` method is called - open func willCommitMenuWithAnimator(_ closure: @escaping (UIContextMenuInteractionCommitAnimating) -> Void) - { - tableDelegate?.appendNonCellReaction(.willCommitMenuWithAnimator, closure: closure) - } - #endif - #endif -#endif -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift deleted file mode 100644 index 5b19dd1..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drag.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// DTTableViewManager+Drag.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 26.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension DTTableViewManager -{ - #if os(iOS) - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:itemsForBeginning:at:)` method is called for `cellClass`. - open func itemsForBeginningDragSession(from cellClass: T.Type, _ closure: @escaping (UIDragSession, T, T.ModelType, IndexPath) -> [UIDragItem]) where T:UITableViewCell - { - tableDragDelegate?.append4ArgumentReaction(for: T.self, - signature: .itemsForBeginningDragSession, - closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:itemsForAddingTo:at:point:)` method is called for `cellClass` - open func itemsForAddingToDragSession(from cellClass: T.Type, _ closure: @escaping (UIDragSession, CGPoint, T, T.ModelType, IndexPath) -> [UIDragItem]) where T: UITableViewCell - { - tableDragDelegate?.append5ArgumentReaction(for: T.self, - signature: .itemsForAddingToDragSession, - closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:dragPreviewParametersForRowAt:)` method is called for `cellClass` - open func dragPreviewParameters(for cellClass: T.Type, _ closure: @escaping (T, T.ModelType, IndexPath) -> UIDragPreviewParameters?) where T:UITableViewCell { - tableDragDelegate?.appendReaction(for: T.self, - signature: .dragPreviewParametersForRowAtIndexPath, - closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:dragSessionWillBegin:)` method is called. - open func dragSessionWillBegin(_ closure: @escaping (UIDragSession) -> Void) { - tableDragDelegate?.appendNonCellReaction(.dragSessionWillBegin, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:dragSessionDidEnd:)` method is called. - open func dragSessionDidEnd(_ closure: @escaping (UIDragSession) -> Void) { - tableDragDelegate?.appendNonCellReaction(.dragSessionDidEnd, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:dragSessionAllowsMoveOperation)` method is called. - open func dragSessionAllowsMoveOperation(_ closure: @escaping (UIDragSession) -> Bool) { - tableDragDelegate?.appendNonCellReaction(.dragSessionAllowsMoveOperation, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDragDelegate.tableView(_:dragSessionIsRestrictedToDraggingApplication:)` method is called. - open func dragSessionIsRestrictedToDraggingApplication(_ closure: @escaping (UIDragSession) -> Bool) { - tableDragDelegate?.appendNonCellReaction(.dragSessionIsRestrictedToDraggingApplication, closure: closure) - } - #endif -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift deleted file mode 100644 index 5da5c29..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Drop.swift +++ /dev/null @@ -1,86 +0,0 @@ -// -// DTTableViewManager+Drop.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 26.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension DTTableViewManager -{ - #if os(iOS) - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:performDropWith:)` method is called. - open func performDropWithCoordinator(_ closure: @escaping (UITableViewDropCoordinator) -> Void) { - tableDropDelegate?.appendNonCellReaction(.performDropWithCoordinator, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:canHandle:)` method is called. - open func canHandleDropSession(_ closure: @escaping (UIDropSession) -> Bool) { - tableDropDelegate?.appendNonCellReaction(.canHandleDropSession, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:dropSessionDidEnter:)` method is called. - open func dropSessionDidEnter(_ closure: @escaping (UIDropSession) -> Void) { - tableDropDelegate?.appendNonCellReaction(.dropSessionDidEnter, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:dropSessionDidUpdate:withDestination:)` method is called. - open func dropSessionDidUpdate(_ closure: @escaping (UIDropSession, IndexPath?) -> UITableViewDropProposal) { - tableDropDelegate?.appendNonCellReaction(.dropSessionDidUpdateWithDestinationIndexPath, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:dropSessionDidExit:)` method is called. - open func dropSessionDidExit(_ closure: @escaping (UIDropSession) -> Void) { - tableDropDelegate?.appendNonCellReaction(.dropSessionDidExit, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:dropSessionDidEnd:)` method is called. - open func dropSessionDidEnd(_ closure: @escaping (UIDropSession) -> Void) { - tableDropDelegate?.appendNonCellReaction(.dropSessionDidEnd, closure: closure) - } - - @available(iOS 11, *) - /// Registers `closure` to be executed when `UITableViewDropDelegate.tableView(_:dropPreviewParametersForRowAt:)` method is called. - open func dropPreviewParameters(_ closure: @escaping (IndexPath) -> UIDragPreviewParameters?) { - tableDropDelegate?.appendNonCellReaction(.dropPreviewParametersForRowAtIndexPath, closure: closure) - } - - @available(iOS 11, *) - /// Convenience method for dropping `item` into `placeholder`. - /// Returns `DTTableViewDropPlaceholderContext`, which is a replacement for `UITableViewDropPlaceholderContext`, that automatically handles drop if you are using `MemoryStorage`. It also automatically dispatches insertion to `DispatchQueue.main`. - open func drop(_ item: UIDragItem, to placeholder: UITableViewDropPlaceholder, - with coordinator: UITableViewDropCoordinator) -> DTTableViewDropPlaceholderContext { - let context = coordinator.drop(item, to: placeholder) - return DTTableViewDropPlaceholderContext(context: context, storage: storage) - } - - #endif -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift deleted file mode 100644 index 9d41150..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift +++ /dev/null @@ -1,125 +0,0 @@ -// -// DTTableViewManager+Registration.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 26.08.17. -// Copyright © 2017 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import DTModelStorage - -extension DTTableViewManager -{ - /// Registers mapping from model class to `cellClass`. - /// - /// Method will automatically check for nib with the same name as `cellClass`. If it exists - nib will be registered instead of class. - open func register(_ cellClass:T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T: UITableViewCell - { - self.viewFactory.registerCellClass(cellClass, mappingBlock: mapping) - } - - /// Registers nib with `nibName` mapping from model class to `cellClass`. - open func registerNibNamed(_ nibName: String, for cellClass: T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T: UITableViewCell - { - self.viewFactory.registerNibNamed(nibName, forCellClass: cellClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to header view of `headerClass` type. - /// - /// Method will automatically check for nib with the same name as `headerClass`. If it exists - nib will be registered instead of class. - /// This method also sets TableViewConfiguration.sectionHeaderStyle property to .view. - /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. - /// - SeeAlso: `UIView+XibLoading`. - open func registerHeader(_ headerClass : T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T: UIView - { - configuration.sectionHeaderStyle = .view - self.viewFactory.registerHeaderClass(headerClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to header view of `headerClass` type. - /// - /// This method is intended to be used for headers created from code - without UI made in XIB. - /// This method also sets TableViewConfiguration.sectionHeaderStyle property to .view. - open func registerNiblessHeader(_ headerClass : T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T: UITableViewHeaderFooterView - { - configuration.sectionHeaderStyle = .view - self.viewFactory.registerNiblessHeaderClass(headerClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to footer view of `footerClass` type. - /// - /// This method is intended to be used for footers created from code - without UI made in XIB. - /// This method also sets TableViewConfiguration.sectionFooterStyle property to .view. - open func registerNiblessFooter(_ footerClass : T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T: UITableViewHeaderFooterView - { - configuration.sectionFooterStyle = .view - self.viewFactory.registerNiblessFooterClass(footerClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to footerView view of `footerClass` type. - /// - /// Method will automatically check for nib with the same name as `footerClass`. If it exists - nib will be registered instead of class. - /// This method also sets TableViewConfiguration.sectionFooterStyle property to .view. - /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. - /// - SeeAlso: `UIView+XibLoading`. - open func registerFooter(_ footerClass: T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T:UIView - { - configuration.sectionFooterStyle = .view - viewFactory.registerFooterClass(footerClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to headerView view of `headerClass` type with `nibName`. - /// - /// This method also sets TableViewConfiguration.sectionHeaderStyle property to .view. - /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. - /// - SeeAlso: `UIView+XibLoading`. - open func registerNibNamed(_ nibName: String, forHeader headerClass: T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T:UIView - { - configuration.sectionHeaderStyle = .view - viewFactory.registerNibNamed(nibName, forHeaderClass: headerClass, mappingBlock: mapping) - } - - /// Registers mapping from model class to headerView view of `footerClass` type with `nibName`. - /// - /// This method also sets TableViewConfiguration.sectionFooterStyle property to .view. - /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. - /// - SeeAlso: `UIView+XibLoading`. - open func registerNibNamed(_ nibName: String, forFooter footerClass: T.Type, mapping: ((ViewModelMapping) -> Void)? = nil) where T:UIView - { - configuration.sectionFooterStyle = .view - viewFactory.registerNibNamed(nibName, forFooterClass: footerClass, mappingBlock: mapping) - } - - /// Unregisters `cellClass` from `DTTableViewManager` and `UITableView`. - open func unregister(_ cellClass: T.Type) where T:UITableViewCell { - viewFactory.unregisterCellClass(T.self) - } - - /// Unregisters `headerClass` from `DTTableViewManager` and `UITableView`. - open func unregisterHeader(_ headerClass: T.Type) where T: UIView { - viewFactory.unregisterHeaderClass(T.self) - } - - /// Unregisters `footerClass` from `DTTableViewManager` and `UITableView`. - open func unregisterFooter(_ footerClass: T.Type) where T: UIView { - viewFactory.unregisterFooterClass(T.self) - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift deleted file mode 100644 index 45d6524..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager.swift +++ /dev/null @@ -1,445 +0,0 @@ -// -// TableViewController.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 12.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -/// Adopting this protocol will automatically inject `manager` property to your object, that lazily instantiates `DTTableViewManager` object. -/// Target is not required to be `UITableViewController`, and can be a regular UIViewController with UITableView, or even different object like UICollectionViewCell. -public protocol DTTableViewManageable : class -{ - /// Table view, that will be managed by DTTableViewManager. This property or `optionalTableView` property must be implemented in order for `DTTableViewManager` to work. - var tableView : UITableView! { get } - - // Table view, that will be managed by DTTableViewManager. This property or `tableView` property must be implemented in order for `DTTableViewManager` to work. - var optionalTableView: UITableView? { get } -} - -/// Extension for `DTTableViewManageable` that provides default implementations for `tableView` and `optionalTableView` properties. One of those properties must be implemented in `DTTableViewManageable` implementation. -public extension DTTableViewManageable { - var tableView: UITableView! { return nil } - - var optionalTableView: UITableView? { return nil } -} - -/// This key is used to store `DTTableViewManager` instance on `DTTableViewManageable` class using object association. -private var DTTableViewManagerAssociatedKey = "DTTableViewManager Associated Key" - -/// Default implementation for `DTTableViewManageable` protocol, that will inject `manager` property to any object, that declares itself `DTTableViewManageable`. -extension DTTableViewManageable -{ - /// Lazily instantiated `DTTableViewManager` instance. When your table view is loaded, call startManagingWithDelegate: method and `DTTableViewManager` will take over UITableView datasource and delegate. Any method, that is not implemented by `DTTableViewManager`, will be forwarded to delegate. - /// If this property is accessed when UITableView is loaded, and DTTableViewManager is not configured yet, startManaging(withDelegate:_) method will automatically be called once to initialize DTTableViewManager. - /// - SeeAlso: `startManagingWithDelegate:` - public var manager : DTTableViewManager { - get { - if let manager = objc_getAssociatedObject(self, &DTTableViewManagerAssociatedKey) as? DTTableViewManager { - if !manager.isConfigured && (tableView != nil || optionalTableView != nil) { - manager.startManaging(withDelegate: self) - } - return manager - } - let manager = DTTableViewManager() - if tableView != nil || optionalTableView != nil { - manager.startManaging(withDelegate: self) - } - objc_setAssociatedObject(self, &DTTableViewManagerAssociatedKey, manager, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return manager - } - set { - objc_setAssociatedObject(self, &DTTableViewManagerAssociatedKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } -} - -/// `DTTableViewManager` manages many of `UITableView` datasource and delegate methods and provides API for managing your data models in the table. Any method, that is not implemented by `DTTableViewManager`, will be forwarded to delegate. -/// - SeeAlso: `startManagingWithDelegate:` -open class DTTableViewManager { - - /// Stores all configuration options for `DTTableViewManager`. - /// - SeeAlso: `TableViewConfiguration`. - open var configuration = TableViewConfiguration() - - /// Anomaly handler, that handles reported by `DTTableViewManager` anomalies. - open var anomalyHandler : DTTableViewManagerAnomalyHandler = .init() - - /// Bool property, that will be true, after `startManagingWithDelegate` method is called on `DTTableViewManager`. - open var isManagingTableView : Bool { - return tableView != nil - } - - /// Factory for creating cells and views for UITableView - final lazy var viewFactory: TableViewFactory = { - precondition(isManagingTableView, "Please call manager.startManagingWithDelegate(self) before calling any other DTTableViewManager methods") - //swiftlint:disable:next force_unwrapping - let factory = TableViewFactory(tableView: self.tableView!) - factory.anomalyHandler = anomalyHandler - return factory - }() - - /// Internal weak link to `UITableView` - final var tableView : UITableView? - { - if let delegate = delegate as? DTTableViewManageable { return delegate.optionalTableView ?? delegate.tableView } - return nil - } - - /// `DTTableViewManageable` delegate. - final fileprivate weak var delegate : AnyObject? - - /// Implicitly unwrap storage property to `MemoryStorage`. - /// - Warning: if storage is not MemoryStorage, will throw an exception. - open var memoryStorage : MemoryStorage! - { - guard let storage = storage as? MemoryStorage else { - assertionFailure("DTTableViewManager memoryStorage method should be called only if you are using MemoryStorage") - return nil - } - return storage - } - - /// Storage, that holds your UITableView models. By default, it's `MemoryStorage` instance. - /// - Note: When setting custom storage for this property, it will be automatically configured for using with UITableView and it's delegate will be set to `DTTableViewManager` instance. - /// - Note: Previous storage `delegate` property will be nilled out to avoid collisions. - /// - SeeAlso: `MemoryStorage`, `CoreDataStorage`, `RealmStorage`. - open var storage : Storage { - willSet { - (storage as? BaseUpdateDeliveringStorage)?.delegate = nil - } - didSet { - if let headerFooterCompatibleStorage = storage as? SupplementaryStorage { - headerFooterCompatibleStorage.configureForTableViewUsage() - } - (storage as? BaseUpdateDeliveringStorage)?.delegate = tableViewUpdater - } - } - - /// Current storage, conditionally casted to `SupplementaryStorage` protocol. - public var supplementaryStorage: SupplementaryStorage? { - return storage as? SupplementaryStorage - } - - /// Object, that is responsible for updating `UITableView`, when received update from `Storage` - open var tableViewUpdater : TableViewUpdater? { - didSet { - (storage as? BaseUpdateDeliveringStorage)?.delegate = tableViewUpdater - tableViewUpdater?.didUpdateContent?(nil) - } - } - - /// Object, that is responsible for implementing `UITableViewDelegate` protocol. - open var tableDelegate: DTTableViewDelegate? { - didSet { - tableView?.delegate = tableDelegate - } - } - - /// Object, that is responsible for implementing `UITableViewDataSource` protocol. - open var tableDataSource: DTTableViewDataSource? { - didSet { - tableView?.dataSource = tableDataSource - } - } - - #if os(iOS) - // Yeah, @availability macros does not work on stored properties ¯\_(ツ)_/¯ - private var _tableDragDelegatePrivate : AnyObject? - @available(iOS 11, *) - /// Object, that is responsible for implementing `UITableViewDragDelegate` protocol - open var tableDragDelegate : DTTableViewDragDelegate? { - get { - return _tableDragDelegatePrivate as? DTTableViewDragDelegate - } - set { - _tableDragDelegatePrivate = newValue - tableView?.dragDelegate = newValue - } - } - - // Yeah, @availability macros does not work on stored properties ¯\_(ツ)_/¯ - private var _tableDropDelegatePrivate : AnyObject? - @available(iOS 11, *) - /// Object, that is responsible for implementing `UITableViewDropDelegate` protocol - open var tableDropDelegate : DTTableViewDropDelegate? { - get { - return _tableDropDelegatePrivate as? DTTableViewDropDelegate - } - set { - _tableDropDelegatePrivate = newValue - tableView?.dropDelegate = newValue - } - } - #endif - - /// Storage construction block, used by `DTTableViewManager` when it's created. Returns `MemoryStorage` by default. - public static var defaultStorage: () -> Storage = { MemoryStorage() } - - /// Creates `DTTableViewManager`. Usually you don't need to call this method directly, as `manager` property on `DTTableViewManageable` instance is filled automatically. `DTTableViewManager.defaultStorage` closure is used to determine which `Storage` would be used by default. - /// - /// - Parameter storage: storage class to be used - public init(storage: Storage = DTTableViewManager.defaultStorage()) { - (storage as? SupplementaryStorage)?.configureForTableViewUsage() - self.storage = storage - } - -#if compiler(>=5.1) - @available(iOS 13.0, tvOS 13.0, *) - /// Configures `UITableViewDiffableDataSource` to be used with `DTTableViewManager`. - /// Because `UITableViewDiffableDataSource` handles UITableView updates, `tableViewUpdater` property on `DTTableViewManager` will be set to nil. - /// - Parameter modelProvider: closure that provides `DTTableViewManager` models. - /// This closure mirrors `cellProvider` property on `UITableViewDiffableDataSource`, but strips away tableView, and asks for data model instead of a cell. Cell mapping is then executed in the same way as without diffable data sources. - open func configureDiffableDataSource(modelProvider: @escaping (IndexPath, ItemIdentifier) -> Any) - -> UITableViewDiffableDataSource - { - guard let tableView = tableView else { - fatalError("Attempt to configure diffable datasource before tableView have been initialized") - } - // UITableViewDiffableDataSource will update UITableView instead of `TableViewUpdater` object. - tableViewUpdater = nil - - // Cell is provided by `DTTableViewDataSource` without actually calling closure that is passed to `UITableViewDiffableDataSource`. - let dataSource = UITableViewDiffableDataSource(tableView: tableView) { _, _, _ in nil } - storage = ProxyDiffableDataSourceStorage(tableView: tableView, - dataSource: dataSource, - modelProvider: modelProvider) - tableView.dataSource = tableDataSource - - return dataSource - } - - @available(iOS 13.0, tvOS 13.0, *) - /// Configures `UITableViewDiffableDataSourceReference` to be used with `DTTableViewManager`. - /// Because `UITableViewDiffableDataSourceReference` handles UITableView updates, `tableViewUpdater` property on `DTTableViewManager` will be set to nil. - /// - Parameter modelProvider: closure that provides `DTTableViewManager` models. - /// This closure mirrors `cellProvider` property on `UITableViewDiffableDataSourceReference`, but strips away tableView, and asks for data model instead of a cell. Cell mapping is then executed in the same way as without diffable data sources. - open func configureDiffableDataSource(modelProvider: @escaping (IndexPath, Any) -> Any) -> UITableViewDiffableDataSourceReference - { - guard let tableView = tableView else { - fatalError("Attempt to configure diffable datasource before tableView have been initialized") - } - // UITableViewDiffableDataSourceReference will update UITableView instead of `TableViewUpdater` object. - tableViewUpdater = nil - - // Cell is provided by `DTTableViewDataSource` without actually calling closure that is passed to `UITableViewDiffableDataSourceReference`. - let dataSource = UITableViewDiffableDataSourceReference(tableView: tableView) { _, _, _ in nil } - storage = ProxyDiffableDataSourceStorage(tableView: tableView, - dataSource: dataSource, - modelProvider: modelProvider) - tableView.dataSource = tableDataSource - - return dataSource - } -#endif - - /// Starts managing `UITableView`. - /// - /// Call this method before calling any of `DTTableViewManager` methods. - /// - Precondition: UITableView instance on `delegate` should not be nil. - /// - Note: If delegate is `DTViewModelMappingCustomizable`, it will also be used to determine which view-model mapping should be used by table view factory. - open func startManaging(withDelegate delegate : DTTableViewManageable) - { - guard !isConfigured else { return } - guard let tableView = delegate.optionalTableView ?? delegate.tableView else { - preconditionFailure("Call startManagingWithDelegate: method only when UITableView has been created") - } - self.delegate = delegate - startManaging(with: tableView) - } - - fileprivate var isConfigured = false - - private func startManaging(with tableView: UITableView) { - guard !isConfigured else { return } - defer { isConfigured = true } - tableViewUpdater = TableViewUpdater(tableView: tableView) - tableDelegate = DTTableViewDelegate(delegate: delegate, tableViewManager: self) - tableDataSource = DTTableViewDataSource(delegate: delegate, tableViewManager: self) - #if os(iOS) - if #available(iOS 11.0, *) { - tableDragDelegate = DTTableViewDragDelegate(delegate: delegate, tableViewManager: self) - tableDropDelegate = DTTableViewDropDelegate(delegate: delegate, tableViewManager: self) - } - #endif - } - - /// Returns closure, that updates cell at provided indexPath. - /// - /// This is used by `coreDataUpdater` method and can be used to silently update a cell without reload row animation. - open func updateCellClosure() -> (IndexPath, Any) -> Void { - return { [weak self] indexPath, model in - self?.viewFactory.updateCellAt(indexPath, with: model) - } - } - - - /// Updates visible cells, using `tableView.indexPathsForVisibleRows`, and update block. This may be more efficient than running `reloadData`, if number of your data models does not change, and the change you want to reflect is completely within models state. - /// - /// - Parameter closure: closure to run for each cell after update has been completed. - open func updateVisibleCells(_ closure: ((UITableViewCell) -> Void)? = nil) { - (tableView?.indexPathsForVisibleRows ?? []).forEach { indexPath in - guard let model = storage.item(at: indexPath), - let visibleCell = tableView?.cellForRow(at: indexPath) - else { return } - updateCellClosure()(indexPath, model) - closure?(visibleCell) - } - } - - /// Returns `TableViewUpdater`, configured to work with `CoreDataStorage` and `NSFetchedResultsController` updates. - /// - /// - Precondition: UITableView instance on `delegate` should not be nil. - open func coreDataUpdater() -> TableViewUpdater { - guard let tableView = tableView else { - preconditionFailure("Call coreDataUpdater() method only when UITableView is created and passed to `DTTableViewManager` via startManaging(with:) method.") - } - return TableViewUpdater(tableView: tableView, - reloadRow: updateCellClosure(), - animateMoveAsDeleteAndInsert: true) - } - - - /// Immediately runs closure to provide access to both T and T.ModelType for `klass`. - /// - /// - Discussion: This is particularly useful for registering events, because near 1/3 of events don't have cell or view before they are getting run, which prevents view type from being known, and required developer to remember, which model is mapped to which cell. - /// By using this container closure you will be able to provide compile-time safety for all events. - /// - Parameters: - /// - klass: Class of reusable view to be used in configuration container - /// - closure: closure to run with view types. - open func configureEvents(for klass: T.Type, _ closure: (T.Type, T.ModelType.Type) -> Void) { - closure(T.self, T.ModelType.self) - } - - func verifyItemEvent(for itemType: T.Type, eventMethod: String) { - switch itemType { - case is UICollectionReusableView.Type: - anomalyHandler.reportAnomaly(.modelEventCalledWithCellClass(modelType: String(describing: T.self), methodName: eventMethod, subclassOf: "UICollectionReusableView")) - case is UITableViewCell.Type: - anomalyHandler.reportAnomaly(.modelEventCalledWithCellClass(modelType: String(describing: T.self), methodName: eventMethod, subclassOf: "UITableViewCell")) - case is UITableViewHeaderFooterView.Type: anomalyHandler.reportAnomaly(.modelEventCalledWithCellClass(modelType: String(describing: T.self), methodName: eventMethod, subclassOf: "UITableViewHeaderFooterView")) - default: () - } - } - - func verifyViewEvent(for viewType: T.Type, methodName: String) { - DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in - if self?.viewFactory.mappings.filter({ $0.viewClass.isSubclass(of: viewType) }).count == 0 { - self?.anomalyHandler.reportAnomaly(DTTableViewManagerAnomaly.unusedEventDetected(viewType: String(describing: T.self), methodName: methodName)) - } - } - } -} - -// MARK: - Method signatures -/// All supported Objective-C method signatures. -/// -/// Some of signatures are made up, so that we would be able to link them with event, however they don't stop "responds(to:)" method from returning true. -internal enum EventMethodSignature: String { - /// UITableViewDataSource - case configureCell = "tableViewConfigureCell_imaginarySelector" - case configureHeader = "tableViewConfigureHeader_imaginarySelector" - case configureFooter = "tableViewConfigureFooter_imaginarySelector" - case commitEditingStyleForRowAtIndexPath = "tableView:commitEditingStyle:forRowAtIndexPath:" - case canEditRowAtIndexPath = "tableView:canEditRowAtIndexPath:" - case canMoveRowAtIndexPath = "tableView:canMoveRowAtIndexPath:" - case sectionIndexTitlesForTableView = "sectionIndexTitlesForTableView:" - case sectionForSectionIndexTitleAtIndex = "tableView:sectionForSectionIndexTitle:atIndex:" - case moveRowAtIndexPathToIndexPath = "tableView:moveRowAtIndexPath:toIndexPath:" - - /// UITableViewDelegate - case heightForRowAtIndexPath = "tableView:heightForRowAtIndexPath:" - case estimatedHeightForRowAtIndexPath = "tableView:estimatedHeightForRowAtIndexPath:" - case indentationLevelForRowAtIndexPath = "tableView:indentationLevelForRowAtIndexPath:" - case willDisplayCellForRowAtIndexPath = "tableView:willDisplayCell:forRowAtIndexPath:" - - case editActionsForRowAtIndexPath = "tableView:editActionsForRowAtIndexPath:" - case accessoryButtonTappedForRowAtIndexPath = "tableView:accessoryButtonTappedForRowWithIndexPath:" - - case willSelectRowAtIndexPath = "tableView:willSelectRowAtIndexPath:" - case didSelectRowAtIndexPath = "tableView:didSelectRowAtIndexPath:" - case willDeselectRowAtIndexPath = "tableView:willDeselectRowAtIndexPath:" - case didDeselectRowAtIndexPath = "tableView:didDeselectRowAtIndexPath:" - - case heightForHeaderInSection = "tableView:heightForHeaderInSection:_imaginarySelector" - case estimatedHeightForHeaderInSection = "tableView:estimatedHeightForHeaderInSection:" - case heightForFooterInSection = "tableView:heightForFooterInSection:_imaginarySelector" - case estimatedHeightForFooterInSection = "tableView:estimatedHeightForFooterInSection:" - case willDisplayHeaderForSection = "tableView:willDisplayHeaderView:forSection:" - case willDisplayFooterForSection = "tableView:willDisplayFooterView:forSection:" - - case willBeginEditingRowAtIndexPath = "tableView:willBeginEditingRowAtIndexPath:" - case didEndEditingRowAtIndexPath = "tableView:didEndEditingRowAtIndexPath:" - case editingStyleForRowAtIndexPath = "tableView:editingStyleForRowAtIndexPath:" - case titleForDeleteButtonForRowAtIndexPath = "tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:" - case shouldIndentWhileEditingRowAtIndexPath = "tableView:shouldIndentWhileEditingRowAtIndexPath:" - - case didEndDisplayingCellForRowAtIndexPath = "tableView:didEndDisplayingCell:forRowAtIndexPath:" - case didEndDisplayingHeaderViewForSection = "tableView:didEndDisplayingHeaderView:forSection:" - case didEndDisplayingFooterViewForSection = "tableView:didEndDisplayingFooterView:forSection:" - - case shouldShowMenuForRowAtIndexPath = "tableView:shouldShowMenuForRowAtIndexPath:" - case canPerformActionForRowAtIndexPath = "tableView:canPerformAction:forRowAtIndexPath:withSender:" - case performActionForRowAtIndexPath = "tableView:performAction:forRowAtIndexPath:withSender:" - - case shouldHighlightRowAtIndexPath = "tableView:shouldHighlightRowAtIndexPath:" - case didHighlightRowAtIndexPath = "tableView:didHighlightRowAtIndexPath:" - case didUnhighlightRowAtIndexPath = "tableView:didUnhighlightRowAtIndexPath:" - - case canFocusRowAtIndexPath = "tableView:canFocusRowAtIndexPath:" - - case leadingSwipeActionsConfigurationForRowAtIndexPath = "tableView:leadingSwipeActionsConfigurationForRowAtIndexPath:" - case trailingSwipeActionsConfigurationForRowAtIndexPath = "tableView:trailingSwipeActionsConfigurationForRowAtIndexPath:" - case targetIndexPathForMoveFromRowAtIndexPath = "tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:" - case shouldUpdateFocusInContext = "tableView:shouldUpdateFocusInContext:" - case didUpdateFocusInContextWithAnimationCoordinator = "tableView:didUpdateFocusInContext:withAnimationCoordinator:" - case indexPathForPreferredFocusedViewInTableView = "indexPathForPreferredFocusedViewInTableView:" - case shouldSpringLoadRowAtIndexPathWithContext = "tableView:shouldSpringLoadRowAtIndexPath:withContext:" - - case shouldBeginMultipleSelectionInteractionAtIndexPath = "tableView:shouldBeginMultipleSelectionInteractionAtIndexPath:" - case didBeginMultipleSelectionInteractionAtIndexPath = "tableView:didBeginMultipleSelectionInteractionAtIndexPath:" - case didEndMultipleSelectionInteraction = "tableViewDidEndMultipleSelectionInteraction:" - case contextMenuConfigurationForRowAtIndexPath = "tableView:contextMenuConfigurationForRowAtIndexPath:point:" - case previewForHighlightingContextMenu = "tableView:previewForHighlightingContextMenuWithConfiguration:" - case previewForDismissingContextMenu = "tableView:previewForDismissingContextMenuWithConfiguration:" - case willCommitMenuWithAnimator = "tableView:willCommitMenuWithAnimator:" - - /// UITableViewDragDelegate - case itemsForBeginningDragSession = "tableView:itemsForBeginningDragSession:atIndexPath:" - case itemsForAddingToDragSession = "tableView:itemsForAddingToDragSession:atIndexPath:point:" - case dragPreviewParametersForRowAtIndexPath = "tableView:dragPreviewParametersForRowAtIndexPath:" - case dragSessionWillBegin = "tableView:dragSessionWillBegin:" - case dragSessionDidEnd = "tableView:dragSessionDidEnd:" - case dragSessionAllowsMoveOperation = "tableView:dragSessionAllowsMoveOperation:" - case dragSessionIsRestrictedToDraggingApplication = "tableView:dragSessionIsRestrictedToDraggingApplication:" - - /// UITableViewDropDelegate - case performDropWithCoordinator = "tableView:performDropWithCoordinator:" - case canHandleDropSession = "tableView:canHandleDropSession:" - case dropSessionDidEnter = "tableView:dropSessionDidEnter:" - case dropSessionDidUpdateWithDestinationIndexPath = "tableView:dropSessionDidUpdate:withDestinationIndexPath:" - case dropSessionDidExit = "tableView:dropSessionDidExit:" - case dropSessionDidEnd = "tableView:dropSessionDidEnd:" - case dropPreviewParametersForRowAtIndexPath = "tableView:dropPreviewParametersForRowAtIndexPath:" -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift deleted file mode 100644 index 3d99810..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManagerAnomalyHandler.swift +++ /dev/null @@ -1,118 +0,0 @@ -// -// DTTableViewManagerAnomalyHandler.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 02.05.2018. -// Copyright © 2018 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import DTModelStorage - -/// `DTTableViewManagerAnomaly` represents various errors and unwanted behaviors that can happen when using `DTTableViewManager` class. -/// - SeeAlso: `MemoryStorageAnomaly`, `DTCollectionViewManagerAnomaly` -public enum DTTableViewManagerAnomaly: Equatable, CustomStringConvertible, CustomDebugStringConvertible { - - case nilCellModel(IndexPath) - case nilHeaderModel(Int) - case nilFooterModel(Int) - case noCellMappingFound(modelDescription: String, indexPath: IndexPath) - case noHeaderFooterMappingFound(modelDescription: String, indexPath: IndexPath) - case differentCellReuseIdentifier(mappingReuseIdentifier: String, cellReuseIdentifier: String) - case differentCellClass(xibName: String, cellClass: String, expectedCellClass: String) - case differentHeaderFooterClass(xibName: String, viewClass: String, expectedViewClass: String) - case emptyXibFile(xibName: String, expectedViewClass: String) - case modelEventCalledWithCellClass(modelType: String, methodName: String, subclassOf: String) - case unusedEventDetected(viewType: String, methodName: String) - - /// Debug information for happened anomaly - public var debugDescription: String { - switch self { - case .nilCellModel(let indexPath): return "❗️[DTTableViewManager] UITableView requested a cell at \(indexPath), however the model at that indexPath was nil." - case .nilHeaderModel(let section): return "⚠️[DTTableViewManager] UITableView requested a header view at section \(section), however the model was nil." - case .nilFooterModel(let section): return "⚠️[DTTableViewManager] UITableView requested a footer view at section \(section), however the model was nil." - case .noCellMappingFound(modelDescription: let description, indexPath: let indexPath): return "❗️[DTTableViewManager] UITableView requested a cell for model at \(indexPath), but view model mapping for it was not found, model description: \(description)" - case .noHeaderFooterMappingFound(modelDescription: let description, let indexPath): return "❗️[DTTableViewManager] UITableView requested a header/footer view for model ar \(indexPath), but view model mapping for it was not found, model description: \(description)" - case .differentCellReuseIdentifier(mappingReuseIdentifier: let mappingReuseIdentifier, - cellReuseIdentifier: let cellReuseIdentifier): - return "❗️[DTTableViewManager] Reuse identifier specified in InterfaceBuilder: \(cellReuseIdentifier) does not match reuseIdentifier used to register with UITableView: \(mappingReuseIdentifier). \n" + - "If you are using XIB, please remove reuseIdentifier from XIB file, or change it to name of UITableViewCell subclass. If you are using Storyboards, please change UITableViewCell identifier to name of the class. \n" + - "If you need different reuseIdentifier for any reason, you can change reuseIdentifier when registering mapping." - case .differentCellClass(xibName: let xibName, cellClass: let cellClass, expectedCellClass: let expectedCellClass): - return "⚠️[DTTableViewManager] Attempted to register xib \(xibName), but view found in a xib was of type \(cellClass), while expected type is \(expectedCellClass). This can prevent cells from being updated with models and react to events." - case .differentHeaderFooterClass(xibName: let xibName, viewClass: let viewClass, expectedViewClass: let expectedViewClass): - return "⚠️[DTTableViewManager] Attempted to register xib \(xibName), but view found in a xib was of type \(viewClass), while expected type is \(expectedViewClass). This can prevent headers/footers from being updated with models and react to events." - case .emptyXibFile(xibName: let xibName, expectedViewClass: let expectedViewClass): - return "⚠️[DTTableViewManager] Attempted to register xib \(xibName) for \(expectedViewClass), but this xib does not contain any views." - case .modelEventCalledWithCellClass(modelType: let modelType, methodName: let methodName, subclassOf: let subclassOf): - return - """ - ⚠️[DTTableViewManager] Event \(methodName) registered with model type, that happens to be a subclass of \(subclassOf): \(modelType). - - This is likely not what you want, because this event expects to receive model type used for current indexPath instead of cell/view. - Reasoning behind it is the fact that for some events views have not yet been created(for example: tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)). - Because they are not created yet, this event cannot be called with cell/view object, and even it's type is unknown at this point, as the mapping resolution will happen later. - - Most likely you need to use model type, that will be passed to this cell/view through ModelTransfer protocol. - For example, for height of cell that expects to receive model Int, event would look like so: - - manager.heightForCell(withItem: Int.self) { model, indexPath in - return 44 - } -""" - case .unusedEventDetected(viewType: let view, methodName: let methodName): - return "⚠️[DTTableViewManager] \(methodName) event registered for \(view), but there were no view mappings registered for \(view) type. This event will never be called." - } - } - - /// Short description for `DTTableViewManagerAnomaly`. Useful for sending to analytics, which might have character limit. - public var description: String { - switch self { - case .nilCellModel(let indexPath): return "DTTableViewManagerAnomaly.nilCellModel(\(indexPath))" - case .nilHeaderModel(let section): return "DTTableViewManagerAnomaly.nilHeaderModel(\(section))" - case .nilFooterModel(let section): return "DTTableViewManagerAnomaly.nilFooterModel(\(section))" - case .noCellMappingFound(modelDescription: let description, indexPath: let indexPath): return "DTTableViewManagerAnomaly.noCellMappingFound(\(description), \(indexPath))" - case .noHeaderFooterMappingFound(modelDescription: let description, indexPath: let indexPath): return "DTTableViewManagerAnomaly.noHeaderFooterMappingFound(\(description), \(indexPath))" - case .differentCellReuseIdentifier(mappingReuseIdentifier: let mappingIdentifier, cellReuseIdentifier: let cellIdentifier): return "DTTableViewManagerAnomaly.differentCellReuseIdentifier(\(mappingIdentifier), \(cellIdentifier))" - case .differentCellClass(xibName: let xibName, cellClass: let cellClass, expectedCellClass: let expected): return "DTTableViewManagerAnomaly.differentCellClass(\(xibName), \(cellClass), \(expected))" - case .differentHeaderFooterClass(xibName: let xibName, viewClass: let viewClass, expectedViewClass: let expected): return "DTTableViewManagerAnomaly.differentHeaderFooterClass(\(xibName), \(viewClass), \(expected))" - case .emptyXibFile(xibName: let xibName, expectedViewClass: let expected): return "DTTableViewManagerAnomaly.emptyXibFile(\(xibName), \(expected))" - case .modelEventCalledWithCellClass(modelType: let model, methodName: let method, subclassOf: let subclass): return "DTTableViewManagerAnomaly.modelEventCalledWithCellClass(\(model), \(method), \(subclass))" - case .unusedEventDetected(viewType: let view, methodName: let method): return "DTTableViewManagerAnomaly.unusedEventDetected(\(view), \(method))" - } - } -} - -/// `DTTableViewManagerAnomalyHandler` handles anomalies from `DTTableViewManager`. -open class DTTableViewManagerAnomalyHandler : AnomalyHandler { - - /// Default action to perform when anomaly is detected. Prints debugDescription of anomaly by default. - public static var defaultAction : (DTTableViewManagerAnomaly) -> Void = { - #if DEBUG - print($0.debugDescription) - #endif - } - - /// Action to perform when anomaly is detected. Defaults to `defaultAction`. - open var anomalyAction: (DTTableViewManagerAnomaly) -> Void = DTTableViewManagerAnomalyHandler.defaultAction - - /// Creates `DTTableViewManagerAnomalyHandler`. - public init() {} -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift deleted file mode 100644 index d1620fa..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewConfiguration.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// TableViewConfiguration.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 20.08.15. -// Copyright © 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit - -/// Style of section headers for table view. Depending on style, datasource methods will return title for section or view for section. Default is .title. -/// - Note: you don't need any mapping methods, if you use .title style, just add String objects to Storage, and that's it -/// - Note: When any mapping method for header or footer view is called, styles are automatically switched to .view -public enum SupplementarySectionStyle -{ - case title - case view -} - -/// Defines most commonly used configuration properties for UITableView -public struct TableViewConfiguration -{ - /// Section header style. Default - .Title. - public var sectionHeaderStyle = SupplementarySectionStyle.title - - /// Section footer style. Default - .Title - public var sectionFooterStyle = SupplementarySectionStyle.title - - /// Defines, whether to show header on a section, that does not contain any items. Default is true. - public var displayHeaderOnEmptySection = true - - /// Defines, whether to show footer on a section, that does not contain any items. Default is true. - public var displayFooterOnEmptySection = true - - /// Minimal header height to hide it when section is empty. This defaults to .zero if `UITableView.Style` is `.plain` and `.leastNormalMagnitude` otherwise. - public var minimalHeaderHeightForTableView: (UITableView) -> CGFloat = { - $0.style == .plain ? CGFloat.zero : CGFloat.leastNormalMagnitude - } - - /// Minimal footer height to hide it when section is empty. This defaults to .zero if `UITableView.Style` is `.plain` and `.leastNormalMagnitude` otherwise. - public var minimalFooterHeightForTableView: (UITableView) -> CGFloat = { - $0.style == .plain ? CGFloat.zero : CGFloat.leastNormalMagnitude - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift deleted file mode 100644 index 189e4f7..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewFactory.swift +++ /dev/null @@ -1,253 +0,0 @@ -// -// TableViewCellFactory.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 13.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import UIKit -import Foundation -import DTModelStorage - -/// Internal class, that is used to create table view cells, headers and footers. -final class TableViewFactory -{ - fileprivate let tableView: UITableView - - var mappings = [ViewModelMapping]() - - weak var anomalyHandler : DTTableViewManagerAnomalyHandler? - - init(tableView: UITableView) - { - self.tableView = tableView - } - - func registerCellClass(_ cellClass : T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T: UITableViewCell - { - let mapping = ViewModelMapping(viewType: .cell, viewClass: T.self, mappingBlock: mappingBlock) - if let cell = tableView.dequeueReusableCell(withIdentifier: mapping.reuseIdentifier) { - // Storyboard prototype cell - mappings.append(mapping) - if let cellReuseIdentifier = cell.reuseIdentifier, cellReuseIdentifier != mapping.reuseIdentifier { - anomalyHandler?.reportAnomaly(.differentCellReuseIdentifier(mappingReuseIdentifier: mapping.reuseIdentifier, cellReuseIdentifier: cellReuseIdentifier)) - } - } else { - tableView.register(T.self, forCellReuseIdentifier: mapping.reuseIdentifier) - - if UINib.nibExists(withNibName: String(describing: T.self), inBundle: mapping.bundle) { - registerNibNamed(String(describing: T.self), forCellClass: T.self, mappingBlock: mappingBlock) - } else { - mappings.append(mapping) - verifyCell(T.self, nibName: nil, withReuseIdentifier: mapping.reuseIdentifier, in: mapping.bundle) - } - } - } - - func verifyCell(_ cell: T.Type, - nibName: String?, - withReuseIdentifier reuseIdentifier: String, - in bundle: Bundle) { - var cell = T(frame: .zero) - if let nibName = nibName, UINib.nibExists(withNibName: nibName, inBundle: bundle) { - let nib = UINib(nibName: nibName, bundle: bundle) - let objects = nib.instantiate(withOwner: cell, options: nil) - if let instantiatedCell = objects.first as? T { - cell = instantiatedCell - } else { - if let first = objects.first { - anomalyHandler?.reportAnomaly(.differentCellClass(xibName: nibName, - cellClass: String(describing: type(of: first)), - expectedCellClass: String(describing: T.self))) - } else { - anomalyHandler?.reportAnomaly(.emptyXibFile(xibName: nibName, expectedViewClass: String(describing: T.self))) - } - } - } - if let cellReuseIdentifier = cell.reuseIdentifier, cellReuseIdentifier != reuseIdentifier { - anomalyHandler?.reportAnomaly(.differentCellReuseIdentifier(mappingReuseIdentifier: reuseIdentifier, cellReuseIdentifier: cellReuseIdentifier)) - } - } - - func verifyHeaderFooterView(_ view: T.Type, nibName: String?, in bundle: Bundle) { - var view = T(frame: .zero) - if let nibName = nibName, UINib.nibExists(withNibName: nibName, inBundle: bundle) { - let nib = UINib(nibName: nibName, bundle: bundle) - let objects = nib.instantiate(withOwner: view, options: nil) - if let instantiatedView = objects.first as? T { - view = instantiatedView - } else { - if let first = objects.first { - anomalyHandler?.reportAnomaly(.differentHeaderFooterClass(xibName: nibName, - viewClass: String(describing: type(of: first)), - expectedViewClass: String(describing: T.self))) - } else { - anomalyHandler?.reportAnomaly(.emptyXibFile(xibName: nibName, expectedViewClass: String(describing: T.self))) - } - } - } - } - - func registerNibNamed(_ nibName : String, forCellClass cellClass: T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T: UITableViewCell - { - let mapping = ViewModelMapping(viewType: .cell, viewClass: T.self, xibName: nibName, mappingBlock: mappingBlock) - assert(UINib.nibExists(withNibName: nibName, inBundle: mapping.bundle), "Register cell nib method should be called only if nib exists") - let nib = UINib(nibName: nibName, bundle: mapping.bundle) - tableView.register(nib, forCellReuseIdentifier: mapping.reuseIdentifier) - mappings.append(mapping) - verifyCell(T.self, nibName: nibName, withReuseIdentifier: mapping.reuseIdentifier, in: mapping.bundle) - } - - func registerNiblessHeaderClass(_ headerClass : T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T: UIView - { - let mapping = ViewModelMapping(viewType: .supplementaryView(kind: DTTableViewElementSectionHeader), viewClass: T.self, mappingBlock: mappingBlock) - tableView.register(headerClass, forHeaderFooterViewReuseIdentifier: mapping.reuseIdentifier) - mappings.append(mapping) - } - - func registerNiblessFooterClass(_ footerClass : T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T: UIView - { - let mapping = ViewModelMapping(viewType: .supplementaryView(kind: DTTableViewElementSectionFooter), viewClass: T.self, mappingBlock: mappingBlock) - tableView.register(footerClass, forHeaderFooterViewReuseIdentifier: mapping.reuseIdentifier) - mappings.append(mapping) - } - - func registerHeaderClass(_ headerClass : T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T: UIView - { - registerNibNamed(String(describing: T.self), forHeaderClass: headerClass, mappingBlock: mappingBlock) - } - - func registerFooterClass(_ footerClass: T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T:UIView - { - registerNibNamed(String(describing: T.self), forFooterClass: footerClass, mappingBlock: mappingBlock) - } - - func registerNibNamed(_ nibName: String, forHeaderClass headerClass: T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T:UIView - { - let mapping = ViewModelMapping(viewType: .supplementaryView(kind: DTTableViewElementSectionHeader), - viewClass: T.self, - xibName: nibName, - mappingBlock: mappingBlock) - - assert(UINib.nibExists(withNibName: nibName, inBundle: mapping.bundle), "Register header nib method should be called only if nib exists. If you need to register header without nib, please call `registerNiblessHeader` method.") - - if T.isSubclass(of: UITableViewHeaderFooterView.self) { - self.tableView.register(UINib(nibName: nibName, bundle: mapping.bundle), forHeaderFooterViewReuseIdentifier: mapping.reuseIdentifier) - } - mappings.append(mapping) - verifyHeaderFooterView(T.self, nibName: nibName, in: mapping.bundle) - } - - func registerNibNamed(_ nibName: String, forFooterClass footerClass: T.Type, mappingBlock: ((ViewModelMapping) -> Void)?) where T:UIView - { - let mapping = ViewModelMapping(viewType: .supplementaryView(kind: DTTableViewElementSectionFooter), - viewClass: T.self, - xibName: nibName, - mappingBlock: mappingBlock) - - assert(UINib.nibExists(withNibName: nibName, inBundle: mapping.bundle), "Register footer nib method should be called only if nib exists. If you need to register footer without nib, please call `registerNiblessHeader` method.") - - if T.isSubclass(of: UITableViewHeaderFooterView.self) { - tableView.register(UINib(nibName: nibName, bundle: mapping.bundle), forHeaderFooterViewReuseIdentifier: mapping.reuseIdentifier) - } - mappings.append(mapping) - verifyHeaderFooterView(T.self, nibName: nibName, in: mapping.bundle) - } - - func unregisterCellClass(_ cellClass: T.Type) where T: UITableViewCell { - mappings = mappings.filter({ (mapping) -> Bool in - if mapping.viewClass is T.Type && mapping.viewType == .cell { return false } - return true - }) - tableView.register(nil as AnyClass?, forCellReuseIdentifier: String(describing: T.self)) - tableView.register(nil as UINib?, forCellReuseIdentifier: String(describing: T.self)) - } - - func unregisterHeaderClass(_ headerClass: T.Type) where T: UIView { - mappings = mappings.filter({ mapping in - if mapping.viewClass is T.Type && mapping.viewType == .supplementaryView(kind: DTTableViewElementSectionHeader) { return false } - return true - }) - tableView.register(nil as AnyClass?, forHeaderFooterViewReuseIdentifier: String(describing: T.self)) - tableView.register(nil as UINib?, forHeaderFooterViewReuseIdentifier: String(describing: self)) - } - - func unregisterFooterClass(_ footerClass: T.Type) where T: UIView { - mappings = mappings.filter({ mapping in - if mapping.viewClass is T.Type && mapping.viewType == .supplementaryView(kind: DTTableViewElementSectionFooter) { return false } - return true - }) - tableView.register(nil as AnyClass?, forHeaderFooterViewReuseIdentifier: String(describing: T.self)) - tableView.register(nil as UINib?, forHeaderFooterViewReuseIdentifier: String(describing: self)) - } - - func viewModelMapping(for viewType: ViewType, model: Any, indexPath: IndexPath) -> ViewModelMapping? - { - guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { - return nil - } - return mappings.mappingCandidates(for: viewType, withModel: unwrappedModel, at: indexPath).first - } - - func cellForModel(_ model: Any, atIndexPath indexPath:IndexPath) -> UITableViewCell? - { - if let mapping = viewModelMapping(for: .cell, model: model, indexPath: indexPath) - { - let cell = tableView.dequeueReusableCell(withIdentifier: mapping.reuseIdentifier, for: indexPath) - mapping.updateBlock(cell, model) - return cell - } - anomalyHandler?.reportAnomaly(.noCellMappingFound(modelDescription: String(describing: model), indexPath: indexPath)) - return nil - } - - func updateCellAt(_ indexPath : IndexPath, with model: Any) { - guard let cell = tableView.cellForRow(at: indexPath) else { return } - guard let unwrappedModel = RuntimeHelper.recursivelyUnwrapAnyValue(model) else { return } - if let mapping = viewModelMapping(for: .cell, model: unwrappedModel, indexPath: indexPath) { - mapping.updateBlock(cell, unwrappedModel) - } - } - - func headerFooterView(of type: ViewType, model : Any, atIndexPath indexPath: IndexPath) -> UIView? - { - guard let mapping = viewModelMapping(for: type, model: model, indexPath: indexPath) else { - anomalyHandler?.reportAnomaly(.noHeaderFooterMappingFound(modelDescription: String(describing: model), indexPath: indexPath)) - return nil - } - - if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: mapping.reuseIdentifier) { - mapping.updateBlock(view, model) - return view - } else { - var view : UIView? - - if let type = mapping.viewClass as? UIView.Type { - view = type.dt_loadFromXib() - } - - if let view = view { - mapping.updateBlock(view, model) - } - return view - } - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift deleted file mode 100644 index 68c8b2b..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/TableViewUpdater.swift +++ /dev/null @@ -1,200 +0,0 @@ -// -// TableViewUpdater.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 03.09.16. -// Copyright © 2016 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -/// `TableViewUpdater` is responsible for updating `UITableView`, when it receives storage updates. -open class TableViewUpdater : StorageUpdating { - - /// table view, that will be updated - weak var tableView: UITableView? - - /// closure to be executed before content is updated - open var willUpdateContent: ((StorageUpdate?) -> Void)? - - /// closure to be executed after content is updated - open var didUpdateContent: ((StorageUpdate?) -> Void)? - -#if swift(>=4.2) - /// Insert section animation. Default - .none. - open var insertSectionAnimation = UITableView.RowAnimation.none - - /// Delete section animation. Default - .automatic - open var deleteSectionAnimation = UITableView.RowAnimation.automatic - - /// Reload section animation. Default - .automatic. - open var reloadSectionAnimation = UITableView.RowAnimation.automatic - - /// Insert row animation. Default - .automatic. - open var insertRowAnimation = UITableView.RowAnimation.automatic - - /// Delete row animation. Default - .automatic. - open var deleteRowAnimation = UITableView.RowAnimation.automatic - - /// Reload row animation. Default - .automatic. - open var reloadRowAnimation = UITableView.RowAnimation.automatic -#else - /// Insert section animation. Default - .none. - open var insertSectionAnimation = UITableViewRowAnimation.none - - /// Delete section animation. Default - .automatic - open var deleteSectionAnimation = UITableViewRowAnimation.automatic - - /// Reload section animation. Default - .automatic. - open var reloadSectionAnimation = UITableViewRowAnimation.automatic - - /// Insert row animation. Default - .automatic. - open var insertRowAnimation = UITableViewRowAnimation.automatic - - /// Delete row animation. Default - .automatic. - open var deleteRowAnimation = UITableViewRowAnimation.automatic - - /// Reload row animation. Default - .automatic. - open var reloadRowAnimation = UITableViewRowAnimation.automatic -#endif - - /// Closure to be executed, when reloading a row. - /// - /// If this property is not nil, then reloadRowAnimation property is ignored. - /// - SeeAlso: `DTTableViewManager.updateCellClosure()` method and `DTTableViewManager.coreDataUpdater()` method. - open var reloadRowClosure : ((IndexPath, Any) -> Void)? - - /// When this property is true, move events will be animated as delete event and insert event. - open var animateMoveAsDeleteAndInsert: Bool - - /// If turned on, `TableViewUpdater` will use `tableView.beginUpdates` and `tableView.endUpdates` methods instead of iOS/tvOS 11 `performBatchUpdates` method. - /// Defaults to `false`. - open var usesLegacyTableViewUpdateMethods = false - - /// If turned on, animates changes off screen, otherwise calls `tableView.reloadData` when update come offscreen. To verify if tableView is onscreen, `TableViewUpdater` compares tableView.window to nil. Defaults to true. - open var animateChangesOffScreen = true - - /// Creates updater with tableView. - public init(tableView: UITableView, reloadRow: ((IndexPath, Any) -> Void)? = nil, animateMoveAsDeleteAndInsert: Bool = false) { - self.tableView = tableView - self.reloadRowClosure = reloadRow - self.animateMoveAsDeleteAndInsert = animateMoveAsDeleteAndInsert - } - - /// Updates `UITableView` with received `update`. This method applies object and section changes in `performBatchUpdates` method or `tableView.beginUpdates` - `tableView.endUpdates` block. - /// To enable iOS 11 `performBatchUpdates` method usage, set `usesLegacyTableViewUpdateMethods` to false. It is also highly recommended to turn on `MemoryStorage.defersDatasourceUpdates` flag on to prevent multiple issues that can happen if you try to use iOS 11 `performBatchUpdates` API. - open func storageDidPerformUpdate(_ update : StorageUpdate) - { - willUpdateContent?(update) - - if !animateChangesOffScreen, tableView?.window == nil { - tableView?.reloadData() - didUpdateContent?(update) - return - } - - if #available(iOS 11, tvOS 11, *), !usesLegacyTableViewUpdateMethods { - tableView?.performBatchUpdates({ [weak self] in - if update.containsDeferredDatasourceUpdates { - update.applyDeferredDatasourceUpdates() - } - self?.applyObjectChanges(from: update) - self?.applySectionChanges(from: update) - }, completion: { [weak self] _ in - self?.didUpdateContent?(update) - }) - } else { - tableView?.beginUpdates() - if update.containsDeferredDatasourceUpdates { - update.applyDeferredDatasourceUpdates() - } - applyObjectChanges(from: update) - applySectionChanges(from: update) - - tableView?.endUpdates() - didUpdateContent?(update) - } - } - - private func applyObjectChanges(from update: StorageUpdate) { - for (change, indexPaths) in update.objectChanges { - switch change { - case .insert: - if let indexPath = indexPaths.first { - tableView?.insertRows(at: [indexPath], with: insertRowAnimation) - } - case .delete: - if let indexPath = indexPaths.first { - tableView?.deleteRows(at: [indexPath], with: deleteRowAnimation) - } - case .update: - if let indexPath = indexPaths.first { - if let closure = reloadRowClosure, let model = update.updatedObjects[indexPath] { - closure(indexPath, model) - } else { - tableView?.reloadRows(at: [indexPath], with: reloadRowAnimation) - } - } - case .move: - if let source = indexPaths.first, let destination = indexPaths.last { - if animateMoveAsDeleteAndInsert { - tableView?.moveRow(at: source, to: destination) - } else { - tableView?.deleteRows(at: [source], with: deleteRowAnimation) - tableView?.insertRows(at: [destination], with: insertRowAnimation) - } - } - } - } - } - - private func applySectionChanges(from update: StorageUpdate) { - for (change, indices) in update.sectionChanges { - switch change { - case .delete: - if let index = indices.first { - tableView?.deleteSections([index], with: deleteSectionAnimation) - } - case .insert: - if let index = indices.first { - tableView?.insertSections([index], with: insertSectionAnimation) - } - case .update: - if let index = indices.first { - tableView?.reloadSections([index], with: reloadSectionAnimation) - } - case .move: - if let source = indices.first, let destination = indices.last { - tableView?.moveSection(source, toSection: destination) - } - } - } - } - - /// Call this method, if you want UITableView to be reloaded, and beforeContentUpdate: and afterContentUpdate: closures to be called. - open func storageNeedsReloading() - { - willUpdateContent?(nil) - tableView?.reloadData() - didUpdateContent?(nil) - } -} diff --git a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift b/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift deleted file mode 100644 index 75b7410..0000000 --- a/Lesson14/Pods/DTTableViewManager/Sources/DTTableViewManager/UIView+XibLoading.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// UIView+XibLoading.swift -// DTTableViewManager -// -// Created by Denys Telezhkin on 18.07.15. -// Copyright (c) 2015 Denys Telezhkin. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation -import UIKit -import DTModelStorage - -extension UIView -{ - /// Loads view from xib with `xibName` in bundle for current class. - static func dt_loadFromXibNamed(_ xibName : String) -> UIView? - { - guard let topLevelObjects = Bundle(for: self).loadNibNamed(xibName, owner: nil, options: nil) else { - return nil - } - - for object in topLevelObjects.compactMap( { $0 as AnyObject }) { - if object.isKind(of: self) { - return object as? UIView - } - } - return nil - } - - /// Loads view from xib with `String(describing:self)` name in bundle for current class. - static func dt_loadFromXib() -> UIView? - { - return self.dt_loadFromXibNamed(String(describing: self)) - } -} diff --git a/Lesson14/Pods/Realm/LICENSE b/Lesson14/Pods/Realm/LICENSE deleted file mode 100644 index 57a0e0b..0000000 --- a/Lesson14/Pods/Realm/LICENSE +++ /dev/null @@ -1,248 +0,0 @@ -TABLE OF CONTENTS - -1. Apache License version 2.0 -2. Realm Components -3. Export Compliance - -1. ------------------------------------------------------------------------------- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -2. ------------------------------------------------------------------------------- - -REALM COMPONENTS - -This software contains components with separate copyright and license terms. -Your use of these components is subject to the terms and conditions of the -following licenses. - -For the Realm Platform Extensions component - - Realm Platform Extensions License - - Copyright (c) 2011-2017 Realm Inc All rights reserved - - Redistribution and use in binary form, with or without modification, is - permitted provided that the following conditions are met: - - 1. You agree not to attempt to decompile, disassemble, reverse engineer or - otherwise discover the source code from which the binary code was derived. - You may, however, access and obtain a separate license for most of the - source code from which this Software was created, at - http://realm.io/pricing/. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -3. ------------------------------------------------------------------------------- - -EXPORT COMPLIANCE - -You understand that the Software may contain cryptographic functions that may be -subject to export restrictions, and you represent and warrant that you are not -(i) located in a jurisdiction that is subject to United States economic -sanctions (“Prohibited Jurisdiction”), including Cuba, Iran, North Korea, -Sudan, Syria or the Crimea region, (ii) a person listed on any U.S. government -blacklist (to include the List of Specially Designated Nationals and Blocked -Persons or the Consolidated Sanctions List administered by the U.S. Department -of the Treasury’s Office of Foreign Assets Control, or the Denied Persons List -or Entity List administered by the U.S. Department of Commerce) -(“Sanctioned Person”), or (iii) controlled or 50% or more owned by a Sanctioned -Person. - -You agree to comply with all export, re-export and import restrictions and -regulations of the U.S. Department of Commerce or other agency or authority of -the United States or other applicable countries. You also agree not to transfer, -or authorize the transfer of, directly or indirectly, of the Software to any -Prohibited Jurisdiction, or otherwise in violation of any such restrictions or -regulations. diff --git a/Lesson14/Pods/Realm/README.md b/Lesson14/Pods/Realm/README.md deleted file mode 100644 index d111286..0000000 --- a/Lesson14/Pods/Realm/README.md +++ /dev/null @@ -1,73 +0,0 @@ -![Realm](https://github.com/realm/realm-cocoa/raw/master/logo.png) - -Realm is a mobile database that runs directly inside phones, tablets or wearables. -This repository holds the source code for the iOS, macOS, tvOS & watchOS versions of Realm Swift & Realm Objective-C. - -## Features - -* **Mobile-first:** Realm is the first database built from the ground up to run directly inside phones, tablets and wearables. -* **Simple:** Data is directly [exposed as objects](https://realm.io/docs/objc/latest/#models) and [queryable by code](https://realm.io/docs/objc/latest/#queries), removing the need for ORM's riddled with performance & maintenance issues. Most of our users pick it up intuitively, getting simple apps up & running in minutes. -* **Modern:** Realm supports relationships, generics, vectorization and Swift. -* **Fast:** Realm is faster than even raw SQLite on common operations, while maintaining an extremely rich feature set. - -## Getting Started - -Please see the detailed instructions in our docs to add [Realm Objective-C](https://realm.io/docs/objc/latest/#installation) _or_ [Realm Swift](https://realm.io/docs/swift/latest/#installation) to your Xcode project. - -## Documentation - -### Realm Objective-C - -The documentation can be found at [realm.io/docs/objc/latest](https://realm.io/docs/objc/latest). -The API reference is located at [realm.io/docs/objc/latest/api/](https://realm.io/docs/objc/latest/api/). - -### Realm Swift - -The documentation can be found at [realm.io/docs/swift/latest](https://realm.io/docs/swift/latest). -The API reference is located at [realm.io/docs/swift/latest/api/](https://realm.io/docs/swift/latest/api/). - -## Getting Help - -- **Need help with your code?**: Look for previous questions with the[`realm` tag](https://stackoverflow.com/questions/tagged/realm?sort=newest) on Stack Overflow or [ask a new question](https://stackoverflow.com/questions/ask?tags=realm). For general discussion that might be considered too broad for Stack Overflow, use the [Realm Forums](https://forums.realm.io). -- **Have a bug to report?** [Open a GitHub issue](https://github.com/realm/realm-cocoa/issues/new). If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue. -- **Have a feature request?** [Open a GitHub issue](https://github.com/realm/realm-cocoa/issues/new). Tell us what the feature should do and why you want the feature. - -## Building Realm - -In case you don't want to use the precompiled version, you can build Realm yourself from source. - -Prerequisites: - -* Building Realm requires Xcode 8.x. -* If cloning from git, submodules are required: `git submodule update --init --recursive`. -* Building Realm documentation requires [jazzy](https://github.com/realm/jazzy) - -Once you have all the necessary prerequisites, building Realm.framework just takes a single command: `sh build.sh build`. You'll need an internet connection the first time you build Realm to download the core binary. - -Run `sh build.sh help` to see all the actions you can perform (build ios/osx, generate docs, test, etc.). - -## Contributing - -See [CONTRIBUTING.md](CONTRIBUTING.md) for more details! - -This project adheres to the [Contributor Covenant Code of Conduct](https://realm.io/conduct). -By participating, you are expected to uphold this code. Please report -unacceptable behavior to [info@realm.io](mailto:info@realm.io). - -## License - -Realm Objective-C & Realm Swift are published under the Apache 2.0 license. -Realm Core is also published under the Apache 2.0 license and is available -[here](https://github.com/realm/realm-core). - -**This product is not being made available to any person located in Cuba, Iran, -North Korea, Sudan, Syria or the Crimea region, or to any other person that is -not eligible to receive the product under U.S. law.** - -## Feedback - -**_If you use Realm and are happy with it, all we ask is that you please consider sending out a tweet mentioning [@realm](https://twitter.com/realm) to share your thoughts!_** - -**_And if you don't like it, please let us know what you would like improved, so we can fix it!_** - -![analytics](https://ga-beacon.appspot.com/UA-50247013-2/realm-cocoa/README?pixel) diff --git a/Lesson14/Pods/Realm/Realm/NSError+RLMSync.m b/Lesson14/Pods/Realm/Realm/NSError+RLMSync.m deleted file mode 100644 index e8c2590..0000000 --- a/Lesson14/Pods/Realm/Realm/NSError+RLMSync.m +++ /dev/null @@ -1,43 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "NSError+RLMSync.h" - -#import "RLMSyncUtil.h" - -@implementation NSError (RLMSync) - -- (RLMSyncErrorActionToken *)rlmSync_errorActionToken { - if (self.domain != RLMSyncErrorDomain) { - return nil; - } - if (self.code == RLMSyncErrorClientResetError - || self.code == RLMSyncErrorPermissionDeniedError) { - return (RLMSyncErrorActionToken *)self.userInfo[kRLMSyncErrorActionTokenKey]; - } - return nil; -} - -- (NSString *)rlmSync_clientResetBackedUpRealmPath { - if (self.domain == RLMSyncErrorDomain && self.code == RLMSyncErrorClientResetError) { - return self.userInfo[kRLMSyncPathOfRealmBackupCopyKey]; - } - return nil; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp deleted file mode 100644 index 0c388d0..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/binding_callback_thread_observer.cpp +++ /dev/null @@ -1,23 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "binding_callback_thread_observer.hpp" - -namespace realm { -BindingCallbackThreadObserver* g_binding_callback_thread_observer = nullptr; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp deleted file mode 100644 index 03fad73..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/collection_notifications.cpp +++ /dev/null @@ -1,61 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "collection_notifications.hpp" - -#include "impl/collection_notifier.hpp" - -using namespace realm; -using namespace realm::_impl; - -NotificationToken::NotificationToken(std::shared_ptr<_impl::CollectionNotifier> notifier, uint64_t token) -: m_notifier(std::move(notifier)), m_token(token) -{ -} - -NotificationToken::~NotificationToken() -{ - // m_notifier itself (and not just the pointed-to thing) needs to be accessed - // atomically to ensure that there are no data races when the token is - // destroyed after being modified on a different thread. - // This is needed despite the token not being thread-safe in general as - // users find it very surprising for obj-c objects to care about what - // thread they are deallocated on. - if (auto notifier = m_notifier.exchange({})) { - notifier->remove_callback(m_token); - } -} - -NotificationToken::NotificationToken(NotificationToken&&) = default; - -NotificationToken& NotificationToken::operator=(realm::NotificationToken&& rgt) -{ - if (this != &rgt) { - if (auto notifier = m_notifier.exchange({})) { - notifier->remove_callback(m_token); - } - m_notifier = std::move(rgt.m_notifier); - m_token = rgt.m_token; - } - return *this; -} - -void NotificationToken::suppress_next() -{ - m_notifier.load()->suppress_next_notification(m_token); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp deleted file mode 100644 index fd56c9e..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/external_commit_helper.cpp +++ /dev/null @@ -1,243 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/external_commit_helper.hpp" -#include "impl/realm_coordinator.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace realm; -using namespace realm::_impl; - -namespace { -// Write a byte to a pipe to notify anyone waiting for data on the pipe -void notify_fd(int fd, int read_fd) -{ - while (true) { - char c = 0; - ssize_t ret = write(fd, &c, 1); - if (ret == 1) { - break; - } - - // If the pipe's buffer is full, we need to read some of the old data in - // it to make space. We don't just read in the code waiting for - // notifications so that we can notify multiple waiters with a single - // write. - assert(ret == -1 && errno == EAGAIN); - char buff[1024]; - read(read_fd, buff, sizeof buff); - } -} - -} // anonymous namespace - -void ExternalCommitHelper::FdHolder::close() -{ - if (m_fd != -1) { - ::close(m_fd); - } - m_fd = -1; -} - -// Inter-thread and inter-process notifications of changes are done using a -// named pipe in the filesystem next to the Realm file. Everyone who wants to be -// notified of commits waits for data to become available on the pipe, and anyone -// who commits a write transaction writes data to the pipe after releasing the -// write lock. Note that no one ever actually *reads* from the pipe: the data -// actually written is meaningless, and trying to read from a pipe from multiple -// processes at once is fraught with race conditions. - -// When a RLMRealm instance is created, we add a CFRunLoopSource to the current -// thread's runloop. On each cycle of the run loop, the run loop checks each of -// its sources for work to do, which in the case of CFRunLoopSource is just -// checking if CFRunLoopSourceSignal has been called since the last time it ran, -// and if so invokes the function pointer supplied when the source is created, -// which in our case just invokes `[realm handleExternalChange]`. - -// Listening for external changes is done using kqueue() on a background thread. -// kqueue() lets us efficiently wait until the amount of data which can be read -// from one or more file descriptors has changed, and tells us which of the file -// descriptors it was that changed. We use this to wait on both the shared named -// pipe, and a local anonymous pipe. When data is written to the named pipe, we -// signal the runloop source and wake up the target runloop, and when data is -// written to the anonymous pipe the background thread removes the runloop -// source from the runloop and and shuts down. -ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent) -: m_parent(parent) -{ - m_kq = kqueue(); - if (m_kq == -1) { - throw std::system_error(errno, std::system_category()); - } - -#if !TARGET_OS_TV - - - // Object Store needs to create a named pipe in order to coordinate notifications. - // This can be a problem on some file systems (e.g. FAT32) or due to security policies in SELinux. Most commonly - // it is a problem when saving Realms on external storage: https://stackoverflow.com/questions/2740321/how-to-create-named-pipe-mkfifo-in-android - // - // For this reason we attempt to create this file in a temporary location known to be safe to write these files. - // - // In order of priority we attempt to write the file in the following locations: - // 1) Next to the Realm file itself - // 2) A location defined by `Realm::Config::fifo_files_fallback_path` - // 3) A location defined by `SharedGroupOptions::set_sys_tmp_dir()` - // - // Core has a similar policy for its named pipes. - // - // Also see https://github.com/realm/realm-java/issues/3140 - // Note that hash collisions are okay here because they just result in doing extra work instead of resulting - // in correctness problems. - - std::string path; - std::string temp_dir = util::normalize_dir(parent.get_config().fifo_files_fallback_path); - std::string sys_temp_dir = util::normalize_dir(SharedGroupOptions::get_sys_tmp_dir()); - - path = parent.get_path() + ".note"; - bool fifo_created = realm::util::try_create_fifo(path); - if (!fifo_created && !temp_dir.empty()) { - path = util::format("%1realm_%2.note", temp_dir, std::hash()(parent.get_path())); - fifo_created = realm::util::try_create_fifo(path); - } - if (!fifo_created && !sys_temp_dir.empty()) { - path = util::format("%1realm_%2.note", sys_temp_dir, std::hash()(parent.get_path())); - realm::util::create_fifo(path); - } - - m_notify_fd = open(path.c_str(), O_RDWR); - if (m_notify_fd == -1) { - throw std::system_error(errno, std::system_category()); - } - - // Make writing to the pipe return -1 when the pipe's buffer is full - // rather than blocking until there's space available - int ret = fcntl(m_notify_fd, F_SETFL, O_NONBLOCK); - if (ret == -1) { - throw std::system_error(errno, std::system_category()); - } - -#else // !TARGET_OS_TV - - // tvOS does not support named pipes, so use an anonymous pipe instead - int notification_pipe[2]; - int ret = pipe(notification_pipe); - if (ret == -1) { - throw std::system_error(errno, std::system_category()); - } - - m_notify_fd = notification_pipe[0]; - m_notify_fd_write = notification_pipe[1]; - -#endif // TARGET_OS_TV - - // Create the anonymous pipe for shutdown notifications - int shutdown_pipe[2]; - ret = pipe(shutdown_pipe); - if (ret == -1) { - throw std::system_error(errno, std::system_category()); - } - - m_shutdown_read_fd = shutdown_pipe[0]; - m_shutdown_write_fd = shutdown_pipe[1]; - - m_thread = std::thread([=] { - try { - listen(); - } -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - catch (std::exception const& e) { - fprintf(stderr, "uncaught exception in notifier thread: %s: %s\n", typeid(e).name(), e.what()); - asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "uncaught exception in notifier thread: %s: %s", typeid(e).name(), e.what()); - throw; - } - catch (...) { - fprintf(stderr, "uncaught exception in notifier thread\n"); - asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "uncaught exception in notifier thread"); - throw; - } -#pragma clang diagnostic pop - }); -} - -ExternalCommitHelper::~ExternalCommitHelper() -{ - notify_fd(m_shutdown_write_fd, m_shutdown_read_fd); - m_thread.join(); // Wait for the thread to exit -} - -void ExternalCommitHelper::listen() -{ - pthread_setname_np("Realm notification listener"); - - // Set up the kqueue - // EVFILT_READ indicates that we care about data being available to read - // on the given file descriptor. - // EV_CLEAR makes it wait for the amount of data available to be read to - // change rather than just returning when there is any data to read. - struct kevent ke[2]; - EV_SET(&ke[0], m_notify_fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, 0); - EV_SET(&ke[1], m_shutdown_read_fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, 0); - int ret = kevent(m_kq, ke, 2, nullptr, 0, nullptr); - assert(ret == 0); - - while (true) { - struct kevent event; - // Wait for data to become on either fd - // Return code is number of bytes available or -1 on error - ret = kevent(m_kq, nullptr, 0, &event, 1, nullptr); - if (ret == 0 || (ret < 0 && errno == EINTR)) { - // Spurious wakeup; just wait again - continue; - } - assert(ret > 0); - - // Check which file descriptor had activity: if it's the shutdown - // pipe, then someone called -stop; otherwise it's the named pipe - // and someone committed a write transaction - if (event.ident == (uint32_t)m_shutdown_read_fd) { - return; - } - assert(event.ident == (uint32_t)m_notify_fd); - - m_parent.on_change(); - } -} - -void ExternalCommitHelper::notify_others() -{ - if (m_notify_fd_write != -1) { - notify_fd(m_notify_fd_write, m_notify_fd); - } - else { - notify_fd(m_notify_fd, m_notify_fd); - } -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp deleted file mode 100644 index 8c9000c..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/apple/keychain_helper.cpp +++ /dev/null @@ -1,143 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/apple/keychain_helper.hpp" - - -#include -#include - -#include - -#include - -using realm::util::CFPtr; -using realm::util::adoptCF; -using realm::util::retainCF; - -namespace realm { -namespace keychain { - -KeychainAccessException::KeychainAccessException(int32_t error_code) -: std::runtime_error(util::format("Keychain returned unexpected status code: %1", error_code)) { } - -namespace { - -constexpr size_t key_size = 64; - -#if !TARGET_IPHONE_SIMULATOR -CFPtr convert_string(const std::string& string) -{ - auto result = adoptCF(CFStringCreateWithBytes(nullptr, reinterpret_cast(string.data()), - string.size(), kCFStringEncodingASCII, false)); - if (!result) { - throw std::bad_alloc(); - } - return result; -} -#endif - -CFPtr build_search_dictionary(CFStringRef account, CFStringRef service, - __unused util::Optional group) -{ - auto d = adoptCF(CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); - if (!d) - throw std::bad_alloc(); - - CFDictionaryAddValue(d.get(), kSecClass, kSecClassGenericPassword); - CFDictionaryAddValue(d.get(), kSecReturnData, kCFBooleanTrue); - CFDictionaryAddValue(d.get(), kSecAttrAccessible, kSecAttrAccessibleAlways); - CFDictionaryAddValue(d.get(), kSecAttrAccount, account); - CFDictionaryAddValue(d.get(), kSecAttrService, service); -#if !TARGET_IPHONE_SIMULATOR - if (group) - CFDictionaryAddValue(d.get(), kSecAttrAccessGroup, convert_string(*group).get()); -#endif - return d; -} - -/// Get the encryption key for a given service, returning it only if it exists. -util::Optional> get_key(CFStringRef account, CFStringRef service) -{ - auto search_dictionary = build_search_dictionary(account, service, none); - CFDataRef retained_key_data; - if (OSStatus status = SecItemCopyMatching(search_dictionary.get(), (CFTypeRef *)&retained_key_data)) { - if (status != errSecItemNotFound) - throw KeychainAccessException(status); - - // Key was not found. - return none; - } - - // Key was previously stored. Extract it. - CFPtr key_data = adoptCF(retained_key_data); - if (key_size != CFDataGetLength(key_data.get())) - throw std::runtime_error("Password stored in keychain was not expected size."); - - auto key_bytes = reinterpret_cast(CFDataGetBytePtr(key_data.get())); - return std::vector(key_bytes, key_bytes + key_size); -} - -void set_key(const std::vector& key, CFStringRef account, CFStringRef service) -{ - auto search_dictionary = build_search_dictionary(account, service, none); - auto key_data = adoptCF(CFDataCreate(nullptr, reinterpret_cast(key.data()), key_size)); - if (!key_data) - throw std::bad_alloc(); - - CFDictionaryAddValue(search_dictionary.get(), kSecValueData, key_data.get()); - if (OSStatus status = SecItemAdd(search_dictionary.get(), nullptr)) - throw KeychainAccessException(status); -} - -} // anonymous namespace - -std::vector metadata_realm_encryption_key(bool check_legacy_service) -{ - CFStringRef account = CFSTR("metadata"); - CFStringRef legacy_service = CFSTR("io.realm.sync.keychain"); - - CFPtr service; - if (CFStringRef bundle_id = CFBundleGetIdentifier(CFBundleGetMainBundle())) - service = adoptCF(CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ - Realm Sync Metadata Key"), bundle_id)); - else { - service = retainCF(legacy_service); - check_legacy_service = false; - } - - // Try retrieving the key. - if (auto existing_key = get_key(account, service.get())) { - return *existing_key; - } else if (check_legacy_service) { - // See if there's a key stored using the legacy shared keychain item. - if (auto existing_legacy_key = get_key(account, legacy_service)) { - // If so, copy it to the per-app keychain item before returning it. - set_key(*existing_legacy_key, account, service.get()); - return *existing_legacy_key; - } - } - // Make a completely new key. - std::vector key(key_size); - arc4random_buf(key.data(), key_size); - set_key(key, account, service.get()); - return key; -} - -} // keychain -} // realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp deleted file mode 100644 index 40b5754..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_change_builder.cpp +++ /dev/null @@ -1,887 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/collection_change_builder.hpp" - -#include -#include - -#include - -using namespace realm; -using namespace realm::_impl; - -CollectionChangeBuilder::CollectionChangeBuilder(IndexSet deletions, - IndexSet insertions, - IndexSet modifications, - std::vector moves) -: CollectionChangeSet({std::move(deletions), std::move(insertions), std::move(modifications), {}, std::move(moves)}) -{ - for (auto&& move : this->moves) { - this->deletions.add(move.from); - this->insertions.add(move.to); - } -} - -void CollectionChangeBuilder::merge(CollectionChangeBuilder&& c) -{ - if (c.empty()) - return; - if (empty()) { - *this = std::move(c); - return; - } - - verify(); - c.verify(); - - auto for_each_col = [&](auto&& f) { - f(modifications, c.modifications); - if (m_track_columns) { - if (columns.size() < c.columns.size()) - columns.resize(c.columns.size()); - else if (columns.size() > c.columns.size()) - c.columns.resize(columns.size()); - for (size_t i = 0; i < columns.size(); ++i) - f(columns[i], c.columns[i]); - } - }; - - // First update any old moves - if (!c.moves.empty() || !c.deletions.empty() || !c.insertions.empty()) { - auto it = std::remove_if(begin(moves), end(moves), [&](auto& old) { - // Check if the moved row was moved again, and if so just update the destination - auto it = find_if(begin(c.moves), end(c.moves), [&](auto const& m) { - return old.to == m.from; - }); - if (it != c.moves.end()) { - for_each_col([&](auto& col, auto& other) { - if (col.contains(it->from)) - other.add(it->to); - }); - old.to = it->to; - *it = c.moves.back(); - c.moves.pop_back(); - return false; - } - - // Check if the destination was deleted - // Removing the insert for this move will happen later - if (c.deletions.contains(old.to)) - return true; - - // Update the destination to adjust for any new insertions and deletions - old.to = c.insertions.shift(c.deletions.unshift(old.to)); - return false; - }); - moves.erase(it, end(moves)); - } - - // Ignore new moves of rows which were previously inserted (the implicit - // delete from the move will remove the insert) - if (!insertions.empty() && !c.moves.empty()) { - c.moves.erase(std::remove_if(begin(c.moves), end(c.moves), - [&](auto const& m) { return insertions.contains(m.from); }), - end(c.moves)); - } - - // Ensure that any previously modified rows which were moved are still modified - if (!modifications.empty() && !c.moves.empty()) { - for (auto const& move : c.moves) { - for_each_col([&](auto& col, auto& other) { - if (col.contains(move.from)) - other.add(move.to); - }); - } - } - - // Update the source position of new moves to compensate for the changes made - // in the old changeset - if (!deletions.empty() || !insertions.empty()) { - for (auto& move : c.moves) - move.from = deletions.shift(insertions.unshift(move.from)); - } - - moves.insert(end(moves), begin(c.moves), end(c.moves)); - - // New deletion indices have been shifted by the insertions, so unshift them - // before adding - deletions.add_shifted_by(insertions, c.deletions); - - // Drop any inserted-then-deleted rows, then merge in new insertions - insertions.erase_at(c.deletions); - insertions.insert_at(c.insertions); - - clean_up_stale_moves(); - - for_each_col([&](auto& col, auto& other) { - col.erase_at(c.deletions); - col.shift_for_insert_at(c.insertions); - col.add(other); - }); - - c = {}; - verify(); -} - -void CollectionChangeBuilder::clean_up_stale_moves() -{ - // Look for moves which are now no-ops, and remove them plus the associated - // insert+delete. Note that this isn't just checking for from == to due to - // that rows can also be shifted by other inserts and deletes - moves.erase(std::remove_if(begin(moves), end(moves), [&](auto const& move) { - if (move.from - deletions.count(0, move.from) != move.to - insertions.count(0, move.to)) - return false; - deletions.remove(move.from); - insertions.remove(move.to); - return true; - }), end(moves)); -} - -void CollectionChangeBuilder::parse_complete() -{ - moves.reserve(m_move_mapping.size()); - for (auto move : m_move_mapping) { - REALM_ASSERT_DEBUG(deletions.contains(move.second)); - REALM_ASSERT_DEBUG(insertions.contains(move.first)); - if (move.first == move.second) { - deletions.remove(move.second); - insertions.remove(move.first); - } - else - moves.push_back({move.second, move.first}); - } - m_move_mapping.clear(); - std::sort(begin(moves), end(moves), - [](auto const& a, auto const& b) { return a.from < b.from; }); -} - -void CollectionChangeBuilder::modify(size_t ndx, size_t col) -{ - modifications.add(ndx); - if (!m_track_columns || col == IndexSet::npos) - return; - - if (col >= columns.size()) - columns.resize(col + 1); - columns[col].add(ndx); -} - -template -void CollectionChangeBuilder::for_each_col(Func&& f) -{ - f(modifications); - if (m_track_columns) { - for (auto& col : columns) - f(col); - } -} - -void CollectionChangeBuilder::insert(size_t index, size_t count, bool track_moves) -{ - REALM_ASSERT(count != 0); - - for_each_col([=](auto& col) { col.shift_for_insert_at(index, count); }); - if (!track_moves) - return; - - insertions.insert_at(index, count); - - for (auto& move : moves) { - if (move.to >= index) - move.to += count; - } - - if (m_move_mapping.empty()) - return; - - // m_move_mapping is new_ndx -> old_ndx, so updating the keys requires - // deleting and re-inserting at the new index - std::vector> shifted; - for (auto it = m_move_mapping.begin(); it != m_move_mapping.end(); ) { - if (it->first >= index) { - shifted.emplace_back(it->first + count, it->second); - it = m_move_mapping.erase(it); - } - else { - ++it; - } - } - for (auto& pair : shifted) - m_move_mapping.insert(pair); -} - -void CollectionChangeBuilder::erase(size_t index) -{ - for_each_col([=](auto& col) { col.erase_at(index); }); - size_t unshifted = insertions.erase_or_unshift(index); - if (unshifted != IndexSet::npos) - deletions.add_shifted(unshifted); - - for (size_t i = 0; i < moves.size(); ++i) { - auto& move = moves[i]; - if (move.to == index) { - moves.erase(moves.begin() + i); - --i; - } - else if (move.to > index) - --move.to; - } -} - -void CollectionChangeBuilder::clear(size_t old_size) -{ - if (old_size != std::numeric_limits::max()) { - for (auto range : deletions) - old_size += range.second - range.first; - for (auto range : insertions) - old_size -= range.second - range.first; - } - - modifications.clear(); - insertions.clear(); - moves.clear(); - m_move_mapping.clear(); - columns.clear(); - deletions.set(old_size); -} - -void CollectionChangeBuilder::move(size_t from, size_t to) -{ - REALM_ASSERT(from != to); - - bool updated_existing_move = false; - for (auto& move : moves) { - if (move.to != from) { - // Shift other moves if this row is moving from one side of them - // to the other - if (move.to >= to && move.to < from) - ++move.to; - else if (move.to <= to && move.to > from) - --move.to; - continue; - } - REALM_ASSERT(!updated_existing_move); - - // Collapse A -> B, B -> C into a single A -> C move - move.to = to; - updated_existing_move = true; - - insertions.erase_at(from); - insertions.insert_at(to); - } - - if (!updated_existing_move) { - auto shifted_from = insertions.erase_or_unshift(from); - insertions.insert_at(to); - - // Don't report deletions/moves for newly inserted rows - if (shifted_from != IndexSet::npos) { - shifted_from = deletions.add_shifted(shifted_from); - moves.push_back({shifted_from, to}); - } - } - - for_each_col([=](auto& col) { - bool modified = col.contains(from); - col.erase_at(from); - - if (modified) - col.insert_at(to); - else - col.shift_for_insert_at(to); - }); -} - -void CollectionChangeBuilder::move_over(size_t row_ndx, size_t last_row, bool track_moves) -{ - REALM_ASSERT(row_ndx <= last_row); - REALM_ASSERT(insertions.empty() || prev(insertions.end())->second - 1 <= last_row); - REALM_ASSERT(modifications.empty() || prev(modifications.end())->second - 1 <= last_row); - - if (row_ndx == last_row) { - if (track_moves) { - auto shifted_from = insertions.erase_or_unshift(row_ndx); - if (shifted_from != IndexSet::npos) - deletions.add_shifted(shifted_from); - m_move_mapping.erase(row_ndx); - } - for_each_col([=](auto& col) { col.remove(row_ndx); }); - return; - } - - for_each_col([=](auto& col) { - bool modified = col.contains(last_row); - if (modified) { - col.remove(last_row); - col.add(row_ndx); - } - else - col.remove(row_ndx); - }); - - if (!track_moves) - return; - - bool row_is_insertion = insertions.contains(row_ndx); - bool last_is_insertion = !insertions.empty() && prev(insertions.end())->second == last_row + 1; - REALM_ASSERT_DEBUG(insertions.empty() || prev(insertions.end())->second <= last_row + 1); - - // Collapse A -> B, B -> C into a single A -> C move - bool last_was_already_moved = false; - if (last_is_insertion) { - auto it = m_move_mapping.find(last_row); - if (it != m_move_mapping.end() && it->first == last_row) { - m_move_mapping[row_ndx] = it->second; - m_move_mapping.erase(it); - last_was_already_moved = true; - } - } - - // Remove moves to the row being deleted - if (row_is_insertion && !last_was_already_moved) { - auto it = m_move_mapping.find(row_ndx); - if (it != m_move_mapping.end() && it->first == row_ndx) - m_move_mapping.erase(it); - } - - // Don't report deletions/moves if last_row is newly inserted - if (last_is_insertion) { - insertions.remove(last_row); - } - // If it was previously moved, the unshifted source row has already been marked as deleted - else if (!last_was_already_moved) { - auto shifted_last_row = insertions.unshift(last_row); - shifted_last_row = deletions.add_shifted(shifted_last_row); - m_move_mapping[row_ndx] = shifted_last_row; - } - - // Don't mark the moved-over row as deleted if it was a new insertion - if (!row_is_insertion) { - deletions.add_shifted(insertions.unshift(row_ndx)); - insertions.add(row_ndx); - } - verify(); -} - -void CollectionChangeBuilder::swap(size_t ndx_1, size_t ndx_2, bool track_moves) -{ - REALM_ASSERT(ndx_1 != ndx_2); - // The order of the two indices doesn't matter semantically, but making them - // consistent simplifies the logic - if (ndx_1 > ndx_2) - std::swap(ndx_1, ndx_2); - - for_each_col([=](auto& col) { - bool row_1_modified = col.contains(ndx_1); - bool row_2_modified = col.contains(ndx_2); - if (row_1_modified != row_2_modified) { - if (row_1_modified) { - col.remove(ndx_1); - col.add(ndx_2); - } - else { - col.remove(ndx_2); - col.add(ndx_1); - } - } - }); - - if (!track_moves) - return; - - auto update_move = [&](auto existing_it, auto ndx_1, auto ndx_2) { - // update the existing move to ndx_2 to point at ndx_1 - auto original = existing_it->second; - m_move_mapping.erase(existing_it); - m_move_mapping[ndx_1] = original; - - // add a move from 1 -> 2 unless 1 was a new insertion - if (!insertions.contains(ndx_1)) { - m_move_mapping[ndx_2] = deletions.add_shifted(insertions.unshift(ndx_1)); - insertions.add(ndx_1); - } - REALM_ASSERT_DEBUG(insertions.contains(ndx_2)); - }; - - auto move_1 = m_move_mapping.find(ndx_1); - auto move_2 = m_move_mapping.find(ndx_2); - bool have_move_1 = move_1 != end(m_move_mapping) && move_1->first == ndx_1; - bool have_move_2 = move_2 != end(m_move_mapping) && move_2->first == ndx_2; - if (have_move_1 && have_move_2) { - // both are already moves, so just swap the destinations - std::swap(move_1->second, move_2->second); - } - else if (have_move_1) { - update_move(move_1, ndx_2, ndx_1); - } - else if (have_move_2) { - update_move(move_2, ndx_1, ndx_2); - } - else { - // ndx_2 needs to be done before 1 to avoid incorrect shifting - if (!insertions.contains(ndx_2)) { - m_move_mapping[ndx_1] = deletions.add_shifted(insertions.unshift(ndx_2)); - insertions.add(ndx_2); - } - if (!insertions.contains(ndx_1)) { - m_move_mapping[ndx_2] = deletions.add_shifted(insertions.unshift(ndx_1)); - insertions.add(ndx_1); - } - } -} - -void CollectionChangeBuilder::subsume(size_t old_ndx, size_t new_ndx, bool track_moves) -{ - REALM_ASSERT(old_ndx != new_ndx); - - for_each_col([=](auto& col) { - if (col.contains(old_ndx)) { - col.add(new_ndx); - } - }); - - if (!track_moves) - return; - - REALM_ASSERT_DEBUG(insertions.contains(new_ndx)); - REALM_ASSERT_DEBUG(!m_move_mapping.count(new_ndx)); - - // If the source row was already moved, update the existing move - auto it = m_move_mapping.find(old_ndx); - if (it != m_move_mapping.end() && it->first == old_ndx) { - m_move_mapping[new_ndx] = it->second; - m_move_mapping.erase(it); - } - // otherwise add a new move unless it was a new insertion - else if (!insertions.contains(old_ndx)) { - m_move_mapping[new_ndx] = deletions.shift(insertions.unshift(old_ndx)); - } - - verify(); -} - -void CollectionChangeBuilder::verify() -{ -#ifdef REALM_DEBUG - for (auto&& move : moves) { - REALM_ASSERT(deletions.contains(move.from)); - REALM_ASSERT(insertions.contains(move.to)); - } -#endif -} - -void CollectionChangeBuilder::insert_column(size_t ndx) -{ - if (ndx < columns.size()) - columns.insert(columns.begin() + ndx, IndexSet{}); -} - -void CollectionChangeBuilder::move_column(size_t from, size_t to) -{ - if (from >= columns.size() && to >= columns.size()) - return; - if (from >= columns.size() || to >= columns.size()) - columns.resize(std::max(from, to) + 1); - if (from < to) - std::rotate(begin(columns) + from, begin(columns) + from + 1, begin(columns) + to + 1); - else - std::rotate(begin(columns) + to, begin(columns) + from, begin(columns) + from + 1); -} - -namespace { -struct RowInfo { - size_t row_index; - size_t prev_tv_index; - size_t tv_index; - size_t shifted_tv_index; -}; - -// Calculates the insertions/deletions required for a query on a table without -// a sort, where `removed` includes the rows which were modified to no longer -// match the query (but not outright deleted rows, which are filtered out long -// before any of this logic), and `move_candidates` tracks the rows which may -// be the result of a move. -// -// This function is not strictly required, as calculate_moves_sorted() will -// produce correct results even for the scenarios where this function is used. -// However, this function has asymptotically better worst-case performance and -// extremely cheap best-case performance, and is guaranteed to produce a minimal -// diff when the only row moves are due to move_last_over(). -void calculate_moves_unsorted(std::vector& new_rows, IndexSet& removed, - IndexSet const& move_candidates, - CollectionChangeSet& changeset) -{ - // Here we track which row we expect to see, which in the absence of swap() - // is always the row immediately after the last row which was not moved. - size_t expected = 0; - for (auto& row : new_rows) { - if (row.shifted_tv_index == expected) { - ++expected; - continue; - } - - // We didn't find the row we were expecting to find, which means that - // either a row was moved forward to here, the row we were expecting was - // removed, or the row we were expecting moved back. - - // First check if this row even could have moved. If it can't, just - // treat it as a match and move on, and we'll handle the row we were - // expecting when we hit it later. - if (!move_candidates.contains(row.row_index)) { - expected = row.shifted_tv_index + 1; - continue; - } - - // Next calculate where we expect this row to be based on the insertions - // and removals (i.e. rows changed to not match the query), as it could - // be that the row actually ends up in this spot due to the rows before - // it being removed. - size_t calc_expected = row.tv_index - changeset.insertions.count(0, row.tv_index) + removed.count(0, row.prev_tv_index); - if (row.shifted_tv_index == calc_expected) { - expected = calc_expected + 1; - continue; - } - - // The row still isn't the expected one, so record it as a move - changeset.moves.push_back({row.prev_tv_index, row.tv_index}); - changeset.insertions.add(row.tv_index); - removed.add(row.prev_tv_index); - } -} - -class LongestCommonSubsequenceCalculator { -public: - // A pair of an index in the table and an index in the table view - struct Row { - size_t row_index; - size_t tv_index; - }; - - struct Match { - // The index in `a` at which this match begins - size_t i; - // The index in `b` at which this match begins - size_t j; - // The length of this match - size_t size; - // The number of rows in this block which were modified - size_t modified; - }; - std::vector m_longest_matches; - - LongestCommonSubsequenceCalculator(std::vector& a, std::vector& b, - size_t start_index, - IndexSet const& modifications) - : m_modified(modifications) - , a(a), b(b) - { - find_longest_matches(start_index, a.size(), - start_index, b.size()); - m_longest_matches.push_back({a.size(), b.size(), 0}); - } - -private: - IndexSet const& m_modified; - - // The two arrays of rows being diffed - // a is sorted by tv_index, b is sorted by row_index - std::vector &a, &b; - - // Find the longest matching range in (a + begin1, a + end1) and (b + begin2, b + end2) - // "Matching" is defined as "has the same row index"; the TV index is just - // there to let us turn an index in a/b into an index which can be reported - // in the output changeset. - // - // This is done with the O(N) space variant of the dynamic programming - // algorithm for longest common subsequence, where N is the maximum number - // of the most common row index (which for everything but linkview-derived - // TVs will be 1). - Match find_longest_match(size_t begin1, size_t end1, size_t begin2, size_t end2) - { - struct Length { - size_t j, len; - }; - // The length of the matching block for each `j` for the previously checked row - std::vector prev; - // The length of the matching block for each `j` for the row currently being checked - std::vector cur; - - // Calculate the length of the matching block *ending* at b[j], which - // is 1 if b[j - 1] did not match, and b[j - 1] + 1 otherwise. - auto length = [&](size_t j) -> size_t { - for (auto const& pair : prev) { - if (pair.j + 1 == j) - return pair.len + 1; - } - return 1; - }; - - // Iterate over each `j` which has the same row index as a[i] and falls - // within the range begin2 <= j < end2 - auto for_each_b_match = [&](size_t i, auto&& f) { - size_t ai = a[i].row_index; - // Find the TV indicies at which this row appears in the new results - // There should always be at least one (or it would have been - // filtered out earlier), but there can be multiple if there are dupes - auto it = lower_bound(begin(b), end(b), ai, - [](auto lft, auto rgt) { return lft.row_index < rgt; }); - REALM_ASSERT(it != end(b) && it->row_index == ai); - for (; it != end(b) && it->row_index == ai; ++it) { - size_t j = it->tv_index; - if (j < begin2) - continue; - if (j >= end2) - break; // b is sorted by tv_index so this can't transition from false to true - f(j); - } - }; - - Match best = {begin1, begin2, 0, 0}; - for (size_t i = begin1; i < end1; ++i) { - // prev = std::move(cur), but avoids discarding prev's heap allocation - cur.swap(prev); - cur.clear(); - - for_each_b_match(i, [&](size_t j) { - size_t size = length(j); - - cur.push_back({j, size}); - - // If the matching block ending at a[i] and b[j] is longer than - // the previous one, select it as the best - if (size > best.size) - best = {i - size + 1, j - size + 1, size, IndexSet::npos}; - // Given two equal-length matches, prefer the one with fewer modified rows - else if (size == best.size) { - if (best.modified == IndexSet::npos) - best.modified = m_modified.count(best.j - size + 1, best.j + 1); - auto count = m_modified.count(j - size + 1, j + 1); - if (count < best.modified) - best = {i - size + 1, j - size + 1, size, count}; - } - - // The best block should always fall within the range being searched - REALM_ASSERT(best.i >= begin1 && best.i + best.size <= end1); - REALM_ASSERT(best.j >= begin2 && best.j + best.size <= end2); - }); - } - return best; - } - - void find_longest_matches(size_t begin1, size_t end1, size_t begin2, size_t end2) - { - // FIXME: recursion could get too deep here - // recursion depth worst case is currently O(N) and each recursion uses 320 bytes of stack - // could reduce worst case to O(sqrt(N)) (and typical case to O(log N)) - // biasing equal selections towards the middle, but that's still - // insufficient for Android's 8 KB stacks - auto m = find_longest_match(begin1, end1, begin2, end2); - if (!m.size) - return; - if (m.i > begin1 && m.j > begin2) - find_longest_matches(begin1, m.i, begin2, m.j); - m_longest_matches.push_back(m); - if (m.i + m.size < end2 && m.j + m.size < end2) - find_longest_matches(m.i + m.size, end1, m.j + m.size, end2); - } -}; - -void calculate_moves_sorted(std::vector& rows, CollectionChangeSet& changeset) -{ - // The RowInfo array contains information about the old and new TV indices of - // each row, which we need to turn into two sequences of rows, which we'll - // then find matches in - std::vector a, b; - - a.reserve(rows.size()); - for (auto& row : rows) { - a.push_back({row.row_index, row.prev_tv_index}); - } - std::sort(begin(a), end(a), [](auto lft, auto rgt) { - return std::tie(lft.tv_index, lft.row_index) < std::tie(rgt.tv_index, rgt.row_index); - }); - - // Before constructing `b`, first find the first index in `a` which will - // actually differ in `b`, and skip everything else if there aren't any - size_t first_difference = IndexSet::npos; - for (size_t i = 0; i < a.size(); ++i) { - if (a[i].row_index != rows[i].row_index) { - first_difference = i; - break; - } - } - if (first_difference == IndexSet::npos) - return; - - // Note that `b` is sorted by row_index, while `a` is sorted by tv_index - b.reserve(rows.size()); - for (size_t i = 0; i < rows.size(); ++i) - b.push_back({rows[i].row_index, i}); - std::sort(begin(b), end(b), [](auto lft, auto rgt) { - return std::tie(lft.row_index, lft.tv_index) < std::tie(rgt.row_index, rgt.tv_index); - }); - - // Calculate the LCS of the two sequences - auto matches = LongestCommonSubsequenceCalculator(a, b, first_difference, - changeset.modifications).m_longest_matches; - - // And then insert and delete rows as needed to align them - size_t i = first_difference, j = first_difference; - for (auto match : matches) { - for (; i < match.i; ++i) - changeset.deletions.add(a[i].tv_index); - for (; j < match.j; ++j) - changeset.insertions.add(rows[j].tv_index); - i += match.size; - j += match.size; - } -} - -} // Anonymous namespace - -CollectionChangeBuilder CollectionChangeBuilder::calculate(std::vector const& prev_rows, - std::vector const& next_rows, - std::function row_did_change, - util::Optional const& move_candidates) -{ - REALM_ASSERT_DEBUG(!move_candidates || std::is_sorted(begin(next_rows), end(next_rows))); - - CollectionChangeBuilder ret; - - size_t deleted = 0; - std::vector old_rows; - old_rows.reserve(prev_rows.size()); - for (size_t i = 0; i < prev_rows.size(); ++i) { - if (prev_rows[i] == IndexSet::npos) { - ++deleted; - ret.deletions.add(i); - } - else - old_rows.push_back({prev_rows[i], IndexSet::npos, i, i - deleted}); - } - std::sort(begin(old_rows), end(old_rows), [](auto& lft, auto& rgt) { - return lft.row_index < rgt.row_index; - }); - - std::vector new_rows; - new_rows.reserve(next_rows.size()); - for (size_t i = 0; i < next_rows.size(); ++i) { - new_rows.push_back({next_rows[i], IndexSet::npos, i, 0}); - } - std::sort(begin(new_rows), end(new_rows), [](auto& lft, auto& rgt) { - return lft.row_index < rgt.row_index; - }); - - // Don't add rows which were modified to not match the query to `deletions` - // immediately because the unsorted move logic needs to be able to - // distinguish them from rows which were outright deleted - IndexSet removed; - - // Now that our old and new sets of rows are sorted by row index, we can - // iterate over them and either record old+new TV indices for rows present - // in both, or mark them as inserted/deleted if they appear only in one - size_t i = 0, j = 0; - while (i < old_rows.size() && j < new_rows.size()) { - auto old_index = old_rows[i]; - auto new_index = new_rows[j]; - if (old_index.row_index == new_index.row_index) { - new_rows[j].prev_tv_index = old_rows[i].tv_index; - new_rows[j].shifted_tv_index = old_rows[i].shifted_tv_index; - ++i; - ++j; - } - else if (old_index.row_index < new_index.row_index) { - removed.add(old_index.tv_index); - ++i; - } - else { - ret.insertions.add(new_index.tv_index); - ++j; - } - } - - for (; i < old_rows.size(); ++i) - removed.add(old_rows[i].tv_index); - for (; j < new_rows.size(); ++j) - ret.insertions.add(new_rows[j].tv_index); - - // Filter out the new insertions since we don't need them for any of the - // further calculations - new_rows.erase(std::remove_if(begin(new_rows), end(new_rows), - [](auto& row) { return row.prev_tv_index == IndexSet::npos; }), - end(new_rows)); - std::sort(begin(new_rows), end(new_rows), - [](auto& lft, auto& rgt) { return lft.tv_index < rgt.tv_index; }); - - for (auto& row : new_rows) { - if (row_did_change(row.row_index)) { - ret.modifications.add(row.tv_index); - } - } - - if (move_candidates) { - calculate_moves_unsorted(new_rows, removed, *move_candidates, ret); - } - else { - calculate_moves_sorted(new_rows, ret); - } - ret.deletions.add(removed); - ret.verify(); - -#ifdef REALM_DEBUG - { // Verify that applying the calculated change to prev_rows actually produces next_rows - auto rows = prev_rows; - auto it = util::make_reverse_iterator(ret.deletions.end()); - auto end = util::make_reverse_iterator(ret.deletions.begin()); - for (; it != end; ++it) { - rows.erase(rows.begin() + it->first, rows.begin() + it->second); - } - - for (auto i : ret.insertions.as_indexes()) { - rows.insert(rows.begin() + i, next_rows[i]); - } - - REALM_ASSERT(rows == next_rows); - } -#endif - - return ret; -} - -CollectionChangeSet CollectionChangeBuilder::finalize() && -{ - // Calculate which indices in the old collection were modified - auto modifications_in_old = modifications; - modifications_in_old.erase_at(insertions); - modifications_in_old.shift_for_insert_at(deletions); - - // During changeset calculation we allow marking a row as both inserted and - // modified in case changeset merging results in it no longer being an insert, - // but we don't want inserts in the final modification set - modifications.remove(insertions); - - return { - std::move(deletions), - std::move(insertions), - std::move(modifications_in_old), - std::move(modifications), - std::move(moves), - std::move(columns) - }; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp deleted file mode 100644 index 8fa94d3..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/collection_notifier.cpp +++ /dev/null @@ -1,497 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/collection_notifier.hpp" - -#include "impl/realm_coordinator.hpp" -#include "shared_realm.hpp" - -#include -#include - -using namespace realm; -using namespace realm::_impl; - -std::function -CollectionNotifier::get_modification_checker(TransactionChangeInfo const& info, - Table const& root_table) -{ - if (info.schema_changed) - set_table(root_table); - - // First check if any of the tables accessible from the root table were - // actually modified. This can be false if there were only insertions, or - // deletions which were not linked to by any row in the linking table - auto table_modified = [&](auto& tbl) { - return tbl.table_ndx < info.tables.size() - && !info.tables[tbl.table_ndx].modifications.empty(); - }; - if (!any_of(begin(m_related_tables), end(m_related_tables), table_modified)) { - return [](size_t) { return false; }; - } - if (m_related_tables.size() == 1) { - auto& modifications = info.tables[m_related_tables[0].table_ndx].modifications; - return [&](size_t row) { return modifications.contains(row); }; - } - - return DeepChangeChecker(info, root_table, m_related_tables); -} - -void DeepChangeChecker::find_related_tables(std::vector& out, Table const& table) -{ - auto table_ndx = table.get_index_in_group(); - if (table_ndx == npos) - return; - if (any_of(begin(out), end(out), [=](auto& tbl) { return tbl.table_ndx == table_ndx; })) - return; - - // We need to add this table to `out` before recurring so that the check - // above works, but we can't store a pointer to the thing being populated - // because the recursive calls may resize `out`, so instead look it up by - // index every time - size_t out_index = out.size(); - out.push_back({table_ndx, {}}); - - for (size_t i = 0, count = table.get_column_count(); i != count; ++i) { - auto type = table.get_column_type(i); - if (type == type_Link || type == type_LinkList) { - out[out_index].links.push_back({i, type == type_LinkList}); - find_related_tables(out, *table.get_link_target(i)); - } - } -} - -DeepChangeChecker::DeepChangeChecker(TransactionChangeInfo const& info, - Table const& root_table, - std::vector const& related_tables) -: m_info(info) -, m_root_table(root_table) -, m_root_table_ndx(root_table.get_index_in_group()) -, m_root_modifications(m_root_table_ndx < info.tables.size() ? &info.tables[m_root_table_ndx].modifications : nullptr) -, m_related_tables(related_tables) -{ -} - -bool DeepChangeChecker::check_outgoing_links(size_t table_ndx, - Table const& table, - size_t row_ndx, size_t depth) -{ - auto it = find_if(begin(m_related_tables), end(m_related_tables), - [&](auto&& tbl) { return tbl.table_ndx == table_ndx; }); - if (it == m_related_tables.end()) - return false; - - // Check if we're already checking if the destination of the link is - // modified, and if not add it to the stack - auto already_checking = [&](size_t col) { - auto end = m_current_path.begin() + depth; - auto match = std::find_if(m_current_path.begin(), end, [&](auto& p) { - return p.table == table_ndx && p.row == row_ndx && p.col == col; - }); - if (match != end) { - for (; match < end; ++match) match->depth_exceeded = true; - return true; - } - m_current_path[depth] = {table_ndx, row_ndx, col, false}; - return false; - }; - - auto linked_object_changed = [&](OutgoingLink const& link) { - if (already_checking(link.col_ndx)) - return false; - if (!link.is_list) { - if (table.is_null_link(link.col_ndx, row_ndx)) - return false; - auto dst = table.get_link(link.col_ndx, row_ndx); - return check_row(*table.get_link_target(link.col_ndx), dst, depth + 1); - } - - auto& target = *table.get_link_target(link.col_ndx); - auto lvr = table.get_linklist(link.col_ndx, row_ndx); - for (size_t j = 0, size = lvr->size(); j < size; ++j) { - size_t dst = lvr->get(j).get_index(); - if (check_row(target, dst, depth + 1)) - return true; - } - return false; - }; - - return std::any_of(begin(it->links), end(it->links), linked_object_changed); -} - -bool DeepChangeChecker::check_row(Table const& table, size_t idx, size_t depth) -{ - // Arbitrary upper limit on the maximum depth to search - if (depth >= m_current_path.size()) { - // Don't mark any of the intermediate rows checked along the path as - // not modified, as a search starting from them might hit a modification - for (size_t i = 0; i < m_current_path.size(); ++i) - m_current_path[i].depth_exceeded = true; - return false; - } - - size_t table_ndx = table.get_index_in_group(); - if (depth > 0 && table_ndx < m_info.tables.size() && m_info.tables[table_ndx].modifications.contains(idx)) - return true; - - if (m_not_modified.size() <= table_ndx) - m_not_modified.resize(table_ndx + 1); - if (m_not_modified[table_ndx].contains(idx)) - return false; - - bool ret = check_outgoing_links(table_ndx, table, idx, depth); - if (!ret && (depth == 0 || !m_current_path[depth - 1].depth_exceeded)) - m_not_modified[table_ndx].add(idx); - return ret; -} - -bool DeepChangeChecker::operator()(size_t ndx) -{ - if (m_root_modifications && m_root_modifications->contains(ndx)) - return true; - return check_row(m_root_table, ndx, 0); -} - -CollectionNotifier::CollectionNotifier(std::shared_ptr realm) -: m_realm(std::move(realm)) -, m_sg_version(Realm::Internal::get_shared_group(*m_realm)->get_version_of_current_transaction()) -{ -} - -CollectionNotifier::~CollectionNotifier() -{ - // Need to do this explicitly to ensure m_realm is destroyed with the mutex - // held to avoid potential double-deletion - unregister(); -} - -uint64_t CollectionNotifier::add_callback(CollectionChangeCallback callback) -{ - m_realm->verify_thread(); - - std::lock_guard lock(m_callback_mutex); - auto token = m_next_token++; - m_callbacks.push_back({std::move(callback), {}, {}, token, false, false}); - if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications - Realm::Internal::get_coordinator(*m_realm).wake_up_notifier_worker(); - m_have_callbacks = true; - } - return token; -} - -void CollectionNotifier::remove_callback(uint64_t token) -{ - // the callback needs to be destroyed after releasing the lock as destroying - // it could cause user code to be called - Callback old; - { - std::lock_guard lock(m_callback_mutex); - auto it = find_callback(token); - if (it == end(m_callbacks)) { - return; - } - - size_t idx = distance(begin(m_callbacks), it); - if (m_callback_index != npos) { - if (m_callback_index >= idx) - --m_callback_index; - } - --m_callback_count; - - old = std::move(*it); - m_callbacks.erase(it); - - m_have_callbacks = !m_callbacks.empty(); - } -} - -void CollectionNotifier::suppress_next_notification(uint64_t token) -{ - { - std::lock_guard lock(m_realm_mutex); - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - m_realm->verify_in_write(); - } - - std::lock_guard lock(m_callback_mutex); - auto it = find_callback(token); - if (it != end(m_callbacks)) { - it->skip_next = true; - } -} - -std::vector::iterator CollectionNotifier::find_callback(uint64_t token) -{ - REALM_ASSERT(m_error || m_callbacks.size() > 0); - - auto it = find_if(begin(m_callbacks), end(m_callbacks), - [=](const auto& c) { return c.token == token; }); - // We should only fail to find the callback if it was removed due to an error - REALM_ASSERT(m_error || it != end(m_callbacks)); - return it; -} - -void CollectionNotifier::unregister() noexcept -{ - std::lock_guard lock(m_realm_mutex); - m_realm = nullptr; -} - -bool CollectionNotifier::is_alive() const noexcept -{ - std::lock_guard lock(m_realm_mutex); - return m_realm != nullptr; -} - -std::unique_lock CollectionNotifier::lock_target() -{ - return std::unique_lock{m_realm_mutex}; -} - -void CollectionNotifier::set_table(Table const& table) -{ - m_related_tables.clear(); - DeepChangeChecker::find_related_tables(m_related_tables, table); -} - -void CollectionNotifier::add_required_change_info(TransactionChangeInfo& info) -{ - if (!do_add_required_change_info(info) || m_related_tables.empty()) { - return; - } - - auto max = max_element(begin(m_related_tables), end(m_related_tables), - [](auto&& a, auto&& b) { return a.table_ndx < b.table_ndx; }); - - if (max->table_ndx >= info.table_modifications_needed.size()) - info.table_modifications_needed.resize(max->table_ndx + 1, false); - for (auto& tbl : m_related_tables) { - info.table_modifications_needed[tbl.table_ndx] = true; - } -} - -void CollectionNotifier::prepare_handover() -{ - REALM_ASSERT(m_sg); - m_sg_version = m_sg->get_version_of_current_transaction(); - do_prepare_handover(*m_sg); - m_has_run = true; - -#ifdef REALM_DEBUG - std::lock_guard lock(m_callback_mutex); - for (auto& callback : m_callbacks) - REALM_ASSERT(!callback.skip_next); -#endif -} - -void CollectionNotifier::before_advance() -{ - for_each_callback([&](auto& lock, auto& callback) { - if (callback.changes_to_deliver.empty()) { - return; - } - - auto changes = callback.changes_to_deliver; - // acquire a local reference to the callback so that removing the - // callback from within it can't result in a dangling pointer - auto cb = callback.fn; - lock.unlock(); - cb.before(changes); - }); -} - -void CollectionNotifier::after_advance() -{ - for_each_callback([&](auto& lock, auto& callback) { - if (callback.initial_delivered && callback.changes_to_deliver.empty()) { - return; - } - callback.initial_delivered = true; - - auto changes = std::move(callback.changes_to_deliver); - // acquire a local reference to the callback so that removing the - // callback from within it can't result in a dangling pointer - auto cb = callback.fn; - lock.unlock(); - cb.after(changes); - }); -} - -void CollectionNotifier::deliver_error(std::exception_ptr error) -{ - // Don't complain about double-unregistering callbacks - m_error = true; - - m_callback_count = m_callbacks.size(); - for_each_callback([this, &error](auto& lock, auto& callback) { - // acquire a local reference to the callback so that removing the - // callback from within it can't result in a dangling pointer - auto cb = std::move(callback.fn); - auto token = callback.token; - lock.unlock(); - cb.error(error); - - // We never want to call the callback again after this, so just remove it - this->remove_callback(token); - }); -} - -bool CollectionNotifier::is_for_realm(Realm& realm) const noexcept -{ - std::lock_guard lock(m_realm_mutex); - return m_realm.get() == &realm; -} - -bool CollectionNotifier::package_for_delivery() -{ - if (!prepare_to_deliver()) - return false; - std::lock_guard l(m_callback_mutex); - for (auto& callback : m_callbacks) - callback.changes_to_deliver = std::move(callback.accumulated_changes).finalize(); - m_callback_count = m_callbacks.size(); - return true; -} - -template -void CollectionNotifier::for_each_callback(Fn&& fn) -{ - std::unique_lock callback_lock(m_callback_mutex); - REALM_ASSERT_DEBUG(m_callback_count <= m_callbacks.size()); - for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) { - fn(callback_lock, m_callbacks[m_callback_index]); - if (!callback_lock.owns_lock()) - callback_lock.lock(); - } - - m_callback_index = npos; -} - -void CollectionNotifier::attach_to(SharedGroup& sg) -{ - REALM_ASSERT(!m_sg); - - m_sg = &sg; - do_attach_to(sg); -} - -void CollectionNotifier::detach() -{ - REALM_ASSERT(m_sg); - do_detach_from(*m_sg); - m_sg = nullptr; -} - -SharedGroup& CollectionNotifier::source_shared_group() -{ - return *Realm::Internal::get_shared_group(*m_realm); -} - -void CollectionNotifier::add_changes(CollectionChangeBuilder change) -{ - std::lock_guard lock(m_callback_mutex); - for (auto& callback : m_callbacks) { - if (callback.skip_next) { - REALM_ASSERT_DEBUG(callback.accumulated_changes.empty()); - callback.skip_next = false; - } - else { - if (&callback == &m_callbacks.back()) - callback.accumulated_changes.merge(std::move(change)); - else - callback.accumulated_changes.merge(CollectionChangeBuilder(change)); - } - } -} - -NotifierPackage::NotifierPackage(std::exception_ptr error, - std::vector> notifiers, - RealmCoordinator* coordinator) -: m_notifiers(std::move(notifiers)) -, m_coordinator(coordinator) -, m_error(std::move(error)) -{ -} - -void NotifierPackage::package_and_wait(util::Optional target_version) -{ - if (!m_coordinator || m_error || !*this) - return; - - auto lock = m_coordinator->wait_for_notifiers([&] { - if (!target_version) - return true; - return std::all_of(begin(m_notifiers), end(m_notifiers), [&](auto const& n) { - return !n->have_callbacks() || (n->has_run() && n->version().version >= *target_version); - }); - }); - - // Package the notifiers for delivery and remove any which don't have anything to deliver - auto package = [&](auto& notifier) { - if (notifier->has_run() && notifier->package_for_delivery()) { - m_version = notifier->version(); - return false; - } - return true; - }; - m_notifiers.erase(std::remove_if(begin(m_notifiers), end(m_notifiers), package), end(m_notifiers)); - if (m_version && target_version && m_version->version < *target_version) { - m_notifiers.clear(); - m_version = util::none; - } - REALM_ASSERT(m_version || m_notifiers.empty()); - - m_coordinator = nullptr; -} - -void NotifierPackage::before_advance() -{ - if (m_error) - return; - for (auto& notifier : m_notifiers) - notifier->before_advance(); -} - -void NotifierPackage::deliver(SharedGroup& sg) -{ - if (m_error) { - for (auto& notifier : m_notifiers) - notifier->deliver_error(m_error); - return; - } - // Can't deliver while in a write transaction - if (sg.get_transact_stage() != SharedGroup::transact_Reading) - return; - for (auto& notifier : m_notifiers) - notifier->deliver(sg); -} - -void NotifierPackage::after_advance() -{ - if (m_error) - return; - for (auto& notifier : m_notifiers) - notifier->after_advance(); -} - -void NotifierPackage::add_notifier(std::shared_ptr notifier) -{ - m_notifiers.push_back(notifier); - m_coordinator->register_notifier(notifier); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp deleted file mode 100644 index a2b459c..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/list_notifier.cpp +++ /dev/null @@ -1,109 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/list_notifier.hpp" - -#include "shared_realm.hpp" - -#include - -using namespace realm; -using namespace realm::_impl; - -ListNotifier::ListNotifier(LinkViewRef lv, std::shared_ptr realm) -: CollectionNotifier(std::move(realm)) -, m_prev_size(lv->size()) -{ - set_table(lv->get_target_table()); - m_lv_handover = source_shared_group().export_linkview_for_handover(lv); -} - -void ListNotifier::release_data() noexcept -{ - m_lv.reset(); -} - -void ListNotifier::do_attach_to(SharedGroup& sg) -{ - REALM_ASSERT(m_lv_handover); - REALM_ASSERT(!m_lv); - m_lv = sg.import_linkview_from_handover(std::move(m_lv_handover)); -} - -void ListNotifier::do_detach_from(SharedGroup& sg) -{ - REALM_ASSERT(!m_lv_handover); - if (m_lv) { - m_lv_handover = sg.export_linkview_for_handover(m_lv); - m_lv = {}; - } -} - -bool ListNotifier::do_add_required_change_info(TransactionChangeInfo& info) -{ - REALM_ASSERT(!m_lv_handover); - if (!m_lv || !m_lv->is_attached()) { - return false; // origin row was deleted after the notification was added - } - - auto& table = m_lv->get_origin_table(); - size_t row_ndx = m_lv->get_origin_row_index(); - size_t col_ndx = find_container_column(table, row_ndx, m_lv, type_LinkList, &Table::get_linklist); - info.lists.push_back({table.get_index_in_group(), row_ndx, col_ndx, &m_change}); - - m_info = &info; - return true; -} - -void ListNotifier::run() -{ - if (!m_lv || !m_lv->is_attached()) { - // LV was deleted, so report all of the rows being removed if this is - // the first run after that - if (m_prev_size) { - m_change.deletions.set(m_prev_size); - m_prev_size = 0; - } - else { - m_change = {}; - } - return; - } - - auto row_did_change = get_modification_checker(*m_info, m_lv->get_target_table()); - for (size_t i = 0; i < m_lv->size(); ++i) { - if (m_change.modifications.contains(i)) - continue; - if (row_did_change(m_lv->get(i).get_index())) - m_change.modifications.add(i); - } - - for (auto const& move : m_change.moves) { - if (m_change.modifications.contains(move.to)) - continue; - if (row_did_change(m_lv->get(move.to).get_index())) - m_change.modifications.add(move.to); - } - - m_prev_size = m_lv->size(); -} - -void ListNotifier::do_prepare_handover(SharedGroup&) -{ - add_changes(std::move(m_change)); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp deleted file mode 100644 index cb31065..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/object_notifier.cpp +++ /dev/null @@ -1,97 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/object_notifier.hpp" - -#include "shared_realm.hpp" - -using namespace realm; -using namespace realm::_impl; - -ObjectNotifier::ObjectNotifier(Row const& row, std::shared_ptr realm) -: CollectionNotifier(std::move(realm)) -{ - REALM_ASSERT(row.get_table()); - set_table(*row.get_table()); - - m_handover = source_shared_group().export_for_handover(row); -} - -void ObjectNotifier::release_data() noexcept -{ - m_row = nullptr; -} - -void ObjectNotifier::do_attach_to(SharedGroup& sg) -{ - REALM_ASSERT(m_handover); - REALM_ASSERT(!m_row); - m_row = sg.import_from_handover(std::move(m_handover)); -} - -void ObjectNotifier::do_detach_from(SharedGroup& sg) -{ - REALM_ASSERT(!m_handover); - if (m_row) { - m_handover = sg.export_for_handover(*m_row); - m_row = nullptr; - } -} - -bool ObjectNotifier::do_add_required_change_info(TransactionChangeInfo& info) -{ - REALM_ASSERT(!m_handover); - m_info = &info; - if (m_row && m_row->is_attached()) { - size_t table_ndx = m_row->get_table()->get_index_in_group(); - if (table_ndx >= info.table_modifications_needed.size()) - info.table_modifications_needed.resize(table_ndx + 1); - info.table_modifications_needed[table_ndx] = true; - } - return false; -} - -void ObjectNotifier::run() -{ - if (!m_row) - return; - if (!m_row->is_attached()) { - m_change.deletions.add(0); - m_row = nullptr; - return; - } - - size_t table_ndx = m_row->get_table()->get_index_in_group(); - if (table_ndx >= m_info->tables.size()) - return; - auto& change = m_info->tables[table_ndx]; - if (!change.modifications.contains(m_row->get_index())) - return; - m_change.modifications.add(0); - m_change.columns.reserve(change.columns.size()); - for (auto& col : change.columns) { - m_change.columns.emplace_back(); - if (col.contains(m_row->get_index())) - m_change.columns.back().add(0); - } -} - -void ObjectNotifier::do_prepare_handover(SharedGroup&) -{ - add_changes(std::move(m_change)); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp deleted file mode 100644 index 111807f..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/primitive_list_notifier.cpp +++ /dev/null @@ -1,100 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/primitive_list_notifier.hpp" - -#include "shared_realm.hpp" - -#include - -using namespace realm; -using namespace realm::_impl; - -PrimitiveListNotifier::PrimitiveListNotifier(TableRef table, std::shared_ptr realm) -: CollectionNotifier(std::move(realm)) -, m_prev_size(table->size()) -{ - set_table(*table->get_parent_table()); - m_table_handover = source_shared_group().export_table_for_handover(table); -} - -void PrimitiveListNotifier::release_data() noexcept -{ - m_table.reset(); -} - -void PrimitiveListNotifier::do_attach_to(SharedGroup& sg) -{ - REALM_ASSERT(!m_table); - if (m_table_handover) - m_table = sg.import_table_from_handover(std::move(m_table_handover)); -} - -void PrimitiveListNotifier::do_detach_from(SharedGroup& sg) -{ - REALM_ASSERT(!m_table_handover); - if (m_table) { - if (m_table->is_attached()) - m_table_handover = sg.export_table_for_handover(m_table); - m_table = {}; - } -} - -bool PrimitiveListNotifier::do_add_required_change_info(TransactionChangeInfo& info) -{ - REALM_ASSERT(!m_table_handover); - if (!m_table || !m_table->is_attached()) { - return false; // origin row was deleted after the notification was added - } - - auto& table = *m_table->get_parent_table(); - size_t row_ndx = m_table->get_parent_row_index(); - size_t col_ndx = find_container_column(table, row_ndx, m_table, type_Table, &Table::get_subtable); - info.lists.push_back({table.get_index_in_group(), row_ndx, col_ndx, &m_change}); - - m_info = &info; - return true; -} - -void PrimitiveListNotifier::run() -{ - if (!m_table || !m_table->is_attached()) { - // Table was deleted entirely, so report all of the rows being removed - // if this is the first run after that - if (m_prev_size) { - m_change.deletions.set(m_prev_size); - m_prev_size = 0; - } - else { - m_change = {}; - } - return; - } - - if (!m_change.deletions.empty() && m_change.deletions.begin()->second == std::numeric_limits::max()) { - // Table was cleared, so set the deletions to the actual previous size - m_change.deletions.set(m_prev_size); - } - - m_prev_size = m_table->size(); -} - -void PrimitiveListNotifier::do_prepare_handover(SharedGroup&) -{ - add_changes(std::move(m_change)); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp deleted file mode 100644 index 05f8baf..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/realm_coordinator.cpp +++ /dev/null @@ -1,1037 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/realm_coordinator.hpp" - -#include "impl/collection_notifier.hpp" -#include "impl/external_commit_helper.hpp" -#include "impl/transact_log_handler.hpp" -#include "impl/weak_realm_notifier.hpp" -#include "binding_context.hpp" -#include "object_schema.hpp" -#include "object_store.hpp" -#include "property.hpp" -#include "schema.hpp" -#include "thread_safe_reference.hpp" - -#if REALM_ENABLE_SYNC -#include "sync/impl/work_queue.hpp" -#include "sync/async_open_task.hpp" -#include "sync/partial_sync.hpp" -#include "sync/sync_config.hpp" -#include "sync/sync_manager.hpp" -#include "sync/sync_session.hpp" -#endif - -#include -#include -#include - -#include -#include - -using namespace realm; -using namespace realm::_impl; - -static auto& s_coordinator_mutex = *new std::mutex; -static auto& s_coordinators_per_path = *new std::unordered_map>; - -std::shared_ptr RealmCoordinator::get_coordinator(StringData path) -{ - std::lock_guard lock(s_coordinator_mutex); - - auto& weak_coordinator = s_coordinators_per_path[path]; - if (auto coordinator = weak_coordinator.lock()) { - return coordinator; - } - - auto coordinator = std::make_shared(); - weak_coordinator = coordinator; - return coordinator; -} - -std::shared_ptr RealmCoordinator::get_coordinator(const Realm::Config& config) -{ - auto coordinator = get_coordinator(config.path); - std::lock_guard lock(coordinator->m_realm_mutex); - coordinator->set_config(config); - return coordinator; -} - -std::shared_ptr RealmCoordinator::get_existing_coordinator(StringData path) -{ - std::lock_guard lock(s_coordinator_mutex); - auto it = s_coordinators_per_path.find(path); - return it == s_coordinators_per_path.end() ? nullptr : it->second.lock(); -} - -void RealmCoordinator::create_sync_session(bool force_client_resync, bool validate_sync_history) -{ -#if REALM_ENABLE_SYNC - if (m_sync_session) - return; - - if (!m_config.encryption_key.empty() && !m_config.sync_config->realm_encryption_key) { - throw std::logic_error("A realm encryption key was specified in Realm::Config but not in SyncConfig"); - } else if (m_config.sync_config->realm_encryption_key && m_config.encryption_key.empty()) { - throw std::logic_error("A realm encryption key was specified in SyncConfig but not in Realm::Config"); - } else if (m_config.sync_config->realm_encryption_key && - !std::equal(m_config.sync_config->realm_encryption_key->begin(), m_config.sync_config->realm_encryption_key->end(), - m_config.encryption_key.begin(), m_config.encryption_key.end())) { - throw std::logic_error("The realm encryption key specified in SyncConfig does not match the one in Realm::Config"); - } - - auto sync_config = *m_config.sync_config; - sync_config.validate_sync_history = validate_sync_history; - m_sync_session = SyncManager::shared().get_session(m_config.path, sync_config, force_client_resync); - - std::weak_ptr weak_self = shared_from_this(); - SyncSession::Internal::set_sync_transact_callback(*m_sync_session, - [weak_self](VersionID old_version, VersionID new_version) { - if (auto self = weak_self.lock()) { - if (self->m_transaction_callback) - self->m_transaction_callback(old_version, new_version); - if (self->m_notifier) - self->m_notifier->notify_others(); - } - }); -#else - static_cast(force_client_resync); - static_cast(validate_sync_history); -#endif -} - -void RealmCoordinator::set_config(const Realm::Config& config) -{ - if (config.encryption_key.data() && config.encryption_key.size() != 64) - throw InvalidEncryptionKeyException(); - if (config.schema_mode == SchemaMode::Immutable && config.sync_config) - throw std::logic_error("Synchronized Realms cannot be opened in immutable mode"); - if (config.schema_mode == SchemaMode::Additive && config.migration_function) - throw std::logic_error("Realms opened in Additive-only schema mode do not use a migration function"); - if (config.schema_mode == SchemaMode::Immutable && config.migration_function) - throw std::logic_error("Realms opened in immutable mode do not use a migration function"); - if (config.schema_mode == SchemaMode::ReadOnlyAlternative && config.migration_function) - throw std::logic_error("Realms opened in read-only mode do not use a migration function"); - if (config.schema_mode == SchemaMode::Immutable && config.initialization_function) - throw std::logic_error("Realms opened in immutable mode do not use an initialization function"); - if (config.schema_mode == SchemaMode::ReadOnlyAlternative && config.initialization_function) - throw std::logic_error("Realms opened in read-only mode do not use an initialization function"); - if (config.schema && config.schema_version == ObjectStore::NotVersioned) - throw std::logic_error("A schema version must be specified when the schema is specified"); - if (!config.realm_data.is_null() && (!config.immutable() || !config.in_memory)) - throw std::logic_error("In-memory realms initialized from memory buffers can only be opened in read-only mode"); - if (!config.realm_data.is_null() && !config.path.empty()) - throw std::logic_error("Specifying both memory buffer and path is invalid"); - if (!config.realm_data.is_null() && !config.encryption_key.empty()) - throw std::logic_error("Memory buffers do not support encryption"); - // ResetFile also won't use the migration function, but specifying one is - // allowed to simplify temporarily switching modes during development - - bool no_existing_realm = std::all_of(begin(m_weak_realm_notifiers), end(m_weak_realm_notifiers), - [](auto& notifier) { return notifier.expired(); }); - if (no_existing_realm) { - m_config = config; - } - else { - if (m_config.immutable() != config.immutable()) { - throw MismatchedConfigException("Realm at path '%1' already opened with different read permissions.", config.path); - } - if (m_config.in_memory != config.in_memory) { - throw MismatchedConfigException("Realm at path '%1' already opened with different inMemory settings.", config.path); - } - if (m_config.encryption_key != config.encryption_key) { - throw MismatchedConfigException("Realm at path '%1' already opened with a different encryption key.", config.path); - } - if (m_config.schema_mode != config.schema_mode) { - throw MismatchedConfigException("Realm at path '%1' already opened with a different schema mode.", config.path); - } - if (config.schema && m_schema_version != ObjectStore::NotVersioned && m_schema_version != config.schema_version) { - throw MismatchedConfigException("Realm at path '%1' already opened with different schema version.", config.path); - } - -#if REALM_ENABLE_SYNC - if (bool(m_config.sync_config) != bool(config.sync_config)) { - throw MismatchedConfigException("Realm at path '%1' already opened with different sync configurations.", config.path); - } - - if (config.sync_config) { - if (m_config.sync_config->user != config.sync_config->user) { - throw MismatchedConfigException("Realm at path '%1' already opened with different sync user.", config.path); - } - if (m_config.sync_config->realm_url() != config.sync_config->realm_url()) { - throw MismatchedConfigException("Realm at path '%1' already opened with different sync server URL.", config.path); - } - if (m_config.sync_config->transformer != config.sync_config->transformer) { - throw MismatchedConfigException("Realm at path '%1' already opened with different transformer.", config.path); - } - if (m_config.sync_config->realm_encryption_key != config.sync_config->realm_encryption_key) { - throw MismatchedConfigException("Realm at path '%1' already opened with sync session encryption key.", config.path); - } - } -#endif - // Mixing cached and uncached Realms is allowed - m_config.cache = config.cache; - - // Realm::update_schema() handles complaining about schema mismatches - } -} - -std::shared_ptr RealmCoordinator::get_cached_realm(Realm::Config const& config, AnyExecutionContextID execution_context) -{ - if (!config.cache) - return nullptr; - for (auto& cached_realm : m_weak_realm_notifiers) { - if (!cached_realm.is_cached_for_execution_context(execution_context)) - continue; - // can be null if we jumped in between ref count hitting zero and - // unregister_realm() getting the lock - if (auto realm = cached_realm.realm()) { - // If the file is uninitialized and was opened without a schema, - // do the normal schema init - if (realm->schema_version() == ObjectStore::NotVersioned) - break; - - // Otherwise if we have a realm schema it needs to be an exact - // match (even having the same properties but in different - // orders isn't good enough) - if (config.schema && realm->schema() != *config.schema) - throw MismatchedConfigException("Realm at path '%1' already opened on current thread with different schema.", config.path); - - return realm; - } - } - return nullptr; -} - -std::shared_ptr RealmCoordinator::get_realm(Realm::Config config) -{ - // realm must be declared before lock so that the mutex is released before - // we release the strong reference to realm, as Realm's destructor may want - // to acquire the same lock - std::shared_ptr realm; - std::unique_lock lock(m_realm_mutex); - set_config(config); - if ((realm = get_cached_realm(config, config.execution_context))) - return realm; - do_get_realm(std::move(config), realm, lock); - return realm; -} - -std::shared_ptr RealmCoordinator::get_realm() -{ - std::shared_ptr realm; - std::unique_lock lock(m_realm_mutex); - if ((realm = get_cached_realm(m_config, m_config.execution_context))) - return realm; - do_get_realm(m_config, realm, lock); - return realm; -} - -ThreadSafeReference RealmCoordinator::get_unbound_realm() -{ - ThreadSafeReference ref; - std::unique_lock lock(m_realm_mutex); - do_get_realm(m_config, ref.m_realm, lock, false); - return ref; -} - -void RealmCoordinator::do_get_realm(Realm::Config config, std::shared_ptr& realm, - std::unique_lock& realm_lock, bool bind_to_context) -{ - auto schema = std::move(config.schema); - auto migration_function = std::move(config.migration_function); - auto initialization_function = std::move(config.initialization_function); - auto audit_factory = std::move(config.audit_factory); - config.schema = {}; - - bool should_initialize_notifier = !config.immutable() && config.automatic_change_notifications; - realm = Realm::make_shared_realm(std::move(config), shared_from_this()); - if (!m_notifier && should_initialize_notifier) { - try { - m_notifier = std::make_unique(*this); - } - catch (std::system_error const& ex) { - throw RealmFileException(RealmFileException::Kind::AccessError, get_path(), ex.code().message(), ""); - } - } - m_weak_realm_notifiers.emplace_back(realm, realm->config().cache, bind_to_context); - - if (realm->config().sync_config) - create_sync_session(false, false); - - if (!m_audit_context && audit_factory) - m_audit_context = audit_factory(); - - realm_lock.unlock(); - if (schema) { -#if REALM_ENABLE_SYNC && REALM_PLATFORM_JAVA - // Workaround for https://github.com/realm/realm-java/issues/6619 - // Between Realm Java 5.10.0 and 5.13.0 created_at/updated_at was optional - // when created from Java, even though the Object Store code specified them as - // required. Due to how the Realm was initialized, this wasn't a problem before - // 5.13.0, but after that the Object Store initializer code was changed causing - // problems when Java clients upgraded. In order to prevent older clients from - // breaking with a schema mismatch when upgrading we thus fix the schema in transit. - // This means that schema reported back from Realm will be different than the one - // specified in the Java model class, but this seemed like the approach with the - // least amount of disadvantages. - if (realm->is_partial()) { - auto& new_schema = schema.value(); - auto current_schema = realm->schema(); - auto current_resultsets_schema_obj = current_schema.find("__ResultSets"); - if (current_resultsets_schema_obj != current_schema.end()) { - Property* p = current_resultsets_schema_obj->property_for_public_name("created_at"); - if (is_nullable(p->type)) { - auto it = new_schema.find("__ResultSets"); - if (it != new_schema.end()) { - auto created_at_property = it->property_for_public_name("created_at"); - auto updated_at_property = it->property_for_public_name("updated_at"); - if (created_at_property && updated_at_property) { - created_at_property->type = created_at_property->type | PropertyType::Nullable; - updated_at_property->type = updated_at_property->type | PropertyType::Nullable; - } - } - } - } - } -#endif - realm->update_schema(std::move(*schema), config.schema_version, std::move(migration_function), - std::move(initialization_function)); - } -#if REALM_ENABLE_SYNC - else if (realm->is_partial()) - _impl::ensure_partial_sync_schema_initialized(*realm); -#endif -} - -void RealmCoordinator::bind_to_context(Realm& realm, AnyExecutionContextID execution_context) -{ - std::unique_lock lock(m_realm_mutex); - for (auto& cached_realm : m_weak_realm_notifiers) { - if (!cached_realm.is_for_realm(&realm)) - continue; - cached_realm.bind_to_execution_context(execution_context); - return; - } - REALM_TERMINATE("Invalid Realm passed to bind_to_context()"); -} - -#if REALM_ENABLE_SYNC -std::shared_ptr RealmCoordinator::get_synchronized_realm(Realm::Config config) -{ - if (!config.sync_config) - throw std::logic_error("This method is only available for fully synchronized Realms."); - - std::unique_lock lock(m_realm_mutex); - set_config(config); - bool exists = File::exists(m_config.path); - create_sync_session(!config.sync_config->is_partial && !exists, exists); - return std::make_shared(shared_from_this(), m_sync_session); -} - -void RealmCoordinator::create_session(const Realm::Config& config) -{ - REALM_ASSERT(config.sync_config); - std::unique_lock lock(m_realm_mutex); - set_config(config); - bool exists = File::exists(m_config.path); - create_sync_session(!config.sync_config->is_partial && !exists, exists); -} -#endif - -bool RealmCoordinator::get_cached_schema(Schema& schema, uint64_t& schema_version, - uint64_t& transaction) const noexcept -{ - std::lock_guard lock(m_schema_cache_mutex); - if (!m_cached_schema) - return false; - schema = *m_cached_schema; - schema_version = m_schema_version; - transaction = m_schema_transaction_version_max; - return true; -} - -void RealmCoordinator::cache_schema(Schema const& new_schema, uint64_t new_schema_version, - uint64_t transaction_version) -{ - std::lock_guard lock(m_schema_cache_mutex); - if (transaction_version < m_schema_transaction_version_max) - return; - if (new_schema.empty() || new_schema_version == ObjectStore::NotVersioned) - return; - - m_cached_schema = new_schema; - m_schema_version = new_schema_version; - m_schema_transaction_version_min = transaction_version; - m_schema_transaction_version_max = transaction_version; -} - -void RealmCoordinator::clear_schema_cache_and_set_schema_version(uint64_t new_schema_version) -{ - std::lock_guard lock(m_schema_cache_mutex); - m_cached_schema = util::none; - m_schema_version = new_schema_version; -} - -void RealmCoordinator::advance_schema_cache(uint64_t previous, uint64_t next) -{ - std::lock_guard lock(m_schema_cache_mutex); - if (!m_cached_schema) - return; - REALM_ASSERT(previous <= m_schema_transaction_version_max); - if (next < m_schema_transaction_version_min) - return; - m_schema_transaction_version_min = std::min(previous, m_schema_transaction_version_min); - m_schema_transaction_version_max = std::max(next, m_schema_transaction_version_max); -} - -RealmCoordinator::RealmCoordinator() -#if REALM_ENABLE_SYNC -: m_partial_sync_work_queue(std::make_unique<_impl::partial_sync::WorkQueue>()) -#endif -{ -} - -RealmCoordinator::~RealmCoordinator() -{ - std::lock_guard coordinator_lock(s_coordinator_mutex); - for (auto it = s_coordinators_per_path.begin(); it != s_coordinators_per_path.end(); ) { - if (it->second.expired()) { - it = s_coordinators_per_path.erase(it); - } - else { - ++it; - } - } -} - -void RealmCoordinator::unregister_realm(Realm* realm) -{ - // Normally results notifiers are cleaned up by the background worker thread - // but if that's disabled we need to ensure that any notifiers from this - // Realm get cleaned up - if (!m_config.automatic_change_notifications) { - std::unique_lock lock(m_notifier_mutex); - clean_up_dead_notifiers(); - } - { - std::lock_guard lock(m_realm_mutex); - auto new_end = remove_if(begin(m_weak_realm_notifiers), end(m_weak_realm_notifiers), - [=](auto& notifier) { return notifier.expired() || notifier.is_for_realm(realm); }); - m_weak_realm_notifiers.erase(new_end, end(m_weak_realm_notifiers)); - } -} - -void RealmCoordinator::clear_cache() -{ - std::vector realms_to_close; - { - std::lock_guard lock(s_coordinator_mutex); - - for (auto& weak_coordinator : s_coordinators_per_path) { - auto coordinator = weak_coordinator.second.lock(); - if (!coordinator) { - continue; - } - - coordinator->m_notifier = nullptr; - - // Gather a list of all of the realms which will be removed - for (auto& weak_realm_notifier : coordinator->m_weak_realm_notifiers) { - if (auto realm = weak_realm_notifier.realm()) { - realms_to_close.push_back(realm); - } - } - } - - s_coordinators_per_path.clear(); - } - - // Close all of the previously cached Realms. This can't be done while - // s_coordinator_mutex is held as it may try to re-lock it. - for (auto& weak_realm : realms_to_close) { - if (auto realm = weak_realm.lock()) { - realm->close(); - } - } -} - -void RealmCoordinator::clear_all_caches() -{ - std::vector> to_clear; - { - std::lock_guard lock(s_coordinator_mutex); - for (auto iter : s_coordinators_per_path) { - to_clear.push_back(iter.second); - } - } - for (auto weak_coordinator : to_clear) { - if (auto coordinator = weak_coordinator.lock()) { - coordinator->clear_cache(); - } - } -} - -void RealmCoordinator::assert_no_open_realms() noexcept -{ -#ifdef REALM_DEBUG - std::lock_guard lock(s_coordinator_mutex); - REALM_ASSERT(s_coordinators_per_path.empty()); -#endif -} - -void RealmCoordinator::wake_up_notifier_worker() -{ - if (m_notifier) { - // FIXME: this wakes up the notification workers for all processes and - // not just us. This might be worth optimizing in the future. - m_notifier->notify_others(); - } -} - -void RealmCoordinator::commit_write(Realm& realm) -{ - REALM_ASSERT(!m_config.immutable()); - REALM_ASSERT(realm.is_in_transaction()); - - { - // Need to acquire this lock before committing or another process could - // perform a write and notify us before we get the chance to set the - // skip version - std::lock_guard l(m_notifier_mutex); - - transaction::commit(*Realm::Internal::get_shared_group(realm)); - - // Don't need to check m_new_notifiers because those don't skip versions - bool have_notifiers = std::any_of(m_notifiers.begin(), m_notifiers.end(), - [&](auto&& notifier) { return notifier->is_for_realm(realm); }); - if (have_notifiers) { - m_notifier_skip_version = Realm::Internal::get_shared_group(realm)->get_version_of_current_transaction(); - } - } - -#if REALM_ENABLE_SYNC - // Realm could be closed in did_change. So send sync notification first before did_change. - if (m_sync_session) { - auto& sg = Realm::Internal::get_shared_group(realm); - auto version = LangBindHelper::get_version_of_latest_snapshot(*sg); - SyncSession::Internal::nonsync_transact_notify(*m_sync_session, version); - } -#endif - if (realm.m_binding_context) { - realm.m_binding_context->did_change({}, {}); - } - - if (m_notifier) { - m_notifier->notify_others(); - } -} - -void RealmCoordinator::pin_version(VersionID versionid) -{ - REALM_ASSERT_DEBUG(!m_notifier_mutex.try_lock()); - if (m_async_error) { - return; - } - - if (!m_advancer_sg) { - try { - std::unique_ptr read_only_group; - Realm::open_with_config(m_config, m_advancer_history, m_advancer_sg, read_only_group, nullptr); - REALM_ASSERT(!read_only_group); - m_advancer_sg->begin_read(versionid); - } - catch (...) { - m_async_error = std::current_exception(); - m_advancer_sg = nullptr; - m_advancer_history = nullptr; - } - } - else if (m_new_notifiers.empty()) { - // If this is the first notifier then we don't already have a read transaction - REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Ready); - m_advancer_sg->begin_read(versionid); - } - else { - REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); - if (versionid < m_advancer_sg->get_version_of_current_transaction()) { - // Ensure we're holding a readlock on the oldest version we have a - // handover object for, as handover objects don't - m_advancer_sg->end_read(); - m_advancer_sg->begin_read(versionid); - } - } -} - -void RealmCoordinator::register_notifier(std::shared_ptr notifier) -{ - auto version = notifier->version(); - auto& self = Realm::Internal::get_coordinator(*notifier->get_realm()); - { - std::lock_guard lock(self.m_notifier_mutex); - self.pin_version(version); - self.m_new_notifiers.push_back(std::move(notifier)); - } -} - -void RealmCoordinator::clean_up_dead_notifiers() -{ - auto swap_remove = [&](auto& container) { - bool did_remove = false; - for (size_t i = 0; i < container.size(); ++i) { - if (container[i]->is_alive()) - continue; - - // Ensure the notifier is destroyed here even if there's lingering refs - // to the async notifier elsewhere - container[i]->release_data(); - - if (container.size() > i + 1) - container[i] = std::move(container.back()); - container.pop_back(); - --i; - did_remove = true; - } - return did_remove; - }; - - if (swap_remove(m_notifiers)) { - // Make sure we aren't holding on to read versions needlessly if there - // are no notifiers left, but don't close them entirely as opening shared - // groups is expensive - if (m_notifiers.empty() && m_notifier_sg) { - REALM_ASSERT_3(m_notifier_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); - m_notifier_sg->end_read(); - m_notifier_skip_version = {0, 0}; - } - } - if (swap_remove(m_new_notifiers) && m_advancer_sg) { - REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); - if (m_new_notifiers.empty()) { - m_advancer_sg->end_read(); - } - } -} - -void RealmCoordinator::on_change() -{ - run_async_notifiers(); - - std::lock_guard lock(m_realm_mutex); - for (auto& realm : m_weak_realm_notifiers) { - realm.notify(); - } -} - -namespace { -class IncrementalChangeInfo { -public: - IncrementalChangeInfo(SharedGroup& sg, - std::vector>& notifiers) - : m_sg(sg) - { - if (notifiers.empty()) - return; - - auto cmp = [&](auto&& lft, auto&& rgt) { - return lft->version() < rgt->version(); - }; - - // Sort the notifiers by their source version so that we can pull them - // all forward to the latest version in a single pass over the transaction log - std::sort(notifiers.begin(), notifiers.end(), cmp); - - // Preallocate the required amount of space in the vector so that we can - // safely give out pointers to within the vector - size_t count = 1; - for (auto it = notifiers.begin(), next = it + 1; next != notifiers.end(); ++it, ++next) { - if (cmp(*it, *next)) - ++count; - } - m_info.reserve(count); - m_info.resize(1); - m_current = &m_info[0]; - } - - TransactionChangeInfo& current() const { return *m_current; } - - bool advance_incremental(VersionID version) - { - if (version != m_sg.get_version_of_current_transaction()) { - transaction::advance(m_sg, *m_current, version); - m_info.push_back({ - m_current->table_modifications_needed, - m_current->table_moves_needed, - std::move(m_current->lists)}); - m_current = &m_info.back(); - return true; - } - return false; - } - - void advance_to_final(VersionID version) - { - if (!m_current) { - transaction::advance(m_sg, nullptr, version); - return; - } - - transaction::advance(m_sg, *m_current, version); - - // We now need to combine the transaction change info objects so that all of - // the notifiers see the complete set of changes from their first version to - // the most recent one - for (size_t i = m_info.size() - 1; i > 0; --i) { - auto& cur = m_info[i]; - if (cur.tables.empty()) - continue; - auto& prev = m_info[i - 1]; - if (prev.tables.empty()) { - prev.tables = cur.tables; - continue; - } - - for (size_t j = 0; j < prev.tables.size() && j < cur.tables.size(); ++j) { - prev.tables[j].merge(CollectionChangeBuilder{cur.tables[j]}); - } - prev.tables.reserve(cur.tables.size()); - while (prev.tables.size() < cur.tables.size()) { - prev.tables.push_back(cur.tables[prev.tables.size()]); - } - } - - // Copy the list change info if there are multiple LinkViews for the same LinkList - auto id = [](auto const& list) { return std::tie(list.table_ndx, list.col_ndx, list.row_ndx); }; - for (size_t i = 1; i < m_current->lists.size(); ++i) { - for (size_t j = i; j > 0; --j) { - if (id(m_current->lists[i]) == id(m_current->lists[j - 1])) { - m_current->lists[j - 1].changes->merge(CollectionChangeBuilder{*m_current->lists[i].changes}); - } - } - } - } - -private: - std::vector m_info; - TransactionChangeInfo* m_current = nullptr; - SharedGroup& m_sg; -}; -} // anonymous namespace - -void RealmCoordinator::run_async_notifiers() -{ - std::unique_lock lock(m_notifier_mutex); - - clean_up_dead_notifiers(); - - if (m_notifiers.empty() && m_new_notifiers.empty()) { - m_notifier_cv.notify_all(); - return; - } - - if (!m_async_error) { - open_helper_shared_group(); - } - - if (m_async_error) { - std::move(m_new_notifiers.begin(), m_new_notifiers.end(), std::back_inserter(m_notifiers)); - m_new_notifiers.clear(); - m_notifier_cv.notify_all(); - return; - } - - VersionID version; - - // Advance all of the new notifiers to the most recent version, if any - auto new_notifiers = std::move(m_new_notifiers); - IncrementalChangeInfo new_notifier_change_info(*m_advancer_sg, new_notifiers); - - if (!new_notifiers.empty()) { - REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Reading); - REALM_ASSERT_3(m_advancer_sg->get_version_of_current_transaction().version, - <=, new_notifiers.front()->version().version); - - // The advancer SG can be at an older version than the oldest new notifier - // if a notifier was added and then removed before it ever got the chance - // to run, as we don't move the pin forward when removing dead notifiers - transaction::advance(*m_advancer_sg, nullptr, new_notifiers.front()->version()); - - // Advance each of the new notifiers to the latest version, attaching them - // to the SG at their handover version. This requires a unique - // TransactionChangeInfo for each source version, so that things don't - // see changes from before the version they were handed over from. - // Each Info has all of the changes between that source version and the - // next source version, and they'll be merged together later after - // releasing the lock - for (auto& notifier : new_notifiers) { - new_notifier_change_info.advance_incremental(notifier->version()); - notifier->attach_to(*m_advancer_sg); - notifier->add_required_change_info(new_notifier_change_info.current()); - } - new_notifier_change_info.advance_to_final(VersionID{}); - - for (auto& notifier : new_notifiers) { - notifier->detach(); - } - - // We want to advance the non-new notifiers to the same version as the - // new notifiers to avoid having to merge changes from any new - // transaction that happen immediately after this into the new notifier - // changes - version = m_advancer_sg->get_version_of_current_transaction(); - m_advancer_sg->end_read(); - } - else { - // If we have no new notifiers we want to just advance to the latest - // version, but we have to pick a "latest" version while holding the - // notifier lock to avoid advancing over a transaction which should be - // skipped - m_advancer_sg->begin_read(); - version = m_advancer_sg->get_version_of_current_transaction(); - m_advancer_sg->end_read(); - } - REALM_ASSERT_3(m_advancer_sg->get_transact_stage(), ==, SharedGroup::transact_Ready); - - auto skip_version = m_notifier_skip_version; - m_notifier_skip_version = {0, 0}; - - // Make a copy of the notifiers vector and then release the lock to avoid - // blocking other threads trying to register or unregister notifiers while we run them - auto notifiers = m_notifiers; - m_notifiers.insert(m_notifiers.end(), new_notifiers.begin(), new_notifiers.end()); - lock.unlock(); - - if (skip_version.version) { - REALM_ASSERT(!notifiers.empty()); - REALM_ASSERT(version >= skip_version); - IncrementalChangeInfo change_info(*m_notifier_sg, notifiers); - for (auto& notifier : notifiers) - notifier->add_required_change_info(change_info.current()); - change_info.advance_to_final(skip_version); - - for (auto& notifier : notifiers) - notifier->run(); - - lock.lock(); - for (auto& notifier : notifiers) - notifier->prepare_handover(); - lock.unlock(); - } - - // Advance the non-new notifiers to the same version as we advanced the new - // ones to (or the latest if there were no new ones) - IncrementalChangeInfo change_info(*m_notifier_sg, notifiers); - for (auto& notifier : notifiers) { - notifier->add_required_change_info(change_info.current()); - } - change_info.advance_to_final(version); - - // Attach the new notifiers to the main SG and move them to the main list - for (auto& notifier : new_notifiers) { - notifier->attach_to(*m_notifier_sg); - notifier->run(); - } - - // Change info is now all ready, so the notifiers can now perform their - // background work - for (auto& notifier : notifiers) { - notifier->run(); - } - - // Reacquire the lock while updating the fields that are actually read on - // other threads - lock.lock(); - for (auto& notifier : new_notifiers) { - notifier->prepare_handover(); - } - for (auto& notifier : notifiers) { - notifier->prepare_handover(); - } - clean_up_dead_notifiers(); - m_notifier_cv.notify_all(); -} - -void RealmCoordinator::open_helper_shared_group() -{ - if (!m_notifier_sg) { - try { - std::unique_ptr read_only_group; - Realm::open_with_config(m_config, m_notifier_history, m_notifier_sg, read_only_group, nullptr); - REALM_ASSERT(!read_only_group); - m_notifier_sg->begin_read(); - } - catch (...) { - // Store the error to be passed to the async notifiers - m_async_error = std::current_exception(); - m_notifier_sg = nullptr; - m_notifier_history = nullptr; - } - } - else if (m_notifiers.empty()) { - m_notifier_sg->begin_read(); - } -} - -void RealmCoordinator::advance_to_ready(Realm& realm) -{ - std::unique_lock lock(m_notifier_mutex); - _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); - lock.unlock(); - notifiers.package_and_wait(util::none); - - auto& sg = Realm::Internal::get_shared_group(realm); - if (notifiers) { - auto version = notifiers.version(); - if (version) { - auto current_version = sg->get_version_of_current_transaction(); - // Notifications are out of date, so just discard - // This should only happen if begin_read() was used to change the - // read version outside of our control - if (*version < current_version) - return; - // While there is a newer version, notifications are for the current - // version so just deliver them without advancing - if (*version == current_version) { - if (realm.m_binding_context) - realm.m_binding_context->will_send_notifications(); - notifiers.deliver(*sg); - notifiers.after_advance(); - if (realm.m_binding_context) - realm.m_binding_context->did_send_notifications(); - return; - } - } - } - - transaction::advance(sg, realm.m_binding_context.get(), notifiers); -} - -std::vector> RealmCoordinator::notifiers_for_realm(Realm& realm) -{ - std::vector> ret; - for (auto& notifier : m_new_notifiers) { - if (notifier->is_for_realm(realm)) - ret.push_back(notifier); - } - for (auto& notifier : m_notifiers) { - if (notifier->is_for_realm(realm)) - ret.push_back(notifier); - } - return ret; -} - -bool RealmCoordinator::advance_to_latest(Realm& realm) -{ - using sgf = SharedGroupFriend; - - auto& sg = Realm::Internal::get_shared_group(realm); - std::unique_lock lock(m_notifier_mutex); - _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); - lock.unlock(); - notifiers.package_and_wait(sgf::get_version_of_latest_snapshot(*sg)); - - auto version = sg->get_version_of_current_transaction(); - transaction::advance(sg, realm.m_binding_context.get(), notifiers); - - // Realm could be closed in the callbacks. - if (realm.is_closed()) - return false; - - return version != sg->get_version_of_current_transaction(); -} - -void RealmCoordinator::promote_to_write(Realm& realm) -{ - REALM_ASSERT(!realm.is_in_transaction()); - - std::unique_lock lock(m_notifier_mutex); - _impl::NotifierPackage notifiers(m_async_error, notifiers_for_realm(realm), this); - lock.unlock(); - - auto& sg = Realm::Internal::get_shared_group(realm); - transaction::begin(sg, realm.m_binding_context.get(), notifiers); -} - -void RealmCoordinator::process_available_async(Realm& realm) -{ - REALM_ASSERT(!realm.is_in_transaction()); - - std::unique_lock lock(m_notifier_mutex); - auto notifiers = notifiers_for_realm(realm); - if (notifiers.empty()) - return; - - if (auto error = m_async_error) { - lock.unlock(); - if (realm.m_binding_context) - realm.m_binding_context->will_send_notifications(); - for (auto& notifier : notifiers) - notifier->deliver_error(m_async_error); - if (realm.m_binding_context) - realm.m_binding_context->did_send_notifications(); - return; - } - - bool in_read = realm.is_in_read_transaction(); - auto& sg = Realm::Internal::get_shared_group(realm); - auto version = sg->get_version_of_current_transaction(); - auto package = [&](auto& notifier) { - return !(notifier->has_run() && (!in_read || notifier->version() == version) && notifier->package_for_delivery()); - }; - notifiers.erase(std::remove_if(begin(notifiers), end(notifiers), package), end(notifiers)); - if (notifiers.empty()) - return; - lock.unlock(); - - // no before advance because the Realm is already at the given version, - // because we're either sending initial notifications or the write was - // done on this Realm instance - - if (realm.m_binding_context) { - realm.m_binding_context->will_send_notifications(); - if (!sg) // i.e. the Realm was closed in the callback above - return; - } - - // Skip delivering if the Realm isn't in a read transaction - if (in_read) { - for (auto& notifier : notifiers) - notifier->deliver(*sg); - } - - // but still call the change callbacks - for (auto& notifier : notifiers) - notifier->after_advance(); - - if (realm.m_binding_context) - realm.m_binding_context->did_send_notifications(); -} - -void RealmCoordinator::set_transaction_callback(std::function fn) -{ - create_sync_session(false, false); - m_transaction_callback = std::move(fn); -} - -#if REALM_ENABLE_SYNC -_impl::partial_sync::WorkQueue& RealmCoordinator::partial_sync_work_queue() -{ - return *m_partial_sync_work_queue; -} -#endif diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp deleted file mode 100644 index 4a711d3..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/results_notifier.cpp +++ /dev/null @@ -1,252 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/results_notifier.hpp" - -#include "shared_realm.hpp" - -using namespace realm; -using namespace realm::_impl; - -ResultsNotifier::ResultsNotifier(Results& target) -: CollectionNotifier(target.get_realm()) -, m_target_results(&target) -, m_target_is_in_table_order(target.is_in_table_order()) -{ - Query q = target.get_query(); - set_table(*q.get_table()); - m_query_handover = source_shared_group().export_for_handover(q, MutableSourcePayload::Move); - DescriptorOrdering::generate_patch(target.get_descriptor_ordering(), m_ordering_handover); -} - -void ResultsNotifier::target_results_moved(Results& old_target, Results& new_target) -{ - auto lock = lock_target(); - - REALM_ASSERT(m_target_results == &old_target); - m_target_results = &new_target; -} - -void ResultsNotifier::release_data() noexcept -{ - m_query = nullptr; -} - -// Most of the inter-thread synchronization for run(), prepare_handover(), -// attach_to(), detach(), release_data() and deliver() is done by -// RealmCoordinator external to this code, which has some potentially -// non-obvious results on which members are and are not safe to use without -// holding a lock. -// -// add_required_change_info(), attach_to(), detach(), run(), -// prepare_handover(), and release_data() are all only ever called on a single -// background worker thread. call_callbacks() and deliver() are called on the -// target thread. Calls to prepare_handover() and deliver() are guarded by a -// lock. -// -// In total, this means that the safe data flow is as follows: -// - add_Required_change_info(), prepare_handover(), attach_to(), detach() and -// release_data() can read members written by each other -// - deliver() can read members written to in prepare_handover(), deliver(), -// and call_callbacks() -// - call_callbacks() and read members written to in deliver() -// -// Separately from the handover data flow, m_target_results is guarded by the target lock - -bool ResultsNotifier::do_add_required_change_info(TransactionChangeInfo& info) -{ - REALM_ASSERT(m_query); - m_info = &info; - - auto& table = *m_query->get_table(); - if (!table.is_attached()) - return false; - - auto table_ndx = table.get_index_in_group(); - if (table_ndx == npos) { // is a subtable - auto& parent = *table.get_parent_table(); - size_t row_ndx = table.get_parent_row_index(); - size_t col_ndx = find_container_column(parent, row_ndx, &table, type_Table, &Table::get_subtable); - info.lists.push_back({parent.get_index_in_group(), row_ndx, col_ndx, &m_changes}); - } - else { // is a top-level table - if (info.table_moves_needed.size() <= table_ndx) - info.table_moves_needed.resize(table_ndx + 1); - info.table_moves_needed[table_ndx] = true; - } - - return has_run() && have_callbacks(); -} - -bool ResultsNotifier::need_to_run() -{ - REALM_ASSERT(m_info); - REALM_ASSERT(!m_tv.is_attached()); - - { - auto lock = lock_target(); - // Don't run the query if the results aren't actually going to be used - if (!get_realm() || (!have_callbacks() && !m_target_results->wants_background_updates())) { - return false; - } - } - - // If we've run previously, check if we need to rerun - if (has_run() && m_query->sync_view_if_needed() == m_last_seen_version) { - return false; - } - - return true; -} - -void ResultsNotifier::calculate_changes() -{ - size_t table_ndx = m_query->get_table()->get_index_in_group(); - if (has_run() && have_callbacks()) { - CollectionChangeBuilder* changes = nullptr; - if (table_ndx == npos) - changes = &m_changes; - else if (table_ndx < m_info->tables.size()) - changes = &m_info->tables[table_ndx]; - - std::vector next_rows; - next_rows.reserve(m_tv.size()); - for (size_t i = 0; i < m_tv.size(); ++i) - next_rows.push_back(m_tv[i].get_index()); - - util::Optional move_candidates; - if (changes) { - auto const& moves = changes->moves; - for (auto& idx : m_previous_rows) { - if (changes->deletions.contains(idx)) { - // check if this deletion was actually a move - auto it = lower_bound(begin(moves), end(moves), idx, - [](auto const& a, auto b) { return a.from < b; }); - idx = it != moves.end() && it->from == idx ? it->to : npos; - } - else - idx = changes->insertions.shift(changes->deletions.unshift(idx)); - } - if (m_target_is_in_table_order && !m_descriptor_ordering.will_apply_sort()) - move_candidates = changes->insertions; - } - - m_changes = CollectionChangeBuilder::calculate(m_previous_rows, next_rows, - get_modification_checker(*m_info, *m_query->get_table()), - move_candidates); - - m_previous_rows = std::move(next_rows); - } - else { - m_previous_rows.resize(m_tv.size()); - for (size_t i = 0; i < m_tv.size(); ++i) - m_previous_rows[i] = m_tv[i].get_index(); - } -} - -void ResultsNotifier::run() -{ - // Table's been deleted, so report all rows as deleted - if (!m_query->get_table()->is_attached()) { - m_changes = {}; - m_changes.deletions.set(m_previous_rows.size()); - m_previous_rows.clear(); - return; - } - - if (!need_to_run()) - return; - - m_query->sync_view_if_needed(); - m_tv = m_query->find_all(); - m_tv.apply_descriptor_ordering(m_descriptor_ordering); - m_last_seen_version = m_tv.sync_if_needed(); - - calculate_changes(); -} - -void ResultsNotifier::do_prepare_handover(SharedGroup& sg) -{ - if (!m_tv.is_attached()) { - // if the table version didn't change we can just reuse the same handover - // object and bump its version to the current SG version - if (m_tv_handover) - m_tv_handover->version = sg.get_version_of_current_transaction(); - - // add_changes() needs to be called even if there are no changes to - // clear the skip flag on the callbacks - add_changes(std::move(m_changes)); - return; - } - - REALM_ASSERT(m_tv.is_in_sync()); - - m_tv_handover = sg.export_for_handover(m_tv, MutableSourcePayload::Move); - - add_changes(std::move(m_changes)); - REALM_ASSERT(m_changes.empty()); - - // detach the TableView as we won't need it again and keeping it around - // makes advance_read() much more expensive - m_tv = {}; -} - -void ResultsNotifier::deliver(SharedGroup& sg) -{ - auto lock = lock_target(); - - // Target realm being null here indicates that we were unregistered while we - // were in the process of advancing the Realm version and preparing for - // delivery, i.e. the results was destroyed from the "wrong" thread - if (!get_realm()) { - return; - } - - REALM_ASSERT(!m_query_handover); - if (m_tv_to_deliver) { - Results::Internal::set_table_view(*m_target_results, - std::move(*sg.import_from_handover(std::move(m_tv_to_deliver)))); - } - REALM_ASSERT(!m_tv_to_deliver); -} - -bool ResultsNotifier::prepare_to_deliver() -{ - auto lock = lock_target(); - if (!get_realm()) - return false; - m_tv_to_deliver = std::move(m_tv_handover); - return true; -} - -void ResultsNotifier::do_attach_to(SharedGroup& sg) -{ - REALM_ASSERT(m_query_handover); - m_query = sg.import_from_handover(std::move(m_query_handover)); - m_descriptor_ordering = DescriptorOrdering::create_from_and_consume_patch(m_ordering_handover, *m_query->get_table()); -} - -void ResultsNotifier::do_detach_from(SharedGroup& sg) -{ - REALM_ASSERT(m_query); - REALM_ASSERT(!m_tv.is_attached()); - - DescriptorOrdering::generate_patch(m_descriptor_ordering, m_ordering_handover); - m_query_handover = sg.export_for_handover(*m_query, MutableSourcePayload::Move); - m_query = nullptr; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp deleted file mode 100644 index 2b3ff27..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/transact_log_handler.cpp +++ /dev/null @@ -1,875 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/transact_log_handler.hpp" - -#include "binding_context.hpp" -#include "impl/collection_notifier.hpp" -#include "index_set.hpp" -#include "shared_realm.hpp" - -#include -#include - -#include -#include - -using namespace realm; - -namespace { - -class KVOAdapter : public _impl::TransactionChangeInfo { -public: - KVOAdapter(std::vector& observers, BindingContext* context); - - void before(SharedGroup& sg); - void after(SharedGroup& sg); - -private: - BindingContext* m_context; - std::vector& m_observers; - std::vector m_invalidated; - - struct ListInfo { - BindingContext::ObserverState* observer; - _impl::CollectionChangeBuilder builder; - size_t col; - size_t initial_size; - }; - std::vector m_lists; - VersionID m_version; - - size_t new_table_ndx(size_t ndx) const { return ndx < table_indices.size() ? table_indices[ndx] : ndx; } -}; - -KVOAdapter::KVOAdapter(std::vector& observers, BindingContext* context) -: _impl::TransactionChangeInfo{} -, m_context(context) -, m_observers(observers) -{ - if (m_observers.empty()) - return; - - std::vector tables_needed; - for (auto& observer : observers) { - tables_needed.push_back(observer.table_ndx); - } - std::sort(begin(tables_needed), end(tables_needed)); - tables_needed.erase(std::unique(begin(tables_needed), end(tables_needed)), end(tables_needed)); - - auto realm = context->realm.lock(); - auto& group = realm->read_group(); - for (auto& observer : observers) { - auto table = group.get_table(observer.table_ndx); - for (size_t i = 0, count = table->get_column_count(); i < count; ++i) { - auto type = table->get_column_type(i); - if (type == type_LinkList) - m_lists.push_back({&observer, {}, i, size_t(-1)}); - else if (type == type_Table) - m_lists.push_back({&observer, {}, i, table->get_subtable_size(i, observer.row_ndx)}); - } - } - - auto max = std::max_element(begin(tables_needed), end(tables_needed)); - if (*max >= table_modifications_needed.size()) - table_modifications_needed.resize(*max + 1, false); - if (*max >= table_moves_needed.size()) - table_moves_needed.resize(*max + 1, false); - for (auto& tbl : tables_needed) { - table_modifications_needed[tbl] = true; - table_moves_needed[tbl] = true; - } - for (auto& list : m_lists) - lists.push_back({list.observer->table_ndx, list.observer->row_ndx, list.col, &list.builder}); -} - -void KVOAdapter::before(SharedGroup& sg) -{ - if (!m_context) - return; - - m_version = sg.get_version_of_current_transaction(); - if (tables.empty()) - return; - - for (auto& observer : m_observers) { - size_t table_ndx = new_table_ndx(observer.table_ndx); - if (table_ndx >= tables.size()) - continue; - - auto const& table = tables[table_ndx]; - auto const& moves = table.moves; - auto idx = observer.row_ndx; - auto it = lower_bound(begin(moves), end(moves), idx, - [](auto const& a, auto b) { return a.from < b; }); - if (it != moves.end() && it->from == idx) - idx = it->to; - else if (table.deletions.contains(idx)) { - m_invalidated.push_back(observer.info); - continue; - } - else - idx = table.insertions.shift(table.deletions.unshift(idx)); - if (table.modifications.contains(idx)) { - observer.changes.resize(table.columns.size()); - size_t i = 0; - for (auto& c : table.columns) { - auto& change = observer.changes[i]; - if (table_ndx >= column_indices.size() || column_indices[table_ndx].empty()) - change.initial_column_index = i; - else if (i >= column_indices[table_ndx].size()) - change.initial_column_index = i - column_indices[table_ndx].size() + column_indices[table_ndx].back() + 1; - else - change.initial_column_index = column_indices[table_ndx][i]; - if (change.initial_column_index != npos && c.contains(idx)) - change.kind = BindingContext::ColumnInfo::Kind::Set; - ++i; - } - } - } - - for (auto& list : m_lists) { - if (list.builder.empty()) { - // We may have pre-emptively marked the column as modified if the - // LinkList was selected but the actual changes made ended up being - // a no-op - if (list.col < list.observer->changes.size()) - list.observer->changes[list.col].kind = BindingContext::ColumnInfo::Kind::None; - continue; - } - // If the containing row was deleted then changes will be empty - if (list.observer->changes.empty()) { - REALM_ASSERT_DEBUG(tables[new_table_ndx(list.observer->table_ndx)].deletions.contains(list.observer->row_ndx)); - continue; - } - // otherwise the column should have been marked as modified - REALM_ASSERT(list.col < list.observer->changes.size()); - auto& builder = list.builder; - auto& changes = list.observer->changes[list.col]; - - builder.modifications.remove(builder.insertions); - - // KVO can't express moves (becaue NSArray doesn't have them), so - // transform them into a series of sets on each affected index when possible - if (!builder.moves.empty() && builder.insertions.count() == builder.moves.size() && builder.deletions.count() == builder.moves.size()) { - changes.kind = BindingContext::ColumnInfo::Kind::Set; - changes.indices = builder.modifications; - changes.indices.add(builder.deletions); - - // Iterate over each of the rows which may have been shifted by - // the moves and check if it actually has been, or if it's ended - // up in the same place as it started (either because the moves were - // actually a swap that doesn't effect the rows in between, or the - // combination of moves happen to leave some intermediate rows in - // the same place) - auto in_range = [](auto& it, auto end, size_t i) { - if (it != end && i >= it->second) - ++it; - return it != end && i >= it->first && i < it->second; - }; - - auto del_it = builder.deletions.begin(), del_end = builder.deletions.end(); - auto ins_it = builder.insertions.begin(), ins_end = builder.insertions.end(); - size_t start = std::min(ins_it->first, del_it->first); - size_t end = std::max(std::prev(ins_end)->second, std::prev(del_end)->second); - ptrdiff_t shift = 0; - for (size_t i = start; i < end; ++i) { - if (in_range(del_it, del_end, i)) - --shift; - else if (in_range(ins_it, ins_end, i + shift)) - ++shift; - if (shift != 0) - changes.indices.add(i); - } - } - // KVO can't express multiple types of changes at once - else if (builder.insertions.empty() + builder.modifications.empty() + builder.deletions.empty() < 2) { - changes.kind = BindingContext::ColumnInfo::Kind::SetAll; - } - else if (!builder.insertions.empty()) { - changes.kind = BindingContext::ColumnInfo::Kind::Insert; - changes.indices = builder.insertions; - } - else if (!builder.modifications.empty()) { - changes.kind = BindingContext::ColumnInfo::Kind::Set; - changes.indices = builder.modifications; - } - else { - REALM_ASSERT(!builder.deletions.empty()); - changes.kind = BindingContext::ColumnInfo::Kind::Remove; - // Table clears don't come with the size, so we need to fix up the - // notification to make it just delete all rows that actually existed - if (std::prev(builder.deletions.end())->second > list.initial_size) - changes.indices.set(list.initial_size); - else - changes.indices = builder.deletions; - } - } - m_context->will_change(m_observers, m_invalidated); -} - -void KVOAdapter::after(SharedGroup& sg) -{ - if (!m_context) - return; - m_context->did_change(m_observers, m_invalidated, - m_version != VersionID{} && - m_version != sg.get_version_of_current_transaction()); -} - -template -struct MarkDirtyMixin { - bool mark_dirty(size_t row, size_t col, _impl::Instruction instr=_impl::instr_Set) - { - // Ignore SetDefault and SetUnique as those conceptually cannot be - // changes to existing rows - if (instr == _impl::instr_Set) - static_cast(this)->mark_dirty(row, col); - return true; - } - - bool set_int(size_t c, size_t r, int_fast64_t, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } - bool set_bool(size_t c, size_t r, bool, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_float(size_t c, size_t r, float, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_double(size_t c, size_t r, double, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_string(size_t c, size_t r, StringData, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } - bool set_binary(size_t c, size_t r, BinaryData, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_olddatetime(size_t c, size_t r, OldDateTime, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_timestamp(size_t c, size_t r, Timestamp, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_table(size_t c, size_t r, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_mixed(size_t c, size_t r, const Mixed&, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_link(size_t c, size_t r, size_t, size_t, _impl::Instruction i) { return mark_dirty(r, c, i); } - bool set_null(size_t c, size_t r, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); } - - bool add_int(size_t col, size_t row, int_fast64_t) { return mark_dirty(row, col); } - bool nullify_link(size_t col, size_t row, size_t) { return mark_dirty(row, col); } - bool insert_substring(size_t col, size_t row, size_t, StringData) { return mark_dirty(row, col); } - bool erase_substring(size_t col, size_t row, size_t, size_t) { return mark_dirty(row, col); } - - bool set_int_unique(size_t, size_t, size_t, int_fast64_t) { return true; } - bool set_string_unique(size_t, size_t, size_t, StringData) { return true; } - - bool add_row_with_key(size_t, size_t, size_t, int64_t) { return true; } -}; - -class TransactLogValidationMixin { - // Index of currently selected table - size_t m_current_table = 0; - - REALM_NORETURN - REALM_NOINLINE - void schema_error() - { - throw _impl::UnsupportedSchemaChange(); - } - -protected: - size_t current_table() const noexcept { return m_current_table; } - -public: - - bool select_table(size_t group_level_ndx, int, const size_t*) noexcept - { - m_current_table = group_level_ndx; - return true; - } - - // Removing or renaming things while a Realm is open is never supported - bool erase_group_level_table(size_t, size_t) { schema_error(); } - bool rename_group_level_table(size_t, StringData) { schema_error(); } - bool erase_column(size_t) { schema_error(); } - bool erase_link_column(size_t, size_t, size_t) { schema_error(); } - bool rename_column(size_t, StringData) { schema_error(); } - - // Schema changes which don't involve a change in the schema version are - // allowed - bool add_search_index(size_t) { return true; } - bool remove_search_index(size_t) { return true; } - - // Additive changes and reorderings are supported - bool insert_group_level_table(size_t, size_t, StringData) { return true; } - bool insert_column(size_t, DataType, StringData, bool) { return true; } - bool insert_link_column(size_t, DataType, StringData, size_t, size_t) { return true; } - bool set_link_type(size_t, LinkType) { return true; } - bool move_column(size_t, size_t) { return true; } - bool move_group_level_table(size_t, size_t) { return true; } - - // Non-schema changes are all allowed - void parse_complete() { } - bool select_descriptor(int, const size_t*) { return true; } - bool select_link_list(size_t, size_t, size_t) { return true; } - bool insert_empty_rows(size_t, size_t, size_t, bool) { return true; } - bool erase_rows(size_t, size_t, size_t, bool) { return true; } - bool swap_rows(size_t, size_t) { return true; } - bool move_row(size_t, size_t) { return true; } - bool clear_table(size_t=0) noexcept { return true; } - bool link_list_set(size_t, size_t, size_t) { return true; } - bool link_list_insert(size_t, size_t, size_t) { return true; } - bool link_list_erase(size_t, size_t) { return true; } - bool link_list_nullify(size_t, size_t) { return true; } - bool link_list_clear(size_t) { return true; } - bool link_list_move(size_t, size_t) { return true; } - bool link_list_swap(size_t, size_t) { return true; } - bool merge_rows(size_t, size_t) { return true; } - bool optimize_table() { return true; } -}; - - -// A transaction log handler that just validates that all operations made are -// ones supported by the object store -struct TransactLogValidator : public TransactLogValidationMixin, public MarkDirtyMixin { - void mark_dirty(size_t, size_t) { } -}; - -// Move the value at container[from] to container[to], shifting everything in -// between, or do nothing if either are out of bounds -template -void rotate(Container& container, size_t from, size_t to) -{ - REALM_ASSERT(from != to); - if (from >= container.size() && to >= container.size()) - return; - if (from >= container.size() || to >= container.size()) - container.resize(std::max(from, to) + 1); - if (from < to) - std::rotate(begin(container) + from, begin(container) + from + 1, begin(container) + to + 1); - else - std::rotate(begin(container) + to, begin(container) + from, begin(container) + from + 1); -} - -// Insert a default-initialized value at pos if there is anything after pos in the container. -template -void insert_empty_at(Container& container, size_t pos) -{ - if (pos < container.size()) - container.emplace(container.begin() + pos); -} - -// Shift `value` to reflect a move from `from` to `to` -void adjust_for_move(size_t& value, size_t from, size_t to) -{ - if (value == from) - value = to; - else if (value > from && value <= to) - --value; - else if (value < from && value >= to) - ++value; -} - -void adjust_for_move(std::vector& values, size_t from, size_t to) -{ - for (auto& value : values) - adjust_for_move(value, from, to); -} - -void expand_to(std::vector& cols, size_t i) -{ - auto old_size = cols.size(); - if (old_size > i) - return; - - cols.resize(std::max(old_size * 2, i + 1)); - std::iota(begin(cols) + old_size, end(cols), old_size == 0 ? 0 : cols[old_size - 1] + 1); -} - -void adjust_ge(std::vector& values, size_t i) -{ - for (auto& value : values) { - if (value >= i) - ++value; - } -} - -// Extends TransactLogValidator to track changes made to LinkViews -class TransactLogObserver : public TransactLogValidationMixin, public MarkDirtyMixin { - _impl::TransactionChangeInfo& m_info; - _impl::CollectionChangeBuilder* m_active_list = nullptr; - _impl::CollectionChangeBuilder* m_active_table = nullptr; - _impl::CollectionChangeBuilder* m_active_descriptor = nullptr; - - bool m_need_move_info = false; - bool m_is_top_level_table = true; - - _impl::CollectionChangeBuilder* find_list(size_t tbl, size_t col, size_t row) - { - // When there are multiple source versions there could be multiple - // change objects for a single LinkView, in which case we need to use - // the last one - for (auto it = m_info.lists.rbegin(), end = m_info.lists.rend(); it != end; ++it) { - if (it->table_ndx == tbl && it->row_ndx == row && it->col_ndx == col) - return it->changes; - } - return nullptr; - } - -public: - TransactLogObserver(_impl::TransactionChangeInfo& info) - : m_info(info) { } - - void mark_dirty(size_t row, size_t col) - { - if (m_active_table) - m_active_table->modify(row, col); - } - - void parse_complete() - { - for (auto& table : m_info.tables) - table.parse_complete(); - for (auto& list : m_info.lists) - list.changes->clean_up_stale_moves(); - } - - bool select_descriptor(int levels, const size_t*) noexcept - { - if (levels == 0) // schema of selected table is being modified - m_active_descriptor = m_active_table; - else // schema of subtable is being modified; currently don't need to track this - m_active_descriptor = nullptr; - return true; - } - - bool select_table(size_t group_level_ndx, int len, size_t const* path) noexcept - { - TransactLogValidationMixin::select_table(group_level_ndx, len, path); - m_active_table = nullptr; - m_is_top_level_table = true; - - // Nested subtables currently not supported - if (len > 1) { - m_is_top_level_table = false; - return true; - } - - auto tbl_ndx = current_table(); - if (!m_info.track_all && (tbl_ndx >= m_info.table_modifications_needed.size() || !m_info.table_modifications_needed[tbl_ndx])) - return true; - - m_need_move_info = m_info.track_all || (tbl_ndx < m_info.table_moves_needed.size() && - m_info.table_moves_needed[tbl_ndx]); - if (m_info.tables.size() <= tbl_ndx) - m_info.tables.resize(std::max(m_info.tables.size() * 2, tbl_ndx + 1)); - m_active_table = &m_info.tables[tbl_ndx]; - - if (len == 1) { - // Mark the cell containing the subtable as modified since selecting - // a table is always followed by a modification of some sort - size_t col = path[0]; - size_t row = path[1]; - mark_dirty(row, col); - - m_active_table = nullptr; - m_is_top_level_table = false; - if (auto table = find_list(current_table(), col, row)) { - m_active_table = table; - m_need_move_info = true; - } - } - return true; - } - - bool select_link_list(size_t col, size_t row, size_t) - { - mark_dirty(row, col); - m_active_list = find_list(current_table(), col, row); - return true; - } - - bool link_list_set(size_t index, size_t, size_t) - { - if (m_active_list) - m_active_list->modify(index); - return true; - } - - bool link_list_insert(size_t index, size_t, size_t) - { - if (m_active_list) - m_active_list->insert(index); - return true; - } - - bool link_list_erase(size_t index, size_t) - { - if (m_active_list) - m_active_list->erase(index); - return true; - } - - bool link_list_nullify(size_t index, size_t prior_size) - { - return link_list_erase(index, prior_size); - } - - bool link_list_swap(size_t index1, size_t index2) - { - link_list_set(index1, 0, npos); - link_list_set(index2, 0, npos); - return true; - } - - bool link_list_clear(size_t old_size) - { - if (m_active_list) - m_active_list->clear(old_size); - return true; - } - - bool link_list_move(size_t from, size_t to) - { - if (m_active_list) - m_active_list->move(from, to); - return true; - } - - bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t, bool) - { - if (m_active_table) - m_active_table->insert(row_ndx, num_rows_to_insert, m_need_move_info); - if (!m_is_top_level_table) - return true; - for (auto& list : m_info.lists) { - if (list.table_ndx == current_table() && list.row_ndx >= row_ndx) - list.row_ndx += num_rows_to_insert; - } - return true; - } - - bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t, int64_t) - { - insert_empty_rows(row_ndx, 1, prior_num_rows, false); - return true; - } - - bool erase_rows(size_t row_ndx, size_t, size_t prior_num_rows, bool unordered) - { - if (!unordered) { - if (m_active_table) - m_active_table->erase(row_ndx); - return true; - } - size_t last_row = prior_num_rows - 1; - if (m_active_table) - m_active_table->move_over(row_ndx, last_row, m_need_move_info); - - if (!m_is_top_level_table) - return true; - for (size_t i = 0; i < m_info.lists.size(); ++i) { - auto& list = m_info.lists[i]; - if (list.table_ndx != current_table()) - continue; - if (list.row_ndx == row_ndx) { - if (i + 1 < m_info.lists.size()) - m_info.lists[i] = std::move(m_info.lists.back()); - m_info.lists.pop_back(); - continue; - } - if (list.row_ndx == last_row) - list.row_ndx = row_ndx; - } - - return true; - } - - bool swap_rows(size_t row_ndx_1, size_t row_ndx_2) { - REALM_ASSERT(row_ndx_1 < row_ndx_2); - if (!m_is_top_level_table) { - if (m_active_table) { - m_active_table->move(row_ndx_1, row_ndx_2); - if (row_ndx_1 + 1 != row_ndx_2) - m_active_table->move(row_ndx_2 - 1, row_ndx_1); - } - return true; - } - - if (m_active_table) - m_active_table->swap(row_ndx_1, row_ndx_2, m_need_move_info); - for (auto& list : m_info.lists) { - if (list.table_ndx == current_table()) { - if (list.row_ndx == row_ndx_1) - list.row_ndx = row_ndx_2; - else if (list.row_ndx == row_ndx_2) - list.row_ndx = row_ndx_1; - } - } - return true; - } - - bool move_row(size_t from_ndx, size_t to_ndx) { - // Move row is not supported for top level tables: - REALM_ASSERT(!m_active_table || !m_is_top_level_table); - - if (m_active_table) - m_active_table->move(from_ndx, to_ndx); - return true; - } - - bool merge_rows(size_t from, size_t to) - { - if (m_active_table) - m_active_table->subsume(from, to, m_need_move_info); - if (!m_is_top_level_table) - return true; - for (auto& list : m_info.lists) { - if (list.table_ndx == current_table() && list.row_ndx == from) - list.row_ndx = to; - } - return true; - } - - bool clear_table(size_t=0) - { - auto tbl_ndx = current_table(); - if (m_active_table) - m_active_table->clear(std::numeric_limits::max()); - if (!m_is_top_level_table) - return true; - auto it = remove_if(begin(m_info.lists), end(m_info.lists), - [&](auto const& lv) { return lv.table_ndx == tbl_ndx; }); - m_info.lists.erase(it, end(m_info.lists)); - return true; - } - - bool insert_column(size_t ndx, DataType, StringData, bool) - { - m_info.schema_changed = true; - - if (m_active_descriptor) - m_active_descriptor->insert_column(ndx); - if (m_active_descriptor != m_active_table || !m_is_top_level_table) - return true; - for (auto& list : m_info.lists) { - if (list.table_ndx == current_table() && list.col_ndx >= ndx) - ++list.col_ndx; - } - if (m_info.column_indices.size() <= current_table()) - m_info.column_indices.resize(current_table() + 1); - auto& indices = m_info.column_indices[current_table()]; - expand_to(indices, ndx); - insert_empty_at(indices, ndx); - indices[ndx] = npos; - return true; - } - - void prepare_table_indices() - { - if (m_info.table_indices.empty() && !m_info.table_modifications_needed.empty()) { - m_info.table_indices.resize(m_info.table_modifications_needed.size()); - std::iota(begin(m_info.table_indices), end(m_info.table_indices), 0); - } - } - - bool insert_group_level_table(size_t ndx, size_t, StringData) - { - m_info.schema_changed = true; - - for (auto& list : m_info.lists) { - if (list.table_ndx >= ndx) - ++list.table_ndx; - } - prepare_table_indices(); - adjust_ge(m_info.table_indices, ndx); - insert_empty_at(m_info.tables, ndx); - insert_empty_at(m_info.table_moves_needed, ndx); - insert_empty_at(m_info.table_modifications_needed, ndx); - return true; - } - - bool move_column(size_t from, size_t to) - { - m_info.schema_changed = true; - - if (m_active_descriptor) - m_active_descriptor->move_column(from, to); - if (m_active_descriptor != m_active_table || !m_is_top_level_table) - return true; - for (auto& list : m_info.lists) { - if (list.table_ndx == current_table()) - adjust_for_move(list.col_ndx, from, to); - } - if (m_info.column_indices.size() <= current_table()) - m_info.column_indices.resize(current_table() + 1); - expand_to(m_info.column_indices[current_table()], std::max(from, to) + 1); - rotate(m_info.column_indices[current_table()], from, to); - return true; - } - - bool move_group_level_table(size_t from, size_t to) - { - m_info.schema_changed = true; - - for (auto& list : m_info.lists) - adjust_for_move(list.table_ndx, from, to); - - prepare_table_indices(); - adjust_for_move(m_info.table_indices, from, to); - rotate(m_info.tables, from, to); - rotate(m_info.table_modifications_needed, from, to); - rotate(m_info.table_moves_needed, from, to); - return true; - } - - bool insert_link_column(size_t ndx, DataType type, StringData name, size_t, size_t) { return insert_column(ndx, type, name, false); } -}; - -class KVOTransactLogObserver : public TransactLogObserver { - KVOAdapter m_adapter; - _impl::NotifierPackage& m_notifiers; - SharedGroup& m_sg; - -public: - KVOTransactLogObserver(std::vector& observers, - BindingContext* context, - _impl::NotifierPackage& notifiers, - SharedGroup& sg) - : TransactLogObserver(m_adapter) - , m_adapter(observers, context) - , m_notifiers(notifiers) - , m_sg(sg) - { - } - - ~KVOTransactLogObserver() - { - m_adapter.after(m_sg); - } - - void parse_complete() - { - TransactLogObserver::parse_complete(); - m_adapter.before(m_sg); - - using sgf = _impl::SharedGroupFriend; - m_notifiers.package_and_wait(sgf::get_version_of_latest_snapshot(m_sg)); - m_notifiers.before_advance(); - } -}; - -template -void advance_with_notifications(BindingContext* context, const std::unique_ptr& sg, - Func&& func, _impl::NotifierPackage& notifiers) -{ - auto old_version = sg->get_version_of_current_transaction(); - std::vector observers; - if (context) { - observers = context->get_observed_rows(); - } - - // Advancing to the latest version with notifiers requires using the full - // transaction log observer so that we have a point where we know what - // version we're going to before we actually advance to that version - if (observers.empty() && (!notifiers || notifiers.version())) { - notifiers.before_advance(); - func(TransactLogValidator()); - auto new_version = sg->get_version_of_current_transaction(); - if (context && old_version != new_version) - context->did_change({}, {}); - if (!sg) // did_change() could close the Realm. Just return if it does. - return; - if (context) - context->will_send_notifications(); - if (!sg) // will_send_notifications() could close the Realm. Just return if it does. - return; - // did_change() can change the read version, and if it does we can't - // deliver notifiers - if (new_version == sg->get_version_of_current_transaction()) - notifiers.deliver(*sg); - notifiers.after_advance(); - if (sg && context) - context->did_send_notifications(); - return; - } - - if (context) - context->will_send_notifications(); - func(KVOTransactLogObserver(observers, context, notifiers, *sg)); - notifiers.package_and_wait(sg->get_version_of_current_transaction().version); // is a no-op if parse_complete() was called - notifiers.deliver(*sg); - notifiers.after_advance(); - if (context) - context->did_send_notifications(); -} - -} // anonymous namespace - -namespace realm { -namespace _impl { - -UnsupportedSchemaChange::UnsupportedSchemaChange() -: std::logic_error("Schema mismatch detected: another process has modified the Realm file's schema in an incompatible way") -{ -} - -namespace transaction { -void advance(SharedGroup& sg, BindingContext*, VersionID version) -{ - LangBindHelper::advance_read(sg, TransactLogValidator(), version); -} - -void advance(const std::unique_ptr& sg, BindingContext* context, NotifierPackage& notifiers) -{ - advance_with_notifications(context, sg, [&](auto&&... args) { - LangBindHelper::advance_read(*sg, std::move(args)..., notifiers.version().value_or(VersionID{})); - }, notifiers); -} - -void begin_without_validation(SharedGroup& sg) -{ - LangBindHelper::promote_to_write(sg); -} - -void begin(const std::unique_ptr& sg, BindingContext* context, NotifierPackage& notifiers) -{ - advance_with_notifications(context, sg, [&](auto&&... args) { - LangBindHelper::promote_to_write(*sg, std::move(args)...); - }, notifiers); -} - -void commit(SharedGroup& sg) -{ - LangBindHelper::commit_and_continue_as_read(sg); -} - -void cancel(SharedGroup& sg, BindingContext* context) -{ - std::vector observers; - if (context) { - observers = context->get_observed_rows(); - } - if (observers.empty()) { - LangBindHelper::rollback_and_continue_as_read(sg); - return; - } - - _impl::NotifierPackage notifiers; - LangBindHelper::rollback_and_continue_as_read(sg, KVOTransactLogObserver(observers, context, notifiers, sg)); -} - -void advance(SharedGroup& sg, TransactionChangeInfo& info, VersionID version) -{ - if (!info.track_all && info.table_modifications_needed.empty() && info.lists.empty()) { - LangBindHelper::advance_read(sg, version); - } - else { - LangBindHelper::advance_read(sg, TransactLogObserver(info), version); - } -} - -} // namespace transaction -} // namespace _impl -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp deleted file mode 100644 index d52c2e6..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/impl/weak_realm_notifier.cpp +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "impl/weak_realm_notifier.hpp" - -#include "shared_realm.hpp" -#include "util/event_loop_signal.hpp" - -using namespace realm; -using namespace realm::_impl; - -WeakRealmNotifier::WeakRealmNotifier(const std::shared_ptr& realm, bool cache, bool bind_to_context) -: m_realm(realm) -, m_execution_context(realm->config().execution_context) -, m_realm_key(realm.get()) -, m_cache(cache) -, m_signal(bind_to_context ? std::make_shared>(Callback{realm}) : nullptr) -{ -} - -WeakRealmNotifier::~WeakRealmNotifier() = default; - -void WeakRealmNotifier::Callback::operator()() const -{ - if (auto realm = weak_realm.lock()) { - realm->notify(); - } -} - -void WeakRealmNotifier::notify() -{ - if (m_signal) - m_signal->notify(); -} - -void WeakRealmNotifier::bind_to_execution_context(AnyExecutionContextID context) -{ - REALM_ASSERT(!m_signal); - m_signal = std::make_shared>(Callback{m_realm}); - m_execution_context = context; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/index_set.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/index_set.cpp deleted file mode 100644 index e1a3b10..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/index_set.cpp +++ /dev/null @@ -1,707 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "index_set.hpp" - -#include - -#include - -using namespace realm; -using namespace realm::_impl; - -const size_t IndexSet::npos; - -template -void MutableChunkedRangeVectorIterator::set(size_t front, size_t back) -{ - this->m_outer->count -= this->m_inner->second - this->m_inner->first; - if (this->offset() == 0) { - this->m_outer->begin = front; - } - if (this->m_inner == &this->m_outer->data.back()) { - this->m_outer->end = back; - } - this->m_outer->count += back - front; - this->m_inner->first = front; - this->m_inner->second = back; -} - -template -void MutableChunkedRangeVectorIterator::adjust(ptrdiff_t front, ptrdiff_t back) -{ - if (this->offset() == 0) { - this->m_outer->begin += front; - } - if (this->m_inner == &this->m_outer->data.back()) { - this->m_outer->end += back; - } - this->m_outer->count += -front + back; - this->m_inner->first += front; - this->m_inner->second += back; -} - -template -void MutableChunkedRangeVectorIterator::shift(ptrdiff_t distance) -{ - if (this->offset() == 0) { - this->m_outer->begin += distance; - } - if (this->m_inner == &this->m_outer->data.back()) { - this->m_outer->end += distance; - } - this->m_inner->first += distance; - this->m_inner->second += distance; -} - -void ChunkedRangeVector::push_back(value_type value) -{ - if (!empty() && m_data.back().data.size() < max_size) { - auto& range = m_data.back(); - REALM_ASSERT(range.end <= value.first); - - range.data.push_back(value); - range.count += value.second - value.first; - range.end = value.second; - } - else { - m_data.push_back({{value}, value.first, value.second, value.second - value.first}); - } - verify(); -} - -ChunkedRangeVector::iterator ChunkedRangeVector::insert(iterator pos, value_type value) -{ - if (pos.m_outer == m_data.end()) { - push_back(std::move(value)); - return std::prev(end()); - } - - pos = ensure_space(pos); - auto& chunk = *pos.m_outer; - pos.m_inner = &*chunk.data.insert(pos.m_outer->data.begin() + pos.offset(), value); - chunk.count += value.second - value.first; - chunk.begin = std::min(chunk.begin, value.first); - chunk.end = std::max(chunk.end, value.second); - - verify(); - return pos; -} - -ChunkedRangeVector::iterator ChunkedRangeVector::ensure_space(iterator pos) -{ - if (pos.m_outer->data.size() + 1 <= max_size) - return pos; - - auto offset = pos.offset(); - - // Split the chunk in half to make space for the new insertion - auto new_pos = m_data.insert(pos.m_outer + 1, Chunk{}); - auto prev = new_pos - 1; - auto to_move = max_size / 2; - new_pos->data.reserve(to_move); - new_pos->data.assign(prev->data.end() - to_move, prev->data.end()); - prev->data.resize(prev->data.size() - to_move); - - size_t moved_count = 0; - for (auto range : new_pos->data) - moved_count += range.second - range.first; - - prev->end = prev->data.back().second; - prev->count -= moved_count; - new_pos->begin = new_pos->data.front().first; - new_pos->end = new_pos->data.back().second; - new_pos->count = moved_count; - - if (offset >= to_move) { - pos.m_outer = new_pos; - offset -= to_move; - } - else { - pos.m_outer = prev; - } - pos.m_end = m_data.end(); - pos.m_inner = &pos.m_outer->data[offset]; - verify(); - return pos; -} - -ChunkedRangeVector::iterator ChunkedRangeVector::erase(iterator pos) noexcept -{ - auto offset = pos.offset(); - auto& chunk = *pos.m_outer; - chunk.count -= pos->second - pos->first; - chunk.data.erase(chunk.data.begin() + offset); - - if (chunk.data.size() == 0) { - pos.m_outer = m_data.erase(pos.m_outer); - pos.m_end = m_data.end(); - pos.m_inner = pos.m_outer == m_data.end() ? nullptr : &pos.m_outer->data.front(); - verify(); - return pos; - } - - chunk.begin = chunk.data.front().first; - chunk.end = chunk.data.back().second; - if (offset < chunk.data.size()) - pos.m_inner = &chunk.data[offset]; - else { - ++pos.m_outer; - pos.m_inner = pos.m_outer == pos.m_end ? nullptr : &pos.m_outer->data.front(); - } - - verify(); - return pos; -} - -void ChunkedRangeVector::verify() const noexcept -{ -#ifdef REALM_DEBUG - size_t prev_end = -1; - for (auto range : *this) { - REALM_ASSERT(range.first < range.second); - REALM_ASSERT(prev_end == size_t(-1) || range.first > prev_end); - prev_end = range.second; - } - - for (auto& chunk : m_data) { - REALM_ASSERT(!chunk.data.empty()); - REALM_ASSERT(chunk.data.front().first == chunk.begin); - REALM_ASSERT(chunk.data.back().second == chunk.end); - REALM_ASSERT(chunk.count <= chunk.end - chunk.begin); - size_t count = 0; - for (auto range : chunk.data) - count += range.second - range.first; - REALM_ASSERT(count == chunk.count); - } -#endif -} - -namespace { -class ChunkedRangeVectorBuilder { -public: - using value_type = std::pair; - - ChunkedRangeVectorBuilder(ChunkedRangeVector const& expected); - void push_back(size_t index); - void push_back(std::pair range); - std::vector finalize(); -private: - std::vector m_data; - size_t m_outer_pos = 0; -}; - -ChunkedRangeVectorBuilder::ChunkedRangeVectorBuilder(ChunkedRangeVector const& expected) -{ - size_t size = 0; - for (auto const& chunk : expected.m_data) - size += chunk.data.size(); - m_data.resize(size / ChunkedRangeVector::max_size + 1); - for (size_t i = 0; i < m_data.size() - 1; ++i) - m_data[i].data.reserve(ChunkedRangeVector::max_size); -} - -void ChunkedRangeVectorBuilder::push_back(size_t index) -{ - push_back({index, index + 1}); -} - -void ChunkedRangeVectorBuilder::push_back(std::pair range) -{ - auto& chunk = m_data[m_outer_pos]; - if (chunk.data.empty()) { - chunk.data.push_back(range); - chunk.count = range.second - range.first; - chunk.begin = range.first; - } - else if (range.first == chunk.data.back().second) { - chunk.data.back().second = range.second; - chunk.count += range.second - range.first; - } - else if (chunk.data.size() < ChunkedRangeVector::max_size) { - chunk.data.push_back(range); - chunk.count += range.second - range.first; - } - else { - chunk.end = chunk.data.back().second; - ++m_outer_pos; - if (m_outer_pos >= m_data.size()) - m_data.push_back({{range}, range.first, 0, 1}); - else { - auto& chunk = m_data[m_outer_pos]; - chunk.data.push_back(range); - chunk.begin = range.first; - chunk.count = range.second - range.first; - } - } -} - -std::vector ChunkedRangeVectorBuilder::finalize() -{ - if (!m_data.empty()) { - m_data.resize(m_outer_pos + 1); - if (m_data.back().data.empty()) - m_data.pop_back(); - else - m_data.back().end = m_data.back().data.back().second; - } - return std::move(m_data); -} -} - -IndexSet::IndexSet(std::initializer_list values) -{ - for (size_t v : values) - add(v); -} - -bool IndexSet::contains(size_t index) const noexcept -{ - auto it = const_cast(this)->find(index); - return it != end() && it->first <= index; -} - -size_t IndexSet::count(size_t start_index, size_t end_index) const noexcept -{ - auto it = const_cast(this)->find(start_index); - const auto end = this->end(); - if (it == end || it->first >= end_index) { - return 0; - } - if (it->second >= end_index) - return std::min(it->second, end_index) - std::max(it->first, start_index); - - size_t ret = 0; - - if (start_index > it->first || it.offset() != 0) { - // Start index is in the middle of a chunk, so start by counting the - // rest of that chunk - ret = it->second - std::max(it->first, start_index); - for (++it; it != end && it->second < end_index && it.offset() != 0; ++it) { - ret += it->second - it->first; - } - if (it != end && it->first < end_index && it.offset() != 0) - ret += end_index - it->first; - if (it == end || it->second >= end_index) - return ret; - } - - // Now count all complete chunks that fall within the range - while (it != end && it.outer()->end <= end_index) { - REALM_ASSERT_DEBUG(it.offset() == 0); - ret += it.outer()->count; - it.next_chunk(); - } - - // Cound all complete ranges within the last chunk - while (it != end && it->second <= end_index) { - ret += it->second - it->first; - ++it; - } - - // And finally add in the partial last range - if (it != end && it->first < end_index) - ret += end_index - it->first; - return ret; -} - -IndexSet::iterator IndexSet::find(size_t index) noexcept -{ - return find(index, begin()); -} - -IndexSet::iterator IndexSet::find(size_t index, iterator begin) noexcept -{ - auto it = std::find_if(begin.outer(), m_data.end(), - [&](auto const& lft) { return lft.end > index; }); - if (it == m_data.end()) - return end(); - if (index < it->begin) - return iterator(it, m_data.end(), &it->data[0]); - auto inner_begin = it->data.begin(); - if (it == begin.outer()) - inner_begin += begin.offset(); - auto inner = std::lower_bound(inner_begin, it->data.end(), index, - [&](auto const& lft, auto) { return lft.second <= index; }); - REALM_ASSERT_DEBUG(inner != it->data.end()); - - return iterator(it, m_data.end(), &*inner); -} - -void IndexSet::add(size_t index) -{ - do_add(find(index), index); -} - -void IndexSet::add(IndexSet const& other) -{ - auto it = begin(); - for (size_t index : other.as_indexes()) { - it = do_add(find(index, it), index); - } -} - -size_t IndexSet::add_shifted(size_t index) -{ - iterator it = begin(), end = this->end(); - - // Shift for any complete chunks before the target - for (; it != end && it.outer()->end <= index; it.next_chunk()) - index += it.outer()->count; - - // And any ranges within the last partial chunk - for (; it != end && it->first <= index; ++it) - index += it->second - it->first; - - do_add(it, index); - return index; -} - -void IndexSet::add_shifted_by(IndexSet const& shifted_by, IndexSet const& values) -{ - if (values.empty()) - return; - -#ifdef REALM_DEBUG - size_t expected = std::distance(as_indexes().begin(), as_indexes().end()); - for (auto index : values.as_indexes()) { - if (!shifted_by.contains(index)) - ++expected; - } -#endif - - ChunkedRangeVectorBuilder builder(*this); - - auto old_it = cbegin(), old_end = cend(); - auto shift_it = shifted_by.cbegin(), shift_end = shifted_by.cend(); - - size_t skip_until = 0; - size_t old_shift = 0; - size_t new_shift = 0; - for (size_t index : values.as_indexes()) { - for (; shift_it != shift_end && shift_it->first <= index; ++shift_it) { - new_shift += shift_it->second - shift_it->first; - skip_until = shift_it->second; - } - if (index < skip_until) - continue; - - for (; old_it != old_end && old_it->first <= index - new_shift + old_shift; ++old_it) { - for (size_t i = old_it->first; i < old_it->second; ++i) - builder.push_back(i); - old_shift += old_it->second - old_it->first; - } - - REALM_ASSERT(index >= new_shift); - builder.push_back(index - new_shift + old_shift); - } - - copy(old_it, old_end, std::back_inserter(builder)); - m_data = builder.finalize(); - -#ifdef REALM_DEBUG - REALM_ASSERT((size_t)std::distance(as_indexes().begin(), as_indexes().end()) == expected); -#endif -} - -void IndexSet::set(size_t len) -{ - clear(); - if (len) { - push_back({0, len}); - } -} - -void IndexSet::insert_at(size_t index, size_t count) -{ - REALM_ASSERT(count > 0); - - auto pos = find(index); - auto end = this->end(); - bool in_existing = false; - if (pos != end) { - if (pos->first <= index) { - in_existing = true; - pos.adjust(0, count); - } - else { - pos.shift(count); - } - for (auto it = std::next(pos); it != end; ++it) - it.shift(count); - } - if (!in_existing) { - for (size_t i = 0; i < count; ++i) - pos = std::next(do_add(pos, index + i)); - } - - verify(); -} - -void IndexSet::insert_at(IndexSet const& positions) -{ - if (positions.empty()) - return; - if (empty()) { - *this = positions; - return; - } - - IndexIterator begin1 = cbegin(), begin2 = positions.cbegin(); - IndexIterator end1 = cend(), end2 = positions.cend(); - - ChunkedRangeVectorBuilder builder(*this); - size_t shift = 0; - while (begin1 != end1 && begin2 != end2) { - if (*begin1 + shift < *begin2) { - builder.push_back(*begin1++ + shift); - } - else { - ++shift; - builder.push_back(*begin2++); - } - } - for (; begin1 != end1; ++begin1) - builder.push_back(*begin1 + shift); - for (; begin2 != end2; ++begin2) - builder.push_back(*begin2); - - m_data = builder.finalize(); -} - -void IndexSet::shift_for_insert_at(size_t index, size_t count) -{ - REALM_ASSERT(count > 0); - - auto it = find(index); - if (it == end()) - return; - - for (auto pos = it, end = this->end(); pos != end; ++pos) - pos.shift(count); - - // If the range contained the insertion point, split the range and move - // the part of it before the insertion point back - if (it->first < index + count) { - auto old_second = it->second; - it.set(it->first - count, index); - insert(std::next(it), {index + count, old_second}); - } - verify(); -} - -void IndexSet::shift_for_insert_at(realm::IndexSet const& values) -{ - if (empty() || values.empty()) - return; - if (values.m_data.front().begin >= m_data.back().end) - return; - - IndexIterator begin1 = cbegin(), begin2 = values.cbegin(); - IndexIterator end1 = cend(), end2 = values.cend(); - - ChunkedRangeVectorBuilder builder(*this); - size_t shift = 0; - while (begin1 != end1 && begin2 != end2) { - if (*begin1 + shift < *begin2) { - builder.push_back(*begin1++ + shift); - } - else { - ++shift; - begin2++; - } - } - for (; begin1 != end1; ++begin1) - builder.push_back(*begin1 + shift); - - m_data = builder.finalize(); -} - -void IndexSet::erase_at(size_t index) -{ - auto it = find(index); - if (it != end()) - do_erase(it, index); -} - -void IndexSet::erase_at(IndexSet const& positions) -{ - if (empty() || positions.empty()) - return; - - ChunkedRangeVectorBuilder builder(*this); - - IndexIterator begin1 = cbegin(), begin2 = positions.cbegin(); - IndexIterator end1 = cend(), end2 = positions.cend(); - - size_t shift = 0; - while (begin1 != end1 && begin2 != end2) { - if (*begin1 < *begin2) { - builder.push_back(*begin1++ - shift); - } - else if (*begin1 == *begin2) { - ++shift; - ++begin1; - ++begin2; - } - else { - ++shift; - ++begin2; - } - } - for (; begin1 != end1; ++begin1) - builder.push_back(*begin1 - shift); - - m_data = builder.finalize(); -} - -size_t IndexSet::erase_or_unshift(size_t index) -{ - auto shifted = index; - iterator it = begin(), end = this->end(); - - // Shift for any complete chunks before the target - for (; it != end && it.outer()->end <= index; it.next_chunk()) - shifted -= it.outer()->count; - - // And any ranges within the last partial chunk - for (; it != end && it->second <= index; ++it) - shifted -= it->second - it->first; - - if (it == end) - return shifted; - - if (it->first <= index) - shifted = npos; - - do_erase(it, index); - - return shifted; -} - -void IndexSet::do_erase(iterator it, size_t index) -{ - if (it->first <= index) { - if (it->first + 1 == it->second) { - it = erase(it); - } - else { - it.adjust(0, -1); - ++it; - } - } - else if (it != begin() && std::prev(it)->second + 1 == it->first) { - std::prev(it).adjust(0, it->second - it->first); - it = erase(it); - } - - for (; it != end(); ++it) - it.shift(-1); -} - -IndexSet::iterator IndexSet::do_remove(iterator it, size_t begin, size_t end) -{ - for (it = find(begin, it); it != this->end() && it->first < end; it = find(begin, it)) { - // Trim off any part of the range to remove that's before the matching range - begin = std::max(it->first, begin); - - // If the matching range extends to both sides of the range to remove, - // split it on the range to remove - if (it->first < begin && it->second > end) { - auto old_second = it->second; - it.set(it->first, begin); - it = std::prev(insert(std::next(it), {end, old_second})); - } - // Range to delete now coverages (at least) one end of the matching range - else if (begin == it->first && end >= it->second) - it = erase(it); - else if (begin == it->first) - it.set(end, it->second); - else - it.set(it->first, begin); - } - return it; -} - -void IndexSet::remove(size_t index, size_t count) -{ - do_remove(find(index), index, index + count); -} - -void IndexSet::remove(realm::IndexSet const& values) -{ - auto it = begin(); - for (auto range : values) { - it = do_remove(it, range.first, range.second); - if (it == end()) - return; - } -} - -size_t IndexSet::shift(size_t index) const noexcept -{ - // FIXME: optimize - for (auto range : *this) { - if (range.first > index) - break; - index += range.second - range.first; - } - return index; -} - -size_t IndexSet::unshift(size_t index) const noexcept -{ - REALM_ASSERT_DEBUG(!contains(index)); - return index - count(0, index); -} - -void IndexSet::clear() noexcept -{ - m_data.clear(); -} - -IndexSet::iterator IndexSet::do_add(iterator it, size_t index) -{ - verify(); - bool more_before = it != begin(), valid = it != end(); - REALM_ASSERT(!more_before || index >= std::prev(it)->second); - if (valid && it->first <= index && it->second > index) { - // index is already in set - return it; - } - if (more_before && std::prev(it)->second == index) { - auto prev = std::prev(it); - // index is immediately after an existing range - prev.adjust(0, 1); - - if (valid && prev->second == it->first) { - // index joins two existing ranges - prev.adjust(0, it->second - it->first); - return std::prev(erase(it)); - } - return prev; - } - if (valid && it->first == index + 1) { - // index is immediately before an existing range - it.adjust(-1, 0); - return it; - } - - // index is not next to an existing range - return insert(it, {index, index + 1}); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/list.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/list.cpp deleted file mode 100644 index 12b4082..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/list.cpp +++ /dev/null @@ -1,468 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "list.hpp" - -#include "impl/list_notifier.hpp" -#include "impl/primitive_list_notifier.hpp" -#include "impl/realm_coordinator.hpp" -#include "object_schema.hpp" -#include "object_store.hpp" -#include "results.hpp" -#include "schema.hpp" -#include "shared_realm.hpp" - -#include - -namespace realm { -using namespace realm::_impl; - -List::List() noexcept = default; -List::~List() = default; - -List::List(const List&) = default; -List& List::operator=(const List&) = default; -List::List(List&&) = default; -List& List::operator=(List&&) = default; - -List::List(std::shared_ptr r, Table& parent_table, size_t col, size_t row) -: m_realm(std::move(r)) -{ - auto type = parent_table.get_column_type(col); - REALM_ASSERT(type == type_LinkList || type == type_Table); - if (type == type_LinkList) { - m_link_view = parent_table.get_linklist(col, row); - m_table.reset(&m_link_view->get_target_table()); - } - else { - m_table = parent_table.get_subtable(col, row); - } -} - -List::List(std::shared_ptr r, LinkViewRef l) noexcept -: m_realm(std::move(r)) -, m_link_view(std::move(l)) -{ - m_table.reset(&m_link_view->get_target_table()); -} - -List::List(std::shared_ptr r, TableRef t) noexcept -: m_realm(std::move(r)) -, m_table(std::move(t)) -{ -} - -static StringData object_name(Table const& table) -{ - return ObjectStore::object_type_for_table_name(table.get_name()); -} - -ObjectSchema const& List::get_object_schema() const -{ - verify_attached(); - REALM_ASSERT(m_link_view); - - if (!m_object_schema) { - REALM_ASSERT(get_type() == PropertyType::Object); - auto object_type = object_name(m_link_view->get_target_table()); - auto it = m_realm->schema().find(object_type); - REALM_ASSERT(it != m_realm->schema().end()); - m_object_schema = &*it; - } - return *m_object_schema; -} - -Query List::get_query() const -{ - verify_attached(); - return m_link_view ? m_table->where(m_link_view) : m_table->where(); -} - -size_t List::get_origin_row_index() const -{ - verify_attached(); - return m_link_view ? m_link_view->get_origin_row_index() : m_table->get_parent_row_index(); -} - -void List::verify_valid_row(size_t row_ndx, bool insertion) const -{ - size_t s = size(); - if (row_ndx > s || (!insertion && row_ndx == s)) { - throw OutOfBoundsIndexException{row_ndx, s + insertion}; - } -} - -void List::validate(RowExpr row) const -{ - if (!row.is_attached()) - throw std::invalid_argument("Object has been deleted or invalidated"); - if (row.get_table() != &m_link_view->get_target_table()) - throw std::invalid_argument(util::format("Object of type (%1) does not match List type (%2)", - object_name(*row.get_table()), - object_name(m_link_view->get_target_table()))); -} - -bool List::is_valid() const -{ - if (!m_realm) - return false; - m_realm->verify_thread(); - if (m_link_view) - return m_link_view->is_attached(); - return m_table && m_table->is_attached(); -} - -void List::verify_attached() const -{ - if (!is_valid()) { - throw InvalidatedException(); - } -} - -void List::verify_in_transaction() const -{ - verify_attached(); - m_realm->verify_in_write(); -} - -size_t List::size() const -{ - verify_attached(); - return m_link_view ? m_link_view->size() : m_table->size(); -} - -size_t List::to_table_ndx(size_t row) const noexcept -{ - return m_link_view ? m_link_view->get(row).get_index() : row; -} - -PropertyType List::get_type() const -{ - verify_attached(); - return m_link_view ? PropertyType::Object - : ObjectSchema::from_core_type(*m_table->get_descriptor(), 0); -} - -namespace { -template -auto get(Table& table, size_t row) -{ - return table.get(0, row); -} - -template<> -auto get(Table& table, size_t row) -{ - return table.get(row); -} -} - -template -T List::get(size_t row_ndx) const -{ - verify_valid_row(row_ndx); - return realm::get(*m_table, to_table_ndx(row_ndx)); -} - -template RowExpr List::get(size_t) const; - -template -size_t List::find(T const& value) const -{ - verify_attached(); - return m_table->find_first(0, value); -} - -template<> -size_t List::find(RowExpr const& row) const -{ - verify_attached(); - if (!row.is_attached()) - return not_found; - validate(row); - - return m_link_view ? m_link_view->find(row.get_index()) : row.get_index(); -} - -size_t List::find(Query&& q) const -{ - verify_attached(); - if (m_link_view) { - size_t index = get_query().and_query(std::move(q)).find(); - return index == not_found ? index : m_link_view->find(index); - } - return q.find(); -} - -template -void List::add(T value) -{ - verify_in_transaction(); - m_table->set(0, m_table->add_empty_row(), value); -} - -template<> -void List::add(size_t target_row_ndx) -{ - verify_in_transaction(); - m_link_view->add(target_row_ndx); -} - -template<> -void List::add(RowExpr row) -{ - validate(row); - add(row.get_index()); -} - -template<> -void List::add(int value) -{ - verify_in_transaction(); - if (m_link_view) - add(static_cast(value)); - else - add(static_cast(value)); -} - -template -void List::insert(size_t row_ndx, T value) -{ - verify_in_transaction(); - verify_valid_row(row_ndx, true); - m_table->insert_empty_row(row_ndx); - m_table->set(0, row_ndx, value); -} - -template<> -void List::insert(size_t row_ndx, size_t target_row_ndx) -{ - verify_in_transaction(); - verify_valid_row(row_ndx, true); - m_link_view->insert(row_ndx, target_row_ndx); -} - -template<> -void List::insert(size_t row_ndx, RowExpr row) -{ - validate(row); - insert(row_ndx, row.get_index()); -} - -void List::move(size_t source_ndx, size_t dest_ndx) -{ - verify_in_transaction(); - verify_valid_row(source_ndx); - verify_valid_row(dest_ndx); // Can't be one past end due to removing one earlier - if (source_ndx == dest_ndx) - return; - - if (m_link_view) - m_link_view->move(source_ndx, dest_ndx); - else - m_table->move_row(source_ndx, dest_ndx); -} - -void List::remove(size_t row_ndx) -{ - verify_in_transaction(); - verify_valid_row(row_ndx); - if (m_link_view) - m_link_view->remove(row_ndx); - else - m_table->remove(row_ndx); -} - -void List::remove_all() -{ - verify_in_transaction(); - if (m_link_view) - m_link_view->clear(); - else - m_table->clear(); -} - -template -void List::set(size_t row_ndx, T value) -{ - verify_in_transaction(); - verify_valid_row(row_ndx); - m_table->set(0, row_ndx, value); -} - -template<> -void List::set(size_t row_ndx, size_t target_row_ndx) -{ - verify_in_transaction(); - verify_valid_row(row_ndx); - m_link_view->set(row_ndx, target_row_ndx); -} - -template<> -void List::set(size_t row_ndx, RowExpr row) -{ - validate(row); - set(row_ndx, row.get_index()); -} - -void List::swap(size_t ndx1, size_t ndx2) -{ - verify_in_transaction(); - verify_valid_row(ndx1); - verify_valid_row(ndx2); - if (m_link_view) - m_link_view->swap(ndx1, ndx2); - else - m_table->swap_rows(ndx1, ndx2); -} - -void List::delete_at(size_t row_ndx) -{ - verify_in_transaction(); - verify_valid_row(row_ndx); - if (m_link_view) - m_link_view->remove_target_row(row_ndx); - else - m_table->remove(row_ndx); -} - -void List::delete_all() -{ - verify_in_transaction(); - if (m_link_view) - m_link_view->remove_all_target_rows(); - else - m_table->clear(); -} - -Results List::sort(SortDescriptor order) const -{ - verify_attached(); - if (m_link_view) - return Results(m_realm, m_link_view, util::none, std::move(order)); - - DescriptorOrdering new_order; - new_order.append_sort(std::move(order)); - return Results(m_realm, get_query(), std::move(new_order)); -} - -Results List::sort(std::vector> const& keypaths) const -{ - return as_results().sort(keypaths); -} - -Results List::filter(Query q) const -{ - verify_attached(); - if (m_link_view) - return Results(m_realm, m_link_view, get_query().and_query(std::move(q))); - return Results(m_realm, get_query().and_query(std::move(q))); -} - -Results List::as_results() const -{ - verify_attached(); - return m_link_view ? Results(m_realm, m_link_view) : Results(m_realm, *m_table); -} - -Results List::snapshot() const -{ - return as_results().snapshot(); -} - -util::Optional List::max(size_t column) -{ - return as_results().max(column); -} - -util::Optional List::min(size_t column) -{ - return as_results().min(column); -} - -Mixed List::sum(size_t column) -{ - // Results::sum() returns none only for Mode::Empty Results, so we can - // safely ignore that possibility here - return *as_results().sum(column); -} - -util::Optional List::average(size_t column) -{ - return as_results().average(column); -} - -// These definitions rely on that LinkViews and Tables are interned by core -bool List::operator==(List const& rgt) const noexcept -{ - return m_link_view == rgt.m_link_view && m_table.get() == rgt.m_table.get(); -} - -NotificationToken List::add_notification_callback(CollectionChangeCallback cb) & -{ - verify_attached(); - // Adding a new callback to a notifier which had all of its callbacks - // removed does not properly reinitialize the notifier. Work around this by - // recreating it instead. - // FIXME: The notifier lifecycle here is dumb (when all callbacks are removed - // from a notifier a zombie is left sitting around uselessly) and should be - // cleaned up. - if (m_notifier && !m_notifier->have_callbacks()) - m_notifier.reset(); - if (!m_notifier) { - if (get_type() == PropertyType::Object) - m_notifier = std::static_pointer_cast<_impl::CollectionNotifier>(std::make_shared(m_link_view, m_realm)); - else - m_notifier = std::static_pointer_cast<_impl::CollectionNotifier>(std::make_shared(m_table, m_realm)); - RealmCoordinator::register_notifier(m_notifier); - } - return {m_notifier, m_notifier->add_callback(std::move(cb))}; -} - -List::OutOfBoundsIndexException::OutOfBoundsIndexException(size_t r, size_t c) -: std::out_of_range(util::format("Requested index %1 greater than max %2", r, c - 1)) -, requested(r), valid_count(c) {} - -#define REALM_PRIMITIVE_LIST_TYPE(T) \ - template T List::get(size_t) const; \ - template size_t List::find(T const&) const; \ - template void List::add(T); \ - template void List::insert(size_t, T); \ - template void List::set(size_t, T); - -REALM_PRIMITIVE_LIST_TYPE(bool) -REALM_PRIMITIVE_LIST_TYPE(int64_t) -REALM_PRIMITIVE_LIST_TYPE(float) -REALM_PRIMITIVE_LIST_TYPE(double) -REALM_PRIMITIVE_LIST_TYPE(StringData) -REALM_PRIMITIVE_LIST_TYPE(BinaryData) -REALM_PRIMITIVE_LIST_TYPE(Timestamp) -REALM_PRIMITIVE_LIST_TYPE(util::Optional) -REALM_PRIMITIVE_LIST_TYPE(util::Optional) -REALM_PRIMITIVE_LIST_TYPE(util::Optional) -REALM_PRIMITIVE_LIST_TYPE(util::Optional) - -#undef REALM_PRIMITIVE_LIST_TYPE -} // namespace realm - -namespace std { -size_t hash::operator()(realm::List const& list) const -{ - return std::hash()(list.m_link_view ? list.m_link_view.get() : (void*)list.m_table.get()); -} -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/object.cpp deleted file mode 100644 index 09c165b..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object.cpp +++ /dev/null @@ -1,120 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "object.hpp" - -#include "impl/object_notifier.hpp" -#include "impl/realm_coordinator.hpp" -#include "object_schema.hpp" -#include "object_store.hpp" - -using namespace realm; - -InvalidatedObjectException::InvalidatedObjectException(const std::string& object_type) -: std::logic_error("Accessing object of type " + object_type + " which has been invalidated or deleted") -, object_type(object_type) -{} - -InvalidPropertyException::InvalidPropertyException(const std::string& object_type, const std::string& property_name) -: std::logic_error(util::format("Property '%1.%2' does not exist", object_type, property_name)) -, object_type(object_type), property_name(property_name) -{} - -MissingPropertyValueException::MissingPropertyValueException(const std::string& object_type, const std::string& property_name) -: std::logic_error(util::format("Missing value for property '%1.%2'", object_type, property_name)) -, object_type(object_type), property_name(property_name) -{} - -MissingPrimaryKeyException::MissingPrimaryKeyException(const std::string& object_type) -: std::logic_error(util::format("'%1' does not have a primary key defined", object_type)) -, object_type(object_type) -{} - -ReadOnlyPropertyException::ReadOnlyPropertyException(const std::string& object_type, const std::string& property_name) -: std::logic_error(util::format("Cannot modify read-only property '%1.%2'", object_type, property_name)) -, object_type(object_type), property_name(property_name) {} - -ModifyPrimaryKeyException::ModifyPrimaryKeyException(const std::string& object_type, const std::string& property_name) - : std::logic_error(util::format("Cannot modify primary key after creation: '%1.%2'", object_type, property_name)) - , object_type(object_type), property_name(property_name) {} - -Object::Object(SharedRealm r, ObjectSchema const& s, RowExpr const& o) -: m_realm(std::move(r)), m_object_schema(&s), m_row(o) { } - -Object::Object(SharedRealm r, StringData object_type, size_t ndx) -: m_realm(std::move(r)) -, m_object_schema(&*m_realm->schema().find(object_type)) -, m_row(ObjectStore::table_for_object_type(m_realm->read_group(), object_type)->get(ndx)) -{ } - -Object::Object() = default; -Object::~Object() = default; -Object::Object(Object const&) = default; -Object::Object(Object&&) = default; -Object& Object::operator=(Object const&) = default; -Object& Object::operator=(Object&&) = default; - -NotificationToken Object::add_notification_callback(CollectionChangeCallback callback) & -{ - verify_attached(); - if (!m_notifier) { - m_notifier = std::make_shared<_impl::ObjectNotifier>(m_row, m_realm); - _impl::RealmCoordinator::register_notifier(m_notifier); - } - return {m_notifier, m_notifier->add_callback(std::move(callback))}; -} - -void Object::verify_attached() const -{ - m_realm->verify_thread(); - if (!m_row.is_attached()) { - throw InvalidatedObjectException(m_object_schema->name); - } -} - -Property const& Object::property_for_name(StringData prop_name) const -{ - auto prop = m_object_schema->property_for_name(prop_name); - if (!prop) { - throw InvalidPropertyException(m_object_schema->name, prop_name); - } - return *prop; -} - -#if REALM_ENABLE_SYNC -void Object::ensure_user_in_everyone_role() -{ - auto role_table = m_realm->read_group().get_table("class___Role"); - if (!role_table) - return; - size_t ndx = role_table->find_first_string(role_table->get_column_index("name"), "everyone"); - if (ndx == npos) - return; - auto users = role_table->get_linklist(role_table->get_column_index("members"), ndx); - if (users->find(m_row.get_index()) != not_found) - return; - - users->add(m_row.get_index()); -} - -void Object::ensure_private_role_exists_for_user() -{ - auto user_id = m_row.get(m_row.get_table()->get_column_index("id")); - ObjectStore::ensure_private_role_exists_for_user(m_realm->read_group(), user_id); -} -#endif diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp deleted file mode 100644 index 4e6f4d8..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_schema.cpp +++ /dev/null @@ -1,319 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "object_schema.hpp" - -#include "feature_checks.hpp" -#include "object_store.hpp" -#include "property.hpp" -#include "schema.hpp" - - -#include -#include -#include -#include - -using namespace realm; - -ObjectSchema::ObjectSchema() = default; -ObjectSchema::~ObjectSchema() = default; - -ObjectSchema::ObjectSchema(std::string name, std::initializer_list persisted_properties) -: ObjectSchema(std::move(name), persisted_properties, {}) -{ -} - -ObjectSchema::ObjectSchema(std::string name, std::initializer_list persisted_properties, - std::initializer_list computed_properties) -: name(std::move(name)) -, persisted_properties(persisted_properties) -, computed_properties(computed_properties) -{ - for (auto const& prop : persisted_properties) { - if (prop.is_primary) { - primary_key = prop.name; - break; - } - } -} - -PropertyType ObjectSchema::from_core_type(Descriptor const& table, size_t col) -{ - auto optional = table.is_nullable(col) ? PropertyType::Nullable : PropertyType::Required; - switch (table.get_column_type(col)) { - case type_Int: return PropertyType::Int | optional; - case type_Float: return PropertyType::Float | optional; - case type_Double: return PropertyType::Double | optional; - case type_Bool: return PropertyType::Bool | optional; - case type_String: return PropertyType::String | optional; - case type_Binary: return PropertyType::Data | optional; - case type_Timestamp: return PropertyType::Date | optional; - case type_Mixed: return PropertyType::Any | optional; - case type_Link: return PropertyType::Object | PropertyType::Nullable; - case type_LinkList: return PropertyType::Object | PropertyType::Array; - case type_Table: return from_core_type(*table.get_subdescriptor(col), 0) | PropertyType::Array; - default: REALM_UNREACHABLE(); - } -} - -ObjectSchema::ObjectSchema(Group const& group, StringData name, size_t index) : name(name) { - ConstTableRef table; - if (index < group.size()) { - table = group.get_table(index); - } - else { - table = ObjectStore::table_for_object_type(group, name); - } - - size_t count = table->get_column_count(); - persisted_properties.reserve(count); - for (size_t col = 0; col < count; col++) { - if (auto property = ObjectStore::property_for_column_index(table, col)) { - persisted_properties.push_back(std::move(property.value())); - } - } - - primary_key = realm::ObjectStore::get_primary_key_for_object(group, name); - set_primary_key_property(); -} - -Property *ObjectSchema::property_for_name(StringData name) -{ - for (auto& prop : persisted_properties) { - if (StringData(prop.name) == name) { - return ∝ - } - } - for (auto& prop : computed_properties) { - if (StringData(prop.name) == name) { - return ∝ - } - } - return nullptr; -} - -Property *ObjectSchema::property_for_public_name(StringData public_name) -{ - // If no `public_name` is defined, the internal `name` is also considered the public name. - for (auto& prop : persisted_properties) { - if (prop.public_name == public_name || (prop.public_name.empty() && prop.name == public_name)) - return ∝ - } - - // Computed properties are not persisted, so creating a public name for such properties - // are a bit pointless since the internal name is already the "public name", but since - // this distinction isn't visible in the Property struct we allow it anyway. - for (auto& prop : computed_properties) { - if ((prop.public_name.empty() ? StringData(prop.name) : StringData(prop.public_name)) == public_name) - return ∝ - } - return nullptr; -} - -const Property *ObjectSchema::property_for_public_name(StringData public_name) const -{ - return const_cast(this)->property_for_public_name(public_name); -} - -const Property *ObjectSchema::property_for_name(StringData name) const -{ - return const_cast(this)->property_for_name(name); -} - -bool ObjectSchema::property_is_computed(Property const& property) const -{ - auto end = computed_properties.end(); - return std::find(computed_properties.begin(), end, property) != end; -} - -void ObjectSchema::set_primary_key_property() -{ - if (primary_key.length()) { - if (auto primary_key_prop = primary_key_property()) { - primary_key_prop->is_primary = true; - } - } -} - -static void validate_property(Schema const& schema, - std::string const& object_name, - Property const& prop, - Property const** primary, - std::vector& exceptions) -{ - if (prop.type == PropertyType::LinkingObjects && !is_array(prop.type)) { - exceptions.emplace_back("Linking Objects property '%1.%2' must be an array.", - object_name, prop.name); - } - - // check nullablity - if (is_nullable(prop.type) && !prop.type_is_nullable()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be nullable.", - object_name, prop.name, string_for_property_type(prop.type)); - } - else if (prop.type == PropertyType::Object && !is_nullable(prop.type) && !is_array(prop.type)) { - exceptions.emplace_back("Property '%1.%2' of type 'object' must be nullable.", object_name, prop.name); - } - - // check primary keys - if (prop.is_primary) { - if (prop.type != PropertyType::Int && prop.type != PropertyType::String) { - exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be made the primary key.", - object_name, prop.name, string_for_property_type(prop.type)); - } - if (*primary) { - exceptions.emplace_back("Properties '%1' and '%2' are both marked as the primary key of '%3'.", - prop.name, (*primary)->name, object_name); - } - *primary = ∝ - } - - // check indexable - if (prop.is_indexed && !prop.type_is_indexable()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' cannot be indexed.", - object_name, prop.name, string_for_property_type(prop.type)); - } - - // check that only link properties have object types - if (prop.type != PropertyType::LinkingObjects && !prop.link_origin_property_name.empty()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' cannot have an origin property name.", - object_name, prop.name, string_for_property_type(prop.type)); - } - else if (prop.type == PropertyType::LinkingObjects && prop.link_origin_property_name.empty()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' must have an origin property name.", - object_name, prop.name, string_for_property_type(prop.type)); - } - - if (prop.type != PropertyType::Object && prop.type != PropertyType::LinkingObjects) { - if (!prop.object_type.empty()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' cannot have an object type.", - object_name, prop.name, prop.type_string()); - } - return; - } - - - // check that the object_type is valid for link properties - auto it = schema.find(prop.object_type); - if (it == schema.end()) { - exceptions.emplace_back("Property '%1.%2' of type '%3' has unknown object type '%4'", - object_name, prop.name, string_for_property_type(prop.type), prop.object_type); - return; - } - if (prop.type != PropertyType::LinkingObjects) { - return; - } - - const Property *origin_property = it->property_for_name(prop.link_origin_property_name); - if (!origin_property) { - exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' does not exist", - prop.object_type, prop.link_origin_property_name, - object_name, prop.name); - } - else if (origin_property->type != PropertyType::Object) { - exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' is not a link", - prop.object_type, prop.link_origin_property_name, - object_name, prop.name); - } - else if (origin_property->object_type != object_name) { - exceptions.emplace_back("Property '%1.%2' declared as origin of linking objects property '%3.%4' links to type '%5'", - prop.object_type, prop.link_origin_property_name, - object_name, prop.name, origin_property->object_type); - } -} - -void ObjectSchema::validate(Schema const& schema, std::vector& exceptions) const -{ - std::vector public_property_names; - std::vector internal_property_names; - internal_property_names.reserve(persisted_properties.size() + computed_properties.size()); - auto gather_names = [&](auto const &properties) { - for (auto const &prop : properties) { - internal_property_names.push_back(prop.name); - if (!prop.public_name.empty()) - public_property_names.push_back(prop.public_name); - } - }; - gather_names(persisted_properties); - gather_names(computed_properties); - std::sort(public_property_names.begin(), public_property_names.end()); - std::sort(internal_property_names.begin(), internal_property_names.end()); - - // Check that property names and aliases are unique - auto for_each_duplicate = [](auto &&container, auto &&fn) { - auto end = container.end(); - for (auto it = std::adjacent_find(container.begin(), end); it != end; it = std::adjacent_find(it + 2, end)) - fn(*it); - }; - for_each_duplicate(public_property_names, [&](auto public_property_name) { - exceptions.emplace_back("Alias '%1' appears more than once in the schema for type '%2'.", - public_property_name, name); - }); - for_each_duplicate(internal_property_names, [&](auto internal_name) { - exceptions.emplace_back("Property '%1' appears more than once in the schema for type '%2'.", - internal_name, name); - }); - - // Check that no aliases conflict with property names - struct ErrorWriter { - ObjectSchema const &os; - std::vector &exceptions; - - struct Proxy { - ObjectSchema const &os; - std::vector &exceptions; - - Proxy &operator=(StringData name) { - exceptions.emplace_back( - "Property '%1.%2' has an alias '%3' that conflicts with a property of the same name.", - os.name, os.property_for_public_name(name)->name, name); - return *this; - } - }; - - Proxy operator*() { return Proxy{os, exceptions}; } - ErrorWriter &operator=(const ErrorWriter &) { return *this; } - ErrorWriter &operator++() { return *this; } - ErrorWriter &operator++(int) { return *this; } - } writer{*this, exceptions}; - std::set_intersection(public_property_names.begin(), public_property_names.end(), - internal_property_names.begin(), internal_property_names.end(), writer); - - // Validate all properties - const Property *primary = nullptr; - for (auto const& prop : persisted_properties) { - validate_property(schema, name, prop, &primary, exceptions); - } - for (auto const& prop : computed_properties) { - validate_property(schema, name, prop, &primary, exceptions); - } - - if (!primary_key.empty() && !primary && !primary_key_property()) { - exceptions.emplace_back("Specified primary key '%1.%2' does not exist.", name, primary_key); - } -} - -namespace realm { -bool operator==(ObjectSchema const& a, ObjectSchema const& b) -{ - return std::tie(a.name, a.primary_key, a.persisted_properties, a.computed_properties) - == std::tie(b.name, b.primary_key, b.persisted_properties, b.computed_properties); - -} -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_store.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_store.cpp deleted file mode 100644 index da255c4..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/object_store.cpp +++ /dev/null @@ -1,1044 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "object_store.hpp" - -#include "feature_checks.hpp" -#include "object_schema.hpp" -#include "schema.hpp" -#include "shared_realm.hpp" -#include "sync/partial_sync.hpp" - -#include -#include -#include -#include -#include - -#if REALM_ENABLE_SYNC -#include -#include -#include -#endif // REALM_ENABLE_SYNC - -#include - -using namespace realm; - -constexpr uint64_t ObjectStore::NotVersioned; - -namespace { -const char * const c_metadataTableName = "metadata"; -const char * const c_versionColumnName = "version"; -const size_t c_versionColumnIndex = 0; - -const char * const c_primaryKeyTableName = "pk"; -const char * const c_primaryKeyObjectClassColumnName = "pk_table"; -const size_t c_primaryKeyObjectClassColumnIndex = 0; -const char * const c_primaryKeyPropertyNameColumnName = "pk_property"; -const size_t c_primaryKeyPropertyNameColumnIndex = 1; - -const size_t c_zeroRowIndex = 0; - -const char c_object_table_prefix[] = "class_"; - -void create_metadata_tables(Group& group) { - // The tables 'pk' and 'metadata' are treated specially by Sync. The 'pk' table - // is populated by `sync::create_table` and friends, while the 'metadata' table - // is simply ignored. - TableRef pk_table = group.get_or_add_table(c_primaryKeyTableName); - TableRef metadata_table = group.get_or_add_table(c_metadataTableName); - - if (metadata_table->get_column_count() == 0) { - metadata_table->insert_column(c_versionColumnIndex, type_Int, c_versionColumnName); - metadata_table->add_empty_row(); - // set initial version - metadata_table->set_int(c_versionColumnIndex, c_zeroRowIndex, ObjectStore::NotVersioned); - } - - if (pk_table->get_column_count() == 0) { - pk_table->insert_column(c_primaryKeyObjectClassColumnIndex, type_String, c_primaryKeyObjectClassColumnName); - pk_table->insert_column(c_primaryKeyPropertyNameColumnIndex, type_String, c_primaryKeyPropertyNameColumnName); - } - pk_table->add_search_index(c_primaryKeyObjectClassColumnIndex); -} - -void set_schema_version(Group& group, uint64_t version) { - TableRef table = group.get_table(c_metadataTableName); - table->set_int(c_versionColumnIndex, c_zeroRowIndex, version); -} - -template -auto table_for_object_schema(Group& group, ObjectSchema const& object_schema) -{ - return ObjectStore::table_for_object_type(group, object_schema.name); -} - -DataType to_core_type(PropertyType type) -{ - REALM_ASSERT(type != PropertyType::Object); // Link columns have to be handled differently - REALM_ASSERT(type != PropertyType::Any); // Mixed columns can't be created - switch (type & ~PropertyType::Flags) { - case PropertyType::Int: return type_Int; - case PropertyType::Bool: return type_Bool; - case PropertyType::Float: return type_Float; - case PropertyType::Double: return type_Double; - case PropertyType::String: return type_String; - case PropertyType::Date: return type_Timestamp; - case PropertyType::Data: return type_Binary; - default: REALM_COMPILER_HINT_UNREACHABLE(); - } -} - -void insert_column(Group& group, Table& table, Property const& property, size_t col_ndx) -{ - // Cannot directly insert a LinkingObjects column (a computed property). - // LinkingObjects must be an artifact of an existing link column. - REALM_ASSERT(property.type != PropertyType::LinkingObjects); - - if (property.type == PropertyType::Object) { - auto target_name = ObjectStore::table_name_for_object_type(property.object_type); - TableRef link_table = group.get_table(target_name); - REALM_ASSERT(link_table); - table.insert_column_link(col_ndx, is_array(property.type) ? type_LinkList : type_Link, - property.name, *link_table); - } - else if (is_array(property.type)) { - DescriptorRef desc; - table.insert_column(col_ndx, type_Table, property.name, &desc); - desc->add_column(to_core_type(property.type & ~PropertyType::Flags), ObjectStore::ArrayColumnName, - nullptr, is_nullable(property.type)); - } - else { - table.insert_column(col_ndx, to_core_type(property.type), property.name, is_nullable(property.type)); - if (property.requires_index()) - table.add_search_index(col_ndx); - } -} - -void add_column(Group& group, Table& table, Property const& property) -{ - insert_column(group, table, property, table.get_column_count()); -} - -void replace_column(Group& group, Table& table, Property const& old_property, Property const& new_property) -{ - insert_column(group, table, new_property, old_property.table_column); - table.remove_column(old_property.table_column + 1); -} - -TableRef create_table(Group& group, ObjectSchema const& object_schema) -{ - auto name = ObjectStore::table_name_for_object_type(object_schema.name); - - TableRef table; -#if REALM_ENABLE_SYNC - if (auto* pk_property = object_schema.primary_key_property()) { - table = sync::create_table_with_primary_key(group, name, to_core_type(pk_property->type), - pk_property->name, is_nullable(pk_property->type)); - } - else { - table = sync::create_table(group, name); - } -#else - table = group.get_or_add_table(name); - ObjectStore::set_primary_key_for_object(group, object_schema.name, object_schema.primary_key); -#endif // REALM_ENABLE_SYNC - - return table; -} - -void add_initial_columns(Group& group, ObjectSchema const& object_schema) -{ - auto name = ObjectStore::table_name_for_object_type(object_schema.name); - TableRef table = group.get_table(name); - - for (auto const& prop : object_schema.persisted_properties) { -#if REALM_ENABLE_SYNC - // The sync::create_table* functions create the PK column for us. - if (prop.is_primary) - continue; -#endif // REALM_ENABLE_SYNC - add_column(group, *table, prop); - } -} - -void copy_property_values(Property const& prop, Table& table) -{ - auto copy_property_values = [&](auto getter, auto setter) { - for (size_t i = 0, count = table.size(); i < count; i++) { - bool is_default = false; - (table.*setter)(prop.table_column, i, (table.*getter)(prop.table_column + 1, i), - is_default); - } - }; - - switch (prop.type & ~PropertyType::Flags) { - case PropertyType::Int: - copy_property_values(&Table::get_int, &Table::set_int); - break; - case PropertyType::Bool: - copy_property_values(&Table::get_bool, &Table::set_bool); - break; - case PropertyType::Float: - copy_property_values(&Table::get_float, &Table::set_float); - break; - case PropertyType::Double: - copy_property_values(&Table::get_double, &Table::set_double); - break; - case PropertyType::String: - copy_property_values(&Table::get_string, &Table::set_string); - break; - case PropertyType::Data: - copy_property_values(&Table::get_binary, &Table::set_binary); - break; - case PropertyType::Date: - copy_property_values(&Table::get_timestamp, &Table::set_timestamp); - break; - default: - break; - } -} - -void make_property_optional(Group& group, Table& table, Property property) -{ - property.type |= PropertyType::Nullable; - insert_column(group, table, property, property.table_column); - copy_property_values(property, table); - table.remove_column(property.table_column + 1); -} - -void make_property_required(Group& group, Table& table, Property property) -{ - property.type &= ~PropertyType::Nullable; - insert_column(group, table, property, property.table_column); - table.remove_column(property.table_column + 1); -} - -void validate_primary_column_uniqueness(Group const& group, StringData object_type, StringData primary_property) -{ - auto table = ObjectStore::table_for_object_type(group, object_type); - if (table->get_distinct_view(table->get_column_index(primary_property)).size() != table->size()) { - throw DuplicatePrimaryKeyValueException(object_type, primary_property); - } -} - -void validate_primary_column_uniqueness(Group const& group) -{ - auto pk_table = group.get_table(c_primaryKeyTableName); - for (size_t i = 0, count = pk_table->size(); i < count; ++i) { - validate_primary_column_uniqueness(group, - pk_table->get_string(c_primaryKeyObjectClassColumnIndex, i), - pk_table->get_string(c_primaryKeyPropertyNameColumnIndex, i)); - } -} -} // anonymous namespace - -void ObjectStore::set_schema_version(Group& group, uint64_t version) { - ::create_metadata_tables(group); - ::set_schema_version(group, version); -} - -uint64_t ObjectStore::get_schema_version(Group const& group) { - ConstTableRef table = group.get_table(c_metadataTableName); - if (!table || table->get_column_count() == 0) { - return ObjectStore::NotVersioned; - } - return table->get_int(c_versionColumnIndex, c_zeroRowIndex); -} - -StringData ObjectStore::get_primary_key_for_object(Group const& group, StringData object_type) { - ConstTableRef table = group.get_table(c_primaryKeyTableName); - if (!table) { - return ""; - } - size_t row = table->find_first_string(c_primaryKeyObjectClassColumnIndex, object_type); - if (row == not_found) { - return ""; - } - return table->get_string(c_primaryKeyPropertyNameColumnIndex, row); -} - -void ObjectStore::set_primary_key_for_object(Group& group, StringData object_type, StringData primary_key) { - TableRef table = group.get_table(c_primaryKeyTableName); - - size_t row = table->find_first_string(c_primaryKeyObjectClassColumnIndex, object_type); - -#if REALM_ENABLE_SYNC - // sync::create_table* functions should have already updated the pk table. - if (sync::has_object_ids(group)) { - if (primary_key.size() == 0) - REALM_ASSERT(row == not_found); - else { - REALM_ASSERT(row != not_found); - REALM_ASSERT(table->get_string(c_primaryKeyPropertyNameColumnIndex, row) == primary_key); - } - return; - } -#endif // REALM_ENABLE_SYNC - - if (row == not_found && primary_key.size()) { - row = table->add_empty_row(); - table->set_string_unique(c_primaryKeyObjectClassColumnIndex, row, object_type); - table->set_string(c_primaryKeyPropertyNameColumnIndex, row, primary_key); - return; - } - // set if changing, or remove if setting to nil - if (primary_key.size() == 0) { - if (row != not_found) { - table->move_last_over(row); - } - } - else { - table->set_string(c_primaryKeyPropertyNameColumnIndex, row, primary_key); - } -} - -StringData ObjectStore::object_type_for_table_name(StringData table_name) { - if (table_name.begins_with(c_object_table_prefix)) { - return table_name.substr(sizeof(c_object_table_prefix) - 1); - } - return StringData(); -} - -std::string ObjectStore::table_name_for_object_type(StringData object_type) { - return std::string(c_object_table_prefix) + std::string(object_type); -} - -TableRef ObjectStore::table_for_object_type(Group& group, StringData object_type) { - auto name = table_name_for_object_type(object_type); - return group.get_table(name); -} - -ConstTableRef ObjectStore::table_for_object_type(Group const& group, StringData object_type) { - auto name = table_name_for_object_type(object_type); - return group.get_table(name); -} - -namespace { -struct SchemaDifferenceExplainer { - std::vector errors; - - void operator()(schema_change::AddTable op) - { - errors.emplace_back("Class '%1' has been added.", op.object->name); - } - - void operator()(schema_change::RemoveTable) - { - // We never do anything for RemoveTable - } - - void operator()(schema_change::AddInitialProperties) - { - // Nothing. Always preceded by AddTable. - } - - void operator()(schema_change::AddProperty op) - { - errors.emplace_back("Property '%1.%2' has been added.", op.object->name, op.property->name); - } - - void operator()(schema_change::RemoveProperty op) - { - errors.emplace_back("Property '%1.%2' has been removed.", op.object->name, op.property->name); - } - - void operator()(schema_change::ChangePropertyType op) - { - errors.emplace_back("Property '%1.%2' has been changed from '%3' to '%4'.", - op.object->name, op.new_property->name, - op.old_property->type_string(), - op.new_property->type_string()); - } - - void operator()(schema_change::MakePropertyNullable op) - { - errors.emplace_back("Property '%1.%2' has been made optional.", op.object->name, op.property->name); - } - - void operator()(schema_change::MakePropertyRequired op) - { - errors.emplace_back("Property '%1.%2' has been made required.", op.object->name, op.property->name); - } - - void operator()(schema_change::ChangePrimaryKey op) - { - if (op.property && !op.object->primary_key.empty()) { - errors.emplace_back("Primary Key for class '%1' has changed from '%2' to '%3'.", - op.object->name, op.object->primary_key, op.property->name); - } - else if (op.property) { - errors.emplace_back("Primary Key for class '%1' has been added.", op.object->name); - } - else { - errors.emplace_back("Primary Key for class '%1' has been removed.", op.object->name); - } - } - - void operator()(schema_change::AddIndex op) - { - errors.emplace_back("Property '%1.%2' has been made indexed.", op.object->name, op.property->name); - } - - void operator()(schema_change::RemoveIndex op) - { - errors.emplace_back("Property '%1.%2' has been made unindexed.", op.object->name, op.property->name); - } -}; - -class TableHelper { -public: - TableHelper(Group& g) : m_group(g) { } - - Table& operator()(const ObjectSchema* object_schema) - { - if (object_schema != m_current_object_schema) { - m_current_table = table_for_object_schema(m_group, *object_schema); - m_current_object_schema = object_schema; - } - REALM_ASSERT(m_current_table); - return *m_current_table; - } - -private: - Group& m_group; - const ObjectSchema* m_current_object_schema = nullptr; - TableRef m_current_table; -}; - -template -void verify_no_errors(Verifier&& verifier, std::vector const& changes) -{ - for (auto& change : changes) { - change.visit(verifier); - } - - if (!verifier.errors.empty()) { - throw ErrorType(verifier.errors); - } -} -} // anonymous namespace - -bool ObjectStore::needs_migration(std::vector const& changes) -{ - using namespace schema_change; - struct Visitor { - bool operator()(AddIndex) { return false; } - bool operator()(AddInitialProperties) { return false; } - bool operator()(AddProperty) { return true; } - bool operator()(AddTable) { return false; } - bool operator()(RemoveTable) { return false; } - bool operator()(ChangePrimaryKey) { return true; } - bool operator()(ChangePropertyType) { return true; } - bool operator()(MakePropertyNullable) { return true; } - bool operator()(MakePropertyRequired) { return true; } - bool operator()(RemoveIndex) { return false; } - bool operator()(RemoveProperty) { return true; } - }; - - return std::any_of(begin(changes), end(changes), - [](auto&& change) { return change.visit(Visitor()); }); -} - -void ObjectStore::verify_no_changes_required(std::vector const& changes) -{ - verify_no_errors(SchemaDifferenceExplainer(), changes); -} - -void ObjectStore::verify_no_migration_required(std::vector const& changes) -{ - using namespace schema_change; - struct Verifier : SchemaDifferenceExplainer { - using SchemaDifferenceExplainer::operator(); - - // Adding a table or adding/removing indexes can be done automatically. - // All other changes require migrations. - void operator()(AddTable) { } - void operator()(AddInitialProperties) { } - void operator()(AddIndex) { } - void operator()(RemoveIndex) { } - } verifier; - verify_no_errors(verifier, changes); -} - -bool ObjectStore::verify_valid_additive_changes(std::vector const& changes, bool update_indexes) -{ - using namespace schema_change; - struct Verifier : SchemaDifferenceExplainer { - using SchemaDifferenceExplainer::operator(); - - bool index_changes = false; - bool other_changes = false; - - // Additive mode allows adding things, extra columns, and adding/removing indexes - void operator()(AddTable) { other_changes = true; } - void operator()(AddInitialProperties) { other_changes = true; } - void operator()(AddProperty) { other_changes = true; } - void operator()(RemoveProperty) { } - void operator()(AddIndex) { index_changes = true; } - void operator()(RemoveIndex) { index_changes = true; } - } verifier; - verify_no_errors(verifier, changes); - return verifier.other_changes || (verifier.index_changes && update_indexes); -} - -void ObjectStore::verify_valid_external_changes(std::vector const& changes) -{ - using namespace schema_change; - struct Verifier : SchemaDifferenceExplainer { - using SchemaDifferenceExplainer::operator(); - - // Adding new things is fine - void operator()(AddTable) { } - void operator()(AddInitialProperties) { } - void operator()(AddProperty) { } - void operator()(AddIndex) { } - void operator()(RemoveIndex) { } - - // Deleting tables is not okay - void operator()(RemoveTable op) { - errors.emplace_back("Class '%1' has been removed.", op.object->name); - } - } verifier; - verify_no_errors(verifier, changes); -} - -void ObjectStore::verify_compatible_for_immutable_and_readonly(std::vector const& changes) -{ - using namespace schema_change; - struct Verifier : SchemaDifferenceExplainer { - using SchemaDifferenceExplainer::operator(); - - void operator()(AddTable) { } - void operator()(AddInitialProperties) { } - void operator()(RemoveProperty) { } - void operator()(AddIndex) { } - void operator()(RemoveIndex) { } - } verifier; - verify_no_errors(verifier, changes); -} - -static void apply_non_migration_changes(Group& group, std::vector const& changes) -{ - using namespace schema_change; - struct Applier : SchemaDifferenceExplainer { - Applier(Group& group) : group{group}, table{group} { } - Group& group; - TableHelper table; - - // Produce an exception listing the unsupported schema changes for - // everything but the explicitly supported ones - using SchemaDifferenceExplainer::operator(); - - void operator()(AddTable op) { create_table(group, *op.object); } - void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } - void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } - void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } - } applier{group}; - verify_no_errors(applier, changes); -} - -static void create_initial_tables(Group& group, std::vector const& changes) -{ - using namespace schema_change; - struct Applier { - Applier(Group& group) : group{group}, table{group} { } - Group& group; - TableHelper table; - - void operator()(AddTable op) { create_table(group, *op.object); } - void operator()(RemoveTable) { } - void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } - - // Note that in normal operation none of these will be hit, as if we're - // creating the initial tables there shouldn't be anything to update. - // Implementing these makes us better able to handle weird - // not-quite-correct files produced by other things and has no obvious - // downside. - void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } - void operator()(RemoveProperty op) { table(op.object).remove_column(op.property->table_column); } - void operator()(MakePropertyNullable op) { make_property_optional(group, table(op.object), *op.property); } - void operator()(MakePropertyRequired op) { make_property_required(group, table(op.object), *op.property); } - void operator()(ChangePrimaryKey op) { ObjectStore::set_primary_key_for_object(group, op.object->name, op.property ? StringData{op.property->name} : ""); } - void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } - void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } - - void operator()(ChangePropertyType op) - { - replace_column(group, table(op.object), *op.old_property, *op.new_property); - } - } applier{group}; - - for (auto& change : changes) { - change.visit(applier); - } -} - -void ObjectStore::apply_additive_changes(Group& group, std::vector const& changes, bool update_indexes) -{ - using namespace schema_change; - struct Applier { - Applier(Group& group, bool update_indexes) - : group{group}, table{group}, update_indexes{update_indexes} { } - Group& group; - TableHelper table; - bool update_indexes; - - void operator()(AddTable op) { create_table(group, *op.object); } - void operator()(RemoveTable) { } - void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } - void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } - void operator()(AddIndex op) { if (update_indexes) table(op.object).add_search_index(op.property->table_column); } - void operator()(RemoveIndex op) { if (update_indexes) table(op.object).remove_search_index(op.property->table_column); } - void operator()(RemoveProperty) { } - - // No need for errors for these, as we've already verified that they aren't present - void operator()(ChangePrimaryKey) { } - void operator()(ChangePropertyType) { } - void operator()(MakePropertyNullable) { } - void operator()(MakePropertyRequired) { } - } applier{group, update_indexes}; - - for (auto& change : changes) { - change.visit(applier); - } -} - -static void apply_pre_migration_changes(Group& group, std::vector const& changes) -{ - using namespace schema_change; - struct Applier { - Applier(Group& group) : group{group}, table{group} { } - Group& group; - TableHelper table; - - void operator()(AddTable op) { create_table(group, *op.object); } - void operator()(RemoveTable) { } - void operator()(AddInitialProperties op) { add_initial_columns(group, *op.object); } - void operator()(AddProperty op) { add_column(group, table(op.object), *op.property); } - void operator()(RemoveProperty) { /* delayed until after the migration */ } - void operator()(ChangePropertyType op) { replace_column(group, table(op.object), *op.old_property, *op.new_property); } - void operator()(MakePropertyNullable op) { make_property_optional(group, table(op.object), *op.property); } - void operator()(MakePropertyRequired op) { make_property_required(group, table(op.object), *op.property); } - void operator()(ChangePrimaryKey op) { ObjectStore::set_primary_key_for_object(group, op.object->name.c_str(), op.property ? op.property->name.c_str() : ""); } - void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } - void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } - } applier{group}; - - for (auto& change : changes) { - change.visit(applier); - } -} - -enum class DidRereadSchema { Yes, No }; - -static void apply_post_migration_changes(Group& group, std::vector const& changes, Schema const& initial_schema, - DidRereadSchema did_reread_schema) -{ - using namespace schema_change; - struct Applier { - Applier(Group& group, Schema const& initial_schema, DidRereadSchema did_reread_schema) - : group{group}, initial_schema(initial_schema), table(group) - , did_reread_schema(did_reread_schema == DidRereadSchema::Yes) - { } - Group& group; - Schema const& initial_schema; - TableHelper table; - bool did_reread_schema; - - void operator()(RemoveProperty op) - { - if (!initial_schema.empty() && !initial_schema.find(op.object->name)->property_for_name(op.property->name)) - throw std::logic_error(util::format("Renamed property '%1.%2' does not exist.", op.object->name, op.property->name)); - auto table = table_for_object_schema(group, *op.object); - table->remove_column(op.property->table_column); - } - - void operator()(ChangePrimaryKey op) - { - if (op.property) { - validate_primary_column_uniqueness(group, op.object->name, op.property->name); - } - } - - void operator()(AddTable op) { create_table(group, *op.object); } - - void operator()(AddInitialProperties op) { - if (did_reread_schema) - add_initial_columns(group, *op.object); - else { - // If we didn't re-read the schema then AddInitialProperties was already taken care of - // during apply_pre_migration_changes. - } - } - - void operator()(AddIndex op) { table(op.object).add_search_index(op.property->table_column); } - void operator()(RemoveIndex op) { table(op.object).remove_search_index(op.property->table_column); } - - void operator()(RemoveTable) { } - void operator()(ChangePropertyType) { } - void operator()(MakePropertyNullable) { } - void operator()(MakePropertyRequired) { } - void operator()(AddProperty) { } - } applier{group, initial_schema, did_reread_schema}; - - for (auto& change : changes) { - change.visit(applier); - } -} - -static void create_default_permissions(Group& group, std::vector const& changes, - std::string const& sync_user_id) -{ -#if !REALM_ENABLE_SYNC - static_cast(group); - static_cast(changes); - static_cast(sync_user_id); -#else - _impl::initialize_schema(group); - sync::set_up_basic_permissions(group, true); - - // Ensure that this user exists so that local privileges checks work immediately - sync::add_user_to_role(group, sync_user_id, "everyone"); - - // Ensure that the user's private role exists so that local privilege checks work immediately. - ObjectStore::ensure_private_role_exists_for_user(group, sync_user_id); - - // Mark all tables we just created as fully world-accessible - // This has to be done after the first pass of schema init is done so that we can be - // sure that the permissions tables actually exist. - using namespace schema_change; - struct Applier { - Group& group; - void operator()(AddTable op) - { - sync::set_class_permissions_for_role(group, op.object->name, "everyone", - static_cast(ComputedPrivileges::All)); - } - - void operator()(RemoveTable) { } - void operator()(AddInitialProperties) { } - void operator()(AddProperty) { } - void operator()(RemoveProperty) { } - void operator()(MakePropertyNullable) { } - void operator()(MakePropertyRequired) { } - void operator()(ChangePrimaryKey) { } - void operator()(AddIndex) { } - void operator()(RemoveIndex) { } - void operator()(ChangePropertyType) { } - } applier{group}; - - for (auto& change : changes) { - change.visit(applier); - } -#endif -} - -#if REALM_ENABLE_SYNC -void ObjectStore::ensure_private_role_exists_for_user(Group& group, StringData sync_user_id) -{ - std::string private_role_name = util::format("__User:%1", sync_user_id); - - TableRef roles = ObjectStore::table_for_object_type(group, "__Role"); - size_t private_role_ndx = roles->find_first_string(roles->get_column_index("name"), private_role_name); - if (private_role_ndx != npos) { - // The private role already exists, so there's nothing for us to do. - return; - } - - // Add the user to the private role, creating the private role in the process. - sync::add_user_to_role(group, sync_user_id, private_role_name); - - // Set the private role on the user. - private_role_ndx = roles->find_first_string(roles->get_column_index("name"), private_role_name); - TableRef users = ObjectStore::table_for_object_type(group, "__User"); - size_t user_ndx = users->find_first_string(users->get_column_index("id"), sync_user_id); - users->set_link(users->get_column_index("role"), user_ndx, private_role_ndx); -} -#endif - -void ObjectStore::apply_schema_changes(Group& group, uint64_t schema_version, - Schema& target_schema, uint64_t target_schema_version, - SchemaMode mode, std::vector const& changes, - util::Optional sync_user_id, - std::function migration_function) -{ - create_metadata_tables(group); - - if (mode == SchemaMode::Additive) { - bool target_schema_is_newer = (schema_version < target_schema_version - || schema_version == ObjectStore::NotVersioned); - - // With sync v2.x, indexes are no longer synced, so there's no reason to avoid creating them. - bool update_indexes = true; - apply_additive_changes(group, changes, update_indexes); - - if (target_schema_is_newer) - set_schema_version(group, target_schema_version); - - if (sync_user_id) - create_default_permissions(group, changes, *sync_user_id); - - set_schema_columns(group, target_schema); - return; - } - - if (schema_version == ObjectStore::NotVersioned) { - create_initial_tables(group, changes); - set_schema_version(group, target_schema_version); - set_schema_columns(group, target_schema); - return; - } - - if (mode == SchemaMode::Manual) { - set_schema_columns(group, target_schema); - if (migration_function) { - migration_function(); - } - - verify_no_changes_required(schema_from_group(group).compare(target_schema)); - validate_primary_column_uniqueness(group); - set_schema_columns(group, target_schema); - set_schema_version(group, target_schema_version); - return; - } - - if (schema_version == target_schema_version) { - apply_non_migration_changes(group, changes); - set_schema_columns(group, target_schema); - return; - } - - auto old_schema = schema_from_group(group); - apply_pre_migration_changes(group, changes); - if (migration_function) { - set_schema_columns(group, target_schema); - migration_function(); - - // Migration function may have changed the schema, so we need to re-read it - auto schema = schema_from_group(group); - apply_post_migration_changes(group, schema.compare(target_schema), old_schema, DidRereadSchema::Yes); - validate_primary_column_uniqueness(group); - } - else { - apply_post_migration_changes(group, changes, {}, DidRereadSchema::No); - } - - set_schema_version(group, target_schema_version); - set_schema_columns(group, target_schema); -} - -Schema ObjectStore::schema_from_group(Group const& group) { - std::vector schema; - schema.reserve(group.size()); - for (size_t i = 0; i < group.size(); i++) { - auto object_type = object_type_for_table_name(group.get_table_name(i)); - if (object_type.size()) { - schema.emplace_back(group, object_type, i); - } - } - return schema; -} - -util::Optional ObjectStore::property_for_column_index(ConstTableRef& table, size_t column_index) -{ - StringData column_name = table->get_column_name(column_index); - -#if REALM_ENABLE_SYNC - // The object ID column is an implementation detail, and is omitted from the schema. - // FIXME: Consider filtering out all column names starting with `!`. - if (column_name == sync::object_id_column_name) - return util::none; -#endif - - if (table->get_column_type(column_index) == type_Table) { - auto subdesc = table->get_subdescriptor(column_index); - if (subdesc->get_column_count() != 1 || subdesc->get_column_name(0) != ObjectStore::ArrayColumnName) - return util::none; - } - - Property property; - property.name = column_name; - property.type = ObjectSchema::from_core_type(*table->get_descriptor(), column_index); - property.is_indexed = table->has_search_index(column_index); - property.table_column = column_index; - - if (property.type == PropertyType::Object) { - // set link type for objects and arrays - ConstTableRef linkTable = table->get_link_target(column_index); - property.object_type = ObjectStore::object_type_for_table_name(linkTable->get_name().data()); - } - return property; -} - -void ObjectStore::set_schema_columns(Group const& group, Schema& schema) -{ - for (auto& object_schema : schema) { - auto table = table_for_object_schema(group, object_schema); - if (!table) { - continue; - } - for (auto& property : object_schema.persisted_properties) { - property.table_column = table->get_column_index(property.name); - } - } -} - -void ObjectStore::delete_data_for_object(Group& group, StringData object_type) { - if (TableRef table = table_for_object_type(group, object_type)) { - group.remove_table(table->get_index_in_group()); - ObjectStore::set_primary_key_for_object(group, object_type, ""); - } -} - -bool ObjectStore::is_empty(Group const& group) { - for (size_t i = 0; i < group.size(); i++) { - ConstTableRef table = group.get_table(i); - auto object_type = object_type_for_table_name(table->get_name()); - if (object_type.size() == 0 || object_type.begins_with("__")) { - continue; - } - if (!table->is_empty()) { - return false; - } - } - return true; -} - -void ObjectStore::rename_property(Group& group, Schema& target_schema, StringData object_type, StringData old_name, StringData new_name) -{ - TableRef table = table_for_object_type(group, object_type); - if (!table) { - throw std::logic_error(util::format("Cannot rename properties for type '%1' because it does not exist.", object_type)); - } - - auto target_object_schema = target_schema.find(object_type); - if (target_object_schema == target_schema.end()) { - throw std::logic_error(util::format("Cannot rename properties for type '%1' because it has been removed from the Realm.", object_type)); - } - - if (target_object_schema->property_for_name(old_name)) { - throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because the source property still exists.", - object_type, old_name, new_name)); - } - - ObjectSchema table_object_schema(group, object_type); - Property *old_property = table_object_schema.property_for_name(old_name); - if (!old_property) { - throw std::logic_error(util::format("Cannot rename property '%1.%2' because it does not exist.", object_type, old_name)); - } - - Property *new_property = table_object_schema.property_for_name(new_name); - if (!new_property) { - // New property doesn't exist in the table, which means we're probably - // renaming to an intermediate property in a multi-version migration. - // This is safe because the migration will fail schema validation unless - // this property is renamed again to a valid name before the end. - table->rename_column(old_property->table_column, new_name); - return; - } - - if (old_property->type != new_property->type || old_property->object_type != new_property->object_type) { - throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because it would change from type '%4' to '%5'.", - object_type, old_name, new_name, old_property->type_string(), new_property->type_string())); - } - - if (is_nullable(old_property->type) && !is_nullable(new_property->type)) { - throw std::logic_error(util::format("Cannot rename property '%1.%2' to '%3' because it would change from optional to required.", - object_type, old_name, new_name)); - } - - size_t column_to_remove = new_property->table_column; - table->rename_column(old_property->table_column, new_name); - table->remove_column(column_to_remove); - - // update table_column for each property since it may have shifted - for (auto& current_prop : target_object_schema->persisted_properties) { - if (current_prop.table_column == column_to_remove) - current_prop.table_column = old_property->table_column; - else if (current_prop.table_column > column_to_remove) - --current_prop.table_column; - } - - // update nullability for column - if (is_nullable(new_property->type) && !is_nullable(old_property->type)) { - auto prop = *new_property; - prop.table_column = old_property->table_column; - make_property_optional(group, *table, prop); - } -} - -InvalidSchemaVersionException::InvalidSchemaVersionException(uint64_t old_version, uint64_t new_version) -: logic_error(util::format("Provided schema version %1 is less than last set version %2.", new_version, old_version)) -, m_old_version(old_version), m_new_version(new_version) -{ -} - -DuplicatePrimaryKeyValueException::DuplicatePrimaryKeyValueException(std::string object_type, std::string property) -: logic_error(util::format("Primary key property '%1.%2' has duplicate values after migration.", object_type, property)) -, m_object_type(object_type), m_property(property) -{ -} - -SchemaValidationException::SchemaValidationException(std::vector const& errors) -: std::logic_error([&] { - std::string message = "Schema validation failed due to the following errors:"; - for (auto const& error : errors) { - message += std::string("\n- ") + error.what(); - } - return message; -}()) -{ -} - -SchemaMismatchException::SchemaMismatchException(std::vector const& errors) -: std::logic_error([&] { - std::string message = "Migration is required due to the following errors:"; - for (auto const& error : errors) { - message += std::string("\n- ") + error.what(); - } - return message; -}()) -{ -} - -InvalidSchemaChangeException::InvalidSchemaChangeException(std::vector const& errors) -: std::logic_error([&] { - std::string message = "The following changes cannot be made in additive-only schema mode:"; - for (auto const& error : errors) { - message += std::string("\n- ") + error.what(); - } - return message; -}()) -{ -} - -InvalidExternalSchemaChangeException::InvalidExternalSchemaChangeException(std::vector const& errors) -: std::logic_error([&] { - std::string message = - "Unsupported schema changes were made by another client or process. For a " - "synchronized Realm, this may be due to the server reverting schema changes which " - "the local user did not have permission to make."; - for (auto const& error : errors) { - message += std::string("\n- ") + error.what(); - } - return message; -}()) -{ -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp deleted file mode 100644 index 8936534..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/placeholder.cpp +++ /dev/null @@ -1 +0,0 @@ -// This file is intentionally left blank. diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/results.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/results.cpp deleted file mode 100644 index 15c21f2..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/results.cpp +++ /dev/null @@ -1,836 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "results.hpp" - -#include "impl/realm_coordinator.hpp" -#include "impl/results_notifier.hpp" -#include "audit.hpp" -#include "object_schema.hpp" -#include "object_store.hpp" -#include "schema.hpp" - -#include - -namespace realm { - -Results::Results() = default; -Results::~Results() = default; - -Results::Results(SharedRealm r, Query q, DescriptorOrdering o) -: m_realm(std::move(r)) -, m_query(std::move(q)) -, m_table(m_query.get_table()) -, m_descriptor_ordering(std::move(o)) -, m_mode(Mode::Query) -{ -} - -Results::Results(SharedRealm r, Table& table) -: m_realm(std::move(r)) -, m_mode(Mode::Table) -{ - m_table.reset(&table); -} - -Results::Results(SharedRealm r, LinkViewRef lv, util::Optional q, SortDescriptor s) -: m_realm(std::move(r)) -, m_link_view(lv) -, m_mode(Mode::LinkView) -{ - m_table.reset(&lv->get_target_table()); - if (q) { - m_query = std::move(*q); - m_mode = Mode::Query; - } - m_descriptor_ordering.append_sort(std::move(s)); -} - -Results::Results(SharedRealm r, TableView tv, DescriptorOrdering o) -: m_realm(std::move(r)) -, m_table_view(std::move(tv)) -, m_descriptor_ordering(std::move(o)) -, m_mode(Mode::TableView) -{ - m_table.reset(&m_table_view.get_parent()); -} - -Results::Results(const Results&) = default; -Results& Results::operator=(const Results&) = default; - -Results::Results(Results&& other) -: m_realm(std::move(other.m_realm)) -, m_object_schema(std::move(other.m_object_schema)) -, m_query(std::move(other.m_query)) -, m_table_view(std::move(other.m_table_view)) -, m_link_view(std::move(other.m_link_view)) -, m_table(std::move(other.m_table)) -, m_descriptor_ordering(std::move(other.m_descriptor_ordering)) -, m_notifier(std::move(other.m_notifier)) -, m_mode(other.m_mode) -, m_update_policy(other.m_update_policy) -, m_has_used_table_view(other.m_has_used_table_view) -, m_wants_background_updates(other.m_wants_background_updates) -{ - if (m_notifier) { - m_notifier->target_results_moved(other, *this); - } -} - -Results& Results::operator=(Results&& other) -{ - this->~Results(); - new (this) Results(std::move(other)); - return *this; -} - -bool Results::is_valid() const -{ - if (m_realm) - m_realm->verify_thread(); - - if (m_table && !m_table->is_attached()) - return false; - - return true; -} - -void Results::validate_read() const -{ - // is_valid ensures that we're on the correct thread. - if (!is_valid()) - throw InvalidatedException(); -} - -void Results::validate_write() const -{ - validate_read(); - if (!m_realm || !m_realm->is_in_transaction()) - throw InvalidTransactionException("Must be in a write transaction"); -} - -size_t Results::size() -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: return 0; - case Mode::Table: return m_table->size(); - case Mode::LinkView: return m_link_view->size(); - case Mode::Query: - m_query.sync_view_if_needed(); - if (!m_descriptor_ordering.will_apply_distinct()) - return m_query.count(m_descriptor_ordering); - REALM_FALLTHROUGH; - case Mode::TableView: - evaluate_query_if_needed(); - return m_table_view.size(); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -const ObjectSchema& Results::get_object_schema() const -{ - validate_read(); - - if (!m_object_schema) { - REALM_ASSERT(m_realm); - auto it = m_realm->schema().find(get_object_type()); - REALM_ASSERT(it != m_realm->schema().end()); - m_object_schema = &*it; - } - - return *m_object_schema; -} - - -StringData Results::get_object_type() const noexcept -{ - if (!m_table) { - return StringData(); - } - - return ObjectStore::object_type_for_table_name(m_table->get_name()); -} - -namespace { -template -auto get(Table& table, size_t row) -{ - return table.get(0, row); -} - -template<> -auto get(Table& table, size_t row) -{ - return table.get(row); -} -} - -template -util::Optional Results::try_get(size_t row_ndx) -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: break; - case Mode::Table: - if (row_ndx < m_table->size()) - return realm::get(*m_table, row_ndx); - break; - case Mode::LinkView: - if (update_linkview()) { - if (row_ndx < m_link_view->size()) - return realm::get(*m_table, m_link_view->get(row_ndx).get_index()); - break; - } - REALM_FALLTHROUGH; - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(); - if (row_ndx >= m_table_view.size()) - break; - if (m_update_policy == UpdatePolicy::Never && !m_table_view.is_row_attached(row_ndx)) - return T{}; - return realm::get(*m_table, m_table_view.get(row_ndx).get_index()); - } - return util::none; -} - -template -T Results::get(size_t row_ndx) -{ - if (auto row = try_get(row_ndx)) - return *row; - throw OutOfBoundsIndexException{row_ndx, size()}; -} - -template -util::Optional Results::first() -{ - return try_get(0); -} - -template -util::Optional Results::last() -{ - validate_read(); - if (m_mode == Mode::Query) - evaluate_query_if_needed(); // avoid running the query twice (for size() and for get()) - return try_get(size() - 1); -} - -bool Results::update_linkview() -{ - REALM_ASSERT(m_update_policy == UpdatePolicy::Auto); - - if (!m_descriptor_ordering.is_empty()) { - m_query = get_query(); - m_mode = Mode::Query; - evaluate_query_if_needed(); - return false; - } - return true; -} - -void Results::evaluate_query_if_needed(bool wants_notifications) -{ - if (m_update_policy == UpdatePolicy::Never) { - REALM_ASSERT(m_mode == Mode::TableView); - return; - } - - switch (m_mode) { - case Mode::Empty: - case Mode::Table: - case Mode::LinkView: - return; - case Mode::Query: - m_query.sync_view_if_needed(); - m_table_view = m_query.find_all(m_descriptor_ordering); - m_mode = Mode::TableView; - REALM_FALLTHROUGH; - case Mode::TableView: - if (wants_notifications) - prepare_async(ForCallback{false}); - m_has_used_table_view = true; - m_table_view.sync_if_needed(); - if (auto audit = m_realm->audit_context()) - audit->record_query(m_realm->read_transaction_version(), m_table_view); - break; - } -} - -template<> -size_t Results::index_of(RowExpr const& row) -{ - validate_read(); - if (!row) { - throw DetatchedAccessorException{}; - } - if (m_table && row.get_table() != m_table) { - throw IncorrectTableException( - ObjectStore::object_type_for_table_name(m_table->get_name()), - ObjectStore::object_type_for_table_name(row.get_table()->get_name()), - "Attempting to get the index of a Row of the wrong type" - ); - } - - switch (m_mode) { - case Mode::Empty: - return not_found; - case Mode::Table: - return row.get_index(); - case Mode::LinkView: - if (update_linkview()) - return m_link_view->find(row.get_index()); - REALM_FALLTHROUGH; - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(); - return m_table_view.find_by_source_ndx(row.get_index()); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -template -size_t Results::index_of(T const& value) -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: - return not_found; - case Mode::Table: - return m_table->find_first(0, value); - case Mode::LinkView: - REALM_UNREACHABLE(); - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(); - return m_table_view.find_first(0, value); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -size_t Results::index_of(Query&& q) -{ - if (m_descriptor_ordering.will_apply_sort()) { - auto first = filter(std::move(q)).first(); - return first ? index_of(*first) : not_found; - } - - auto query = get_query().and_query(std::move(q)); - query.sync_view_if_needed(); - size_t row = query.find(); - return row != not_found ? index_of(m_table->get(row)) : row; -} - -void Results::prepare_for_aggregate(size_t column, const char* name) -{ - if (column > m_table->get_column_count()) - throw OutOfBoundsIndexException{column, m_table->get_column_count()}; - switch (m_mode) { - case Mode::Empty: break; - case Mode::Table: break; - case Mode::LinkView: - m_query = this->get_query(); - m_mode = Mode::Query; - REALM_FALLTHROUGH; - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(); - break; - default: - REALM_COMPILER_HINT_UNREACHABLE(); - } - switch (m_table->get_column_type(column)) { - case type_Timestamp: case type_Double: case type_Float: case type_Int: break; - default: throw UnsupportedColumnTypeException{column, m_table.get(), name}; - } -} - -template -util::Optional Results::aggregate(size_t column, - const char* name, - Int agg_int, Float agg_float, - Double agg_double, Timestamp agg_timestamp) -{ - validate_read(); - if (!m_table) - return none; - prepare_for_aggregate(column, name); - - auto do_agg = [&](auto const& getter) { - return Mixed(m_mode == Mode::Table ? getter(*m_table) : getter(m_table_view)); - }; - switch (m_table->get_column_type(column)) { - case type_Timestamp: return do_agg(agg_timestamp); - case type_Double: return do_agg(agg_double); - case type_Float: return do_agg(agg_float); - case type_Int: return do_agg(agg_int); - default: REALM_COMPILER_HINT_UNREACHABLE(); - } -} - -util::Optional Results::max(size_t column) -{ - size_t return_ndx = npos; - auto results = aggregate(column, "max", - [&](auto const& table) { return table.maximum_int(column, &return_ndx); }, - [&](auto const& table) { return table.maximum_float(column, &return_ndx); }, - [&](auto const& table) { return table.maximum_double(column, &return_ndx); }, - [&](auto const& table) { return table.maximum_timestamp(column, &return_ndx); }); - return return_ndx == npos ? none : results; -} - -util::Optional Results::min(size_t column) -{ - size_t return_ndx = npos; - auto results = aggregate(column, "min", - [&](auto const& table) { return table.minimum_int(column, &return_ndx); }, - [&](auto const& table) { return table.minimum_float(column, &return_ndx); }, - [&](auto const& table) { return table.minimum_double(column, &return_ndx); }, - [&](auto const& table) { return table.minimum_timestamp(column, &return_ndx); }); - return return_ndx == npos ? none : results; -} - -util::Optional Results::sum(size_t column) -{ - return aggregate(column, "sum", - [=](auto const& table) { return table.sum_int(column); }, - [=](auto const& table) { return table.sum_float(column); }, - [=](auto const& table) { return table.sum_double(column); }, - [=](auto const&) -> Timestamp { throw UnsupportedColumnTypeException{column, m_table.get(), "sum"}; }); -} - -util::Optional Results::average(size_t column) -{ - size_t value_count = 0; - auto results = aggregate(column, "average", - [&](auto const& table) { return table.average_int(column, &value_count); }, - [&](auto const& table) { return table.average_float(column, &value_count); }, - [&](auto const& table) { return table.average_double(column, &value_count); }, - [&](auto const&) -> Timestamp { throw UnsupportedColumnTypeException{column, m_table.get(), "average"}; }); - return value_count == 0 ? none : util::make_optional(results->get_double()); -} - -void Results::clear() -{ - switch (m_mode) { - case Mode::Empty: - return; - case Mode::Table: - validate_write(); - if (m_realm->is_partial()) - Results(m_realm, m_table->where()).clear(); - else - m_table->clear(); - break; - case Mode::Query: - // Not using Query:remove() because building the tableview and - // clearing it is actually significantly faster - case Mode::TableView: - validate_write(); - evaluate_query_if_needed(); - - switch (m_update_policy) { - case UpdatePolicy::Auto: - m_table_view.clear(RemoveMode::unordered); - break; - case UpdatePolicy::Never: { - // Copy the TableView because a frozen Results shouldn't let its size() change. - TableView copy(m_table_view); - copy.clear(RemoveMode::unordered); - break; - } - } - break; - case Mode::LinkView: - validate_write(); - m_link_view->remove_all_target_rows(); - break; - } -} - -PropertyType Results::get_type() const -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: - case Mode::LinkView: - return PropertyType::Object; - case Mode::Query: - case Mode::TableView: - case Mode::Table: - if (m_table->get_index_in_group() != npos) - return PropertyType::Object; - return ObjectSchema::from_core_type(*m_table->get_descriptor(), 0); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -Query Results::get_query() const -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: - case Mode::Query: - return m_query; - case Mode::TableView: { - // A TableView has an associated Query if it was produced by Query::find_all. This is indicated - // by TableView::get_query returning a Query with a non-null table. - Query query = m_table_view.get_query(); - if (query.get_table()) { - return query; - } - - // The TableView has no associated query so create one with no conditions that is restricted - // to the rows in the TableView. - if (m_update_policy == UpdatePolicy::Auto) { - m_table_view.sync_if_needed(); - } - return Query(*m_table, std::unique_ptr(new TableView(m_table_view))); - } - case Mode::LinkView: - return m_table->where(m_link_view); - case Mode::Table: - return m_table->where(); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -TableView Results::get_tableview() -{ - validate_read(); - switch (m_mode) { - case Mode::Empty: - return {}; - case Mode::LinkView: - if (update_linkview()) - return m_table->where(m_link_view).find_all(); - REALM_FALLTHROUGH; - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(); - return m_table_view; - case Mode::Table: - return m_table->where().find_all(); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -static std::vector parse_keypath(StringData keypath, Schema const& schema, const ObjectSchema *object_schema) -{ - auto check = [&](bool condition, const char* fmt, auto... args) { - if (!condition) { - throw std::invalid_argument(util::format("Cannot sort on key path '%1': %2.", - keypath, util::format(fmt, args...))); - } - }; - auto is_sortable_type = [](PropertyType type) { - return !is_array(type) && type != PropertyType::LinkingObjects && type != PropertyType::Data; - }; - - const char* begin = keypath.data(); - const char* end = keypath.data() + keypath.size(); - check(begin != end, "missing property name"); - - std::vector indices; - while (begin != end) { - auto sep = std::find(begin, end, '.'); - check(sep != begin && sep + 1 != end, "missing property name"); - StringData key(begin, sep - begin); - begin = sep + (sep != end); - - auto prop = object_schema->property_for_name(key); - check(prop, "property '%1.%2' does not exist", object_schema->name, key); - check(is_sortable_type(prop->type), "property '%1.%2' is of unsupported type '%3'", - object_schema->name, key, string_for_property_type(prop->type)); - if (prop->type == PropertyType::Object) - check(begin != end, "property '%1.%2' of type 'object' cannot be the final property in the key path", - object_schema->name, key); - else - check(begin == end, "property '%1.%2' of type '%3' may only be the final property in the key path", - object_schema->name, key, prop->type_string()); - - indices.push_back(prop->table_column); - if (prop->type == PropertyType::Object) - object_schema = &*schema.find(prop->object_type); - } - return indices; -} - -Results Results::sort(std::vector> const& keypaths) const -{ - if (keypaths.empty()) - return *this; - if (get_type() != PropertyType::Object) { - if (keypaths.size() != 1) - throw std::invalid_argument(util::format("Cannot sort array of '%1' on more than one key path", - string_for_property_type(get_type()))); - if (keypaths[0].first != "self") - throw std::invalid_argument(util::format("Cannot sort on key path '%1': arrays of '%2' can only be sorted on 'self'", - keypaths[0].first, string_for_property_type(get_type()))); - return sort({*m_table, {{0}}, {keypaths[0].second}}); - } - - std::vector> column_indices; - std::vector ascending; - column_indices.reserve(keypaths.size()); - ascending.reserve(keypaths.size()); - - for (auto& keypath : keypaths) { - column_indices.push_back(parse_keypath(keypath.first, m_realm->schema(), &get_object_schema())); - ascending.push_back(keypath.second); - } - return sort({*m_table, std::move(column_indices), std::move(ascending)}); -} - -Results Results::sort(SortDescriptor&& sort) const -{ - if (m_mode == Mode::LinkView) - return Results(m_realm, m_link_view, util::none, std::move(sort)); - DescriptorOrdering new_order = m_descriptor_ordering; - new_order.append_sort(std::move(sort)); - return Results(m_realm, get_query(), std::move(new_order)); -} - -Results Results::filter(Query&& q) const -{ - if (m_descriptor_ordering.will_apply_limit()) - throw UnimplementedOperationException("Filtering a Results with a limit is not yet implemented"); - return Results(m_realm, get_query().and_query(std::move(q)), m_descriptor_ordering); -} - -Results Results::limit(size_t max_count) const -{ - auto new_order = m_descriptor_ordering; - new_order.append_limit(max_count); - return Results(m_realm, get_query(), std::move(new_order)); -} - -Results Results::apply_ordering(DescriptorOrdering&& ordering) -{ - DescriptorOrdering new_order = m_descriptor_ordering; - for (size_t i = 0; i < ordering.size(); ++i) { - auto desc = ordering[i]; - DescriptorType desc_type = ordering.get_type(i); - switch (desc_type) { - case DescriptorType::Sort: - new_order.append_sort(std::move(*dynamic_cast(desc))); - break; - case DescriptorType::Distinct: - new_order.append_distinct(std::move(*dynamic_cast(desc))); - break; - case DescriptorType::Limit: - new_order.append_limit(std::move(*dynamic_cast(desc))); - break; - case DescriptorType::Include: - new_order.append_include(std::move(*dynamic_cast(desc))); - break; - } - } - return Results(m_realm, get_query(), std::move(new_order)); -} - -Results Results::distinct(DistinctDescriptor&& uniqueness) const -{ - DescriptorOrdering new_order = m_descriptor_ordering; - new_order.append_distinct(std::move(uniqueness)); - return Results(m_realm, get_query(), std::move(new_order)); -} - -Results Results::distinct(std::vector const& keypaths) const -{ - if (keypaths.empty()) - return *this; - if (get_type() != PropertyType::Object) { - if (keypaths.size() != 1) - throw std::invalid_argument(util::format("Cannot sort array of '%1' on more than one key path", - string_for_property_type(get_type()))); - if (keypaths[0] != "self") - throw std::invalid_argument(util::format("Cannot sort on key path '%1': arrays of '%2' can only be sorted on 'self'", - keypaths[0], string_for_property_type(get_type()))); - return distinct({*m_table, {{0}}}); - } - - std::vector> column_indices; - column_indices.reserve(keypaths.size()); - for (auto& keypath : keypaths) - column_indices.push_back(parse_keypath(keypath, m_realm->schema(), &get_object_schema())); - return distinct({*m_table, std::move(column_indices)}); -} - -Results Results::snapshot() const & -{ - validate_read(); - return Results(*this).snapshot(); -} - -Results Results::snapshot() && -{ - validate_read(); - - switch (m_mode) { - case Mode::Empty: - return Results(); - - case Mode::Table: - case Mode::LinkView: - m_query = get_query(); - m_mode = Mode::Query; - - REALM_FALLTHROUGH; - case Mode::Query: - case Mode::TableView: - evaluate_query_if_needed(false); - m_notifier.reset(); - m_update_policy = UpdatePolicy::Never; - return std::move(*this); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -void Results::prepare_async(ForCallback force) -{ - if (m_notifier) { - return; - } - if (m_realm->config().immutable()) { - if (force) - throw InvalidTransactionException("Cannot create asynchronous query for immutable Realms"); - return; - } - if (m_realm->is_in_transaction()) { - if (force) - throw InvalidTransactionException("Cannot create asynchronous query while in a write transaction"); - return; - } - if (m_update_policy == UpdatePolicy::Never) { - if (force) - throw std::logic_error("Cannot create asynchronous query for snapshotted Results."); - return; - } - if (!force) { - // Don't do implicit background updates if we can't actually deliver them - if (!m_realm->can_deliver_notifications()) - return; - // Don't do implicit background updates if there isn't actually anything - // that needs to be run. - if (!m_query.get_table() && m_descriptor_ordering.is_empty()) - return; - } - - m_wants_background_updates = true; - m_notifier = std::make_shared<_impl::ResultsNotifier>(*this); - _impl::RealmCoordinator::register_notifier(m_notifier); -} - -NotificationToken Results::add_notification_callback(CollectionChangeCallback cb) & -{ - prepare_async(ForCallback{true}); - return {m_notifier, m_notifier->add_callback(std::move(cb))}; -} - -bool Results::is_in_table_order() const -{ - switch (m_mode) { - case Mode::Empty: - case Mode::Table: - return true; - case Mode::LinkView: - return false; - case Mode::Query: - return m_query.produces_results_in_table_order() && !m_descriptor_ordering.will_apply_sort(); - case Mode::TableView: - return m_table_view.is_in_table_order(); - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -void Results::Internal::set_table_view(Results& results, TableView &&tv) -{ - REALM_ASSERT(results.m_update_policy != UpdatePolicy::Never); - // If the previous TableView was never actually used, then stop generating - // new ones until the user actually uses the Results object again - if (results.m_mode == Mode::TableView) { - results.m_wants_background_updates = results.m_has_used_table_view; - } - - results.m_table_view = std::move(tv); - results.m_mode = Mode::TableView; - results.m_has_used_table_view = false; - REALM_ASSERT(results.m_table_view.is_in_sync()); - REALM_ASSERT(results.m_table_view.is_attached()); -} -#define REALM_RESULTS_TYPE(T) \ - template T Results::get(size_t); \ - template util::Optional Results::first(); \ - template util::Optional Results::last(); \ - template size_t Results::index_of(T const&); - -template RowExpr Results::get(size_t); -template util::Optional Results::first(); -template util::Optional Results::last(); - -REALM_RESULTS_TYPE(bool) -REALM_RESULTS_TYPE(int64_t) -REALM_RESULTS_TYPE(float) -REALM_RESULTS_TYPE(double) -REALM_RESULTS_TYPE(StringData) -REALM_RESULTS_TYPE(BinaryData) -REALM_RESULTS_TYPE(Timestamp) -REALM_RESULTS_TYPE(util::Optional) -REALM_RESULTS_TYPE(util::Optional) -REALM_RESULTS_TYPE(util::Optional) -REALM_RESULTS_TYPE(util::Optional) - -#undef REALM_RESULTS_TYPE - -Results::OutOfBoundsIndexException::OutOfBoundsIndexException(size_t r, size_t c) -: std::out_of_range(util::format("Requested index %1 greater than max %2", r, c - 1)) -, requested(r), valid_count(c) {} - -static std::string unsupported_operation_msg(size_t column, const Table* table, const char* operation) -{ - const char* column_type = string_for_property_type(ObjectSchema::from_core_type(*table->get_descriptor(), column)); - if (table->is_group_level()) - return util::format("Cannot %1 property '%2': operation not supported for '%3' properties", - operation, table->get_column_name(column), column_type); - return util::format("Cannot %1 '%2' array: operation not supported", - operation, column_type); -} - -Results::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table, const char* operation) -: std::logic_error(unsupported_operation_msg(column, table, operation)) -, column_index(column) -, column_name(table->get_column_name(column)) -, property_type(ObjectSchema::from_core_type(*table->get_descriptor(), column)) -{ -} - -Results::InvalidPropertyException::InvalidPropertyException(const std::string& object_type, const std::string& property_name) -: std::logic_error(util::format("Property '%1.%2' does not exist", object_type, property_name)) -, object_type(object_type), property_name(property_name) -{ -} - -Results::UnimplementedOperationException::UnimplementedOperationException(const char* msg) -: std::logic_error(msg) -{ -} - -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/schema.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/schema.cpp deleted file mode 100644 index 4b572e7..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/schema.cpp +++ /dev/null @@ -1,275 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "schema.hpp" - -#include "object_schema.hpp" -#include "object_store.hpp" -#include "object_schema.hpp" -#include "property.hpp" - -#include - -using namespace realm; - -namespace realm { -bool operator==(Schema const& a, Schema const& b) -{ - return static_cast(a) == static_cast(b); -} -} - -Schema::Schema() = default; -Schema::~Schema() = default; -Schema::Schema(Schema const&) = default; -Schema::Schema(Schema &&) = default; -Schema& Schema::operator=(Schema const&) = default; -Schema& Schema::operator=(Schema&&) = default; - -Schema::Schema(std::initializer_list types) : Schema(base(types)) { } - -Schema::Schema(base types) : base(std::move(types)) -{ - std::sort(begin(), end(), [](ObjectSchema const& lft, ObjectSchema const& rgt) { - return lft.name < rgt.name; - }); -} - -Schema::iterator Schema::find(StringData name) -{ - auto it = std::lower_bound(begin(), end(), name, [](ObjectSchema const& lft, StringData rgt) { - return lft.name < rgt; - }); - if (it != end() && it->name != name) { - it = end(); - } - return it; -} - -Schema::const_iterator Schema::find(StringData name) const -{ - return const_cast(this)->find(name); -} - -Schema::iterator Schema::find(ObjectSchema const& object) noexcept -{ - return find(object.name); -} - -Schema::const_iterator Schema::find(ObjectSchema const& object) const noexcept -{ - return const_cast(this)->find(object); -} - -void Schema::validate() const -{ - std::vector exceptions; - - // As the types are added sorted by name, we can detect duplicates by just looking at the following element. - auto find_next_duplicate = [&](const_iterator start) { - return std::adjacent_find(start, cend(), [](ObjectSchema const& lft, ObjectSchema const& rgt) { - return lft.name == rgt.name; - }); - }; - - for (auto it = find_next_duplicate(cbegin()); it != cend(); it = find_next_duplicate(++it)) { - exceptions.push_back(ObjectSchemaValidationException("Type '%1' appears more than once in the schema.", - it->name)); - } - - for (auto const& object : *this) { - object.validate(*this, exceptions); - } - - if (exceptions.size()) { - throw SchemaValidationException(exceptions); - } -} - -namespace { -struct IsNotRemoveProperty { - bool operator()(SchemaChange sc) const { return sc.visit(*this); } - bool operator()(schema_change::RemoveProperty) const { return false; } - template bool operator()(T) const { return true; } -}; -struct GetRemovedColumn { - size_t operator()(SchemaChange sc) const { return sc.visit(*this); } - size_t operator()(schema_change::RemoveProperty p) const { return p.property->table_column; } - template size_t operator()(T) const { REALM_COMPILER_HINT_UNREACHABLE(); } -}; -} - -static void compare(ObjectSchema const& existing_schema, - ObjectSchema const& target_schema, - std::vector& changes) -{ - for (auto& current_prop : existing_schema.persisted_properties) { - auto target_prop = target_schema.property_for_name(current_prop.name); - - if (!target_prop) { - changes.emplace_back(schema_change::RemoveProperty{&existing_schema, ¤t_prop}); - continue; - } - if (target_schema.property_is_computed(*target_prop)) { - changes.emplace_back(schema_change::RemoveProperty{&existing_schema, ¤t_prop}); - continue; - } - if (current_prop.type != target_prop->type || - current_prop.object_type != target_prop->object_type || - is_array(current_prop.type) != is_array(target_prop->type)) { - - changes.emplace_back(schema_change::ChangePropertyType{&existing_schema, ¤t_prop, target_prop}); - continue; - } - if (is_nullable(current_prop.type) != is_nullable(target_prop->type)) { - if (is_nullable(current_prop.type)) - changes.emplace_back(schema_change::MakePropertyRequired{&existing_schema, ¤t_prop}); - else - changes.emplace_back(schema_change::MakePropertyNullable{&existing_schema, ¤t_prop}); - } - if (target_prop->requires_index()) { - if (!current_prop.is_indexed) - changes.emplace_back(schema_change::AddIndex{&existing_schema, ¤t_prop}); - } - else if (current_prop.requires_index()) { - changes.emplace_back(schema_change::RemoveIndex{&existing_schema, ¤t_prop}); - } - } - - if (existing_schema.primary_key != target_schema.primary_key) { - changes.emplace_back(schema_change::ChangePrimaryKey{&existing_schema, target_schema.primary_key_property()}); - } - - for (auto& target_prop : target_schema.persisted_properties) { - if (!existing_schema.property_for_name(target_prop.name)) { - changes.emplace_back(schema_change::AddProperty{&existing_schema, &target_prop}); - } - } - - // Move all RemovePropertys to the end and sort in descending order of - // column index, as removing a column will shift all columns after that one - auto it = std::partition(begin(changes), end(changes), IsNotRemoveProperty{}); - std::sort(it, end(changes), - [](auto a, auto b) { return GetRemovedColumn()(a) > GetRemovedColumn()(b); }); -} - -template -void Schema::zip_matching(T&& a, U&& b, Func&& func) -{ - size_t i = 0, j = 0; - while (i < a.size() && j < b.size()) { - auto& object_schema = a[i]; - auto& matching_schema = b[j]; - int cmp = object_schema.name.compare(matching_schema.name); - if (cmp == 0) { - func(&object_schema, &matching_schema); - ++i; - ++j; - } - else if (cmp < 0) { - func(&object_schema, nullptr); - ++i; - } - else { - func(nullptr, &matching_schema); - ++j; - } - } - for (; i < a.size(); ++i) - func(&a[i], nullptr); - for (; j < b.size(); ++j) - func(nullptr, &b[j]); - -} - -std::vector Schema::compare(Schema const& target_schema, bool include_table_removals) const -{ - std::vector changes; - - // Add missing tables - zip_matching(target_schema, *this, [&](const ObjectSchema* target, const ObjectSchema* existing) { - if (target && !existing) { - changes.emplace_back(schema_change::AddTable{target}); - } - else if (include_table_removals && existing && !target) { - changes.emplace_back(schema_change::RemoveTable{existing}); - } - }); - - // Modify columns - zip_matching(target_schema, *this, [&](const ObjectSchema* target, const ObjectSchema* existing) { - if (target && existing) - ::compare(*existing, *target, changes); - else if (target) { - // Target is a new table -- add all properties - changes.emplace_back(schema_change::AddInitialProperties{target}); - } - // nothing for tables in existing but not target - }); - return changes; -} - -void Schema::copy_table_columns_from(realm::Schema const& other) -{ - zip_matching(*this, other, [&](ObjectSchema* existing, const ObjectSchema* other) { - if (!existing || !other) - return; - - for (auto& current_prop : other->persisted_properties) { - auto target_prop = existing->property_for_name(current_prop.name); - if (target_prop) { - target_prop->table_column = current_prop.table_column; - } - } - }); -} - -namespace realm { -bool operator==(SchemaChange const& lft, SchemaChange const& rgt) -{ - if (lft.m_kind != rgt.m_kind) - return false; - - using namespace schema_change; - struct Visitor { - SchemaChange const& value; - - #define REALM_SC_COMPARE(type, ...) \ - bool operator()(type rgt) const \ - { \ - auto cmp = [](auto&& v) { return std::tie(__VA_ARGS__); }; \ - return cmp(value.type) == cmp(rgt); \ - } - - REALM_SC_COMPARE(AddIndex, v.object, v.property) - REALM_SC_COMPARE(AddProperty, v.object, v.property) - REALM_SC_COMPARE(AddInitialProperties, v.object) - REALM_SC_COMPARE(AddTable, v.object) - REALM_SC_COMPARE(RemoveTable, v.object) - REALM_SC_COMPARE(ChangePrimaryKey, v.object, v.property) - REALM_SC_COMPARE(ChangePropertyType, v.object, v.old_property, v.new_property) - REALM_SC_COMPARE(MakePropertyNullable, v.object, v.property) - REALM_SC_COMPARE(MakePropertyRequired, v.object, v.property) - REALM_SC_COMPARE(RemoveIndex, v.object, v.property) - REALM_SC_COMPARE(RemoveProperty, v.object, v.property) - - #undef REALM_SC_COMPARE - } visitor{lft}; - return rgt.visit(visitor); -} -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp deleted file mode 100644 index a3f2665..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/shared_realm.cpp +++ /dev/null @@ -1,1159 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "shared_realm.hpp" - -#include "impl/collection_notifier.hpp" -#include "impl/realm_coordinator.hpp" -#include "impl/transact_log_handler.hpp" - -#include "audit.hpp" -#include "binding_context.hpp" -#include "list.hpp" -#include "object.hpp" -#include "object_schema.hpp" -#include "object_store.hpp" -#include "results.hpp" -#include "schema.hpp" -#include "thread_safe_reference.hpp" - -#include -#include -#include - - -#if REALM_ENABLE_SYNC -#include "sync/impl/sync_file.hpp" -#include "sync/sync_config.hpp" -#include "sync/sync_manager.hpp" - -#include -#include -#include -#else -namespace realm { -namespace sync { - struct PermissionsCache {}; - struct TableInfoCache {}; -} -} -#endif - -using namespace realm; -using namespace realm::_impl; - -Realm::Realm(Config config, std::shared_ptr<_impl::RealmCoordinator> coordinator) -: m_config(std::move(config)) -, m_execution_context(m_config.execution_context) -{ - open_with_config(m_config, m_history, m_shared_group, m_read_only_group, this); - - if (m_read_only_group) { - m_group = m_read_only_group.get(); - m_schema_version = ObjectStore::get_schema_version(*m_group); - m_schema = ObjectStore::schema_from_group(*m_group); - } - else if (!coordinator || !coordinator->get_cached_schema(m_schema, m_schema_version, m_schema_transaction_version)) { - if (m_config.should_compact_on_launch_function) { - size_t free_space = -1; - size_t used_space = -1; - // getting stats requires committing a write transaction beforehand. - Group* group = nullptr; - if (m_shared_group->try_begin_write(group)) { - m_shared_group->commit(); - m_shared_group->get_stats(free_space, used_space); - if (m_config.should_compact_on_launch_function(free_space + used_space, used_space)) - compact(); - } - } - read_group(); - if (coordinator) - coordinator->cache_schema(m_schema, m_schema_version, m_schema_transaction_version); - m_shared_group->end_read(); - m_group = nullptr; - } - - m_coordinator = std::move(coordinator); -} - -REALM_NOINLINE static void translate_file_exception(StringData path, bool immutable=false) -{ - try { - throw; - } - catch (util::File::PermissionDenied const& ex) { - throw RealmFileException(RealmFileException::Kind::PermissionDenied, ex.get_path(), - util::format("Unable to open a realm at path '%1'. Please use a path where your app has %2 permissions.", - ex.get_path(), immutable ? "read" : "read-write"), - ex.what()); - } - catch (util::File::Exists const& ex) { - throw RealmFileException(RealmFileException::Kind::Exists, ex.get_path(), - util::format("File at path '%1' already exists.", ex.get_path()), - ex.what()); - } - catch (util::File::NotFound const& ex) { - throw RealmFileException(RealmFileException::Kind::NotFound, ex.get_path(), - util::format("Directory at path '%1' does not exist.", ex.get_path()), ex.what()); - } - catch (util::File::AccessError const& ex) { - // Errors for `open()` include the path, but other errors don't. We - // don't want two copies of the path in the error, so strip it out if it - // appears, and then include it in our prefix. - std::string underlying = ex.what(); - RealmFileException::Kind error_kind = RealmFileException::Kind::AccessError; - // FIXME: Replace this with a proper specific exception type once Core adds support for it. - if (underlying == "Bad or incompatible history type") - error_kind = RealmFileException::Kind::BadHistoryError; - auto pos = underlying.find(ex.get_path()); - if (pos != std::string::npos && pos > 0) { - // One extra char at each end for the quotes - underlying.replace(pos - 1, ex.get_path().size() + 2, ""); - } - throw RealmFileException(error_kind, ex.get_path(), - util::format("Unable to open a realm at path '%1': %2.", ex.get_path(), underlying), ex.what()); - } - catch (IncompatibleLockFile const& ex) { - throw RealmFileException(RealmFileException::Kind::IncompatibleLockFile, path, - "Realm file is currently open in another process " - "which cannot share access with this process. " - "All processes sharing a single file must be the same architecture.", - ex.what()); - } - catch (FileFormatUpgradeRequired const& ex) { - throw RealmFileException(RealmFileException::Kind::FormatUpgradeRequired, path, - "The Realm file format must be allowed to be upgraded " - "in order to proceed.", - ex.what()); - } -} - -#if REALM_ENABLE_SYNC -static bool is_nonupgradable_history(IncompatibleHistories const& ex) -{ - // FIXME: Replace this with a proper specific exception type once Core adds support for it. - return std::string(ex.what()).find(std::string("Incompatible histories. Nonupgradable history schema")) != npos; -} -#endif - -void Realm::open_with_config(const Config& config, - std::unique_ptr& history, - std::unique_ptr& shared_group, - std::unique_ptr& read_only_group, - Realm* realm) -{ - bool server_synchronization_mode = bool(config.sync_config) || config.force_sync_history; - try { - if (config.immutable()) { - if (config.realm_data.is_null()) { - read_only_group = std::make_unique(config.path, config.encryption_key.data(), Group::mode_ReadOnly); - } - else { - // Create in-memory read-only realm from existing buffer (without taking ownership of the buffer) - read_only_group = std::make_unique(config.realm_data, false); - } - } - else { - if (server_synchronization_mode) { -#if REALM_ENABLE_SYNC - history = realm::sync::make_client_history(config.path); -#else - REALM_TERMINATE("Realm was not built with sync enabled"); -#endif - } - else { - history = realm::make_in_realm_history(config.path); - } - - SharedGroupOptions options; - options.durability = config.in_memory ? SharedGroupOptions::Durability::MemOnly : - SharedGroupOptions::Durability::Full; - if (!config.fifo_files_fallback_path.empty()) { - options.temp_dir = util::normalize_dir(config.fifo_files_fallback_path); - } - options.encryption_key = config.encryption_key.data(); - options.allow_file_format_upgrade = !config.disable_format_upgrade && - config.schema_mode != SchemaMode::ResetFile; - options.upgrade_callback = [&](int from_version, int to_version) { - if (realm) { - realm->upgrade_initial_version = from_version; - realm->upgrade_final_version = to_version; - } - }; - shared_group = std::make_unique(*history, options); - } - } - catch (realm::FileFormatUpgradeRequired const&) { - if (config.schema_mode != SchemaMode::ResetFile) { - translate_file_exception(config.path, config.immutable()); - } - util::File::remove(config.path); - open_with_config(config, history, shared_group, read_only_group, realm); - } -#if REALM_ENABLE_SYNC - catch (IncompatibleHistories const& ex) { - if (!server_synchronization_mode || !is_nonupgradable_history(ex)) - translate_file_exception(config.path, config.immutable()); // Throws - - // Move the Realm file into the recovery directory. - std::string recovery_directory = SyncManager::shared().recovery_directory_path(config.sync_config ? config.sync_config->recovery_directory : none); - std::string new_realm_path = util::reserve_unique_file_name(recovery_directory, "synced-realm-XXXXXXX"); - util::File::move(config.path, new_realm_path); - - const char* message = "The local copy of this synced Realm was created with an incompatible version of " - "Realm. It has been moved aside, and the Realm will be re-downloaded the next time it " - "is opened. You should write a handler for this error that uses the provided " - "configuration to open the old Realm in read-only mode to recover any pending changes " - "and then remove the Realm file."; - throw RealmFileException(RealmFileException::Kind::IncompatibleSyncedRealm, std::move(new_realm_path), - message, ex.what()); - } -#endif // REALM_ENABLE_SYNC - catch (...) { - translate_file_exception(config.path, config.immutable()); - } -} - -Realm::~Realm() -{ - if (m_coordinator) { - m_coordinator->unregister_realm(this); - } -} - -bool Realm::is_partial() const noexcept -{ -#if REALM_ENABLE_SYNC - return m_config.sync_config && m_config.sync_config->is_partial; -#else - return false; -#endif -} - -Group& Realm::read_group() -{ - verify_open(); - - if (!m_group) - begin_read(VersionID{}); - return *m_group; -} - -void Realm::Internal::begin_read(Realm& realm, VersionID version_id) -{ - realm.begin_read(version_id); -} - -void Realm::begin_read(VersionID version_id) -{ - REALM_ASSERT(!m_group); - m_group = &const_cast(m_shared_group->begin_read(version_id)); - add_schema_change_handler(); - read_schema_from_group_if_needed(); -} - -SharedRealm Realm::get_shared_realm(Config config) -{ - auto coordinator = RealmCoordinator::get_coordinator(config.path); - return coordinator->get_realm(std::move(config)); -} - -SharedRealm Realm::get_shared_realm(ThreadSafeReference ref, util::Optional execution_context) -{ - REALM_ASSERT(ref.m_realm); - auto& config = ref.m_realm->config(); - auto coordinator = RealmCoordinator::get_coordinator(config.path); - if (auto realm = coordinator->get_cached_realm(config, execution_context)) - return realm; - coordinator->bind_to_context(*ref.m_realm, execution_context); - ref.m_realm->m_execution_context = execution_context; - return std::move(ref.m_realm); -} - -#if REALM_ENABLE_SYNC -std::shared_ptr Realm::get_synchronized_realm(Config config) -{ - auto coordinator = RealmCoordinator::get_coordinator(config.path); - return coordinator->get_synchronized_realm(std::move(config)); -} -#endif - -void Realm::set_schema(Schema const& reference, Schema schema) -{ - m_dynamic_schema = false; - schema.copy_table_columns_from(reference); - m_schema = std::move(schema); - notify_schema_changed(); -} - -void Realm::read_schema_from_group_if_needed() -{ - REALM_ASSERT(!m_read_only_group); - - Group& group = read_group(); - auto current_version = m_shared_group->get_version_of_current_transaction().version; - if (m_schema_transaction_version == current_version) - return; - - m_schema_transaction_version = current_version; - m_schema_version = ObjectStore::get_schema_version(group); - auto schema = ObjectStore::schema_from_group(group); - if (m_coordinator) - m_coordinator->cache_schema(schema, m_schema_version, - m_schema_transaction_version); - - if (m_dynamic_schema) { - if (m_schema == schema) { - // The structure of the schema hasn't changed. Bring the table column indices up to date. - m_schema.copy_table_columns_from(schema); - } - else { - // The structure of the schema has changed, so replace our copy of the schema. - // FIXME: This invalidates any pointers to the object schemas within the schema vector, - // which will cause problems for anyone that caches such a pointer. - m_schema = std::move(schema); - } - } - else { - ObjectStore::verify_valid_external_changes(m_schema.compare(schema)); - m_schema.copy_table_columns_from(schema); - } - notify_schema_changed(); -} - -bool Realm::reset_file(Schema& schema, std::vector& required_changes) -{ - // FIXME: this does not work if multiple processes try to open the file at - // the same time, or even multiple threads if there is not any external - // synchronization. The latter is probably fixable, but making it - // multi-process-safe requires some sort of multi-process exclusive lock - m_group = nullptr; - m_shared_group = nullptr; - m_history = nullptr; - util::File::remove(m_config.path); - - open_with_config(m_config, m_history, m_shared_group, m_read_only_group, this); - m_schema = ObjectStore::schema_from_group(read_group()); - m_schema_version = ObjectStore::get_schema_version(read_group()); - required_changes = m_schema.compare(schema); - m_coordinator->clear_schema_cache_and_set_schema_version(m_schema_version); - return false; -} - -bool Realm::schema_change_needs_write_transaction(Schema& schema, - std::vector& changes, - uint64_t version) -{ - if (version == m_schema_version && changes.empty()) - return false; - - switch (m_config.schema_mode) { - case SchemaMode::Automatic: - if (version < m_schema_version && m_schema_version != ObjectStore::NotVersioned) - throw InvalidSchemaVersionException(m_schema_version, version); - return true; - - case SchemaMode::Immutable: - if (version != m_schema_version) - throw InvalidSchemaVersionException(m_schema_version, version); - REALM_FALLTHROUGH; - case SchemaMode::ReadOnlyAlternative: - ObjectStore::verify_compatible_for_immutable_and_readonly(changes); - return false; - - case SchemaMode::ResetFile: - if (m_schema_version == ObjectStore::NotVersioned) - return true; - if (m_schema_version == version && !ObjectStore::needs_migration(changes)) - return true; - reset_file(schema, changes); - return true; - - case SchemaMode::Additive: { - bool will_apply_index_changes = version > m_schema_version; - if (ObjectStore::verify_valid_additive_changes(changes, will_apply_index_changes)) - return true; - return version != m_schema_version; - } - - case SchemaMode::Manual: - if (version < m_schema_version && m_schema_version != ObjectStore::NotVersioned) - throw InvalidSchemaVersionException(m_schema_version, version); - if (version == m_schema_version) { - ObjectStore::verify_no_changes_required(changes); - REALM_UNREACHABLE(); // changes is non-empty so above line always throws - } - return true; - } - REALM_COMPILER_HINT_UNREACHABLE(); -} - -Schema Realm::get_full_schema() -{ - if (!m_read_only_group) - refresh(); - - // If the user hasn't specified a schema previously then m_schema is always - // the full schema - if (m_dynamic_schema) - return m_schema; - - // Otherwise we may have a subset of the file's schema, so we need to get - // the complete thing to calculate what changes to make - if (m_read_only_group) - return ObjectStore::schema_from_group(read_group()); - - Schema actual_schema; - uint64_t actual_version; - uint64_t transaction = -1; - bool got_cached = m_coordinator->get_cached_schema(actual_schema, actual_version, transaction); - if (!got_cached || transaction != m_shared_group->get_version_of_current_transaction().version) - return ObjectStore::schema_from_group(read_group()); - return actual_schema; -} - -void Realm::set_schema_subset(Schema schema) -{ - REALM_ASSERT(m_dynamic_schema); - REALM_ASSERT(m_schema_version != ObjectStore::NotVersioned); - - std::vector changes = m_schema.compare(schema); - switch (m_config.schema_mode) { - case SchemaMode::Automatic: - case SchemaMode::ResetFile: - ObjectStore::verify_no_migration_required(changes); - break; - - case SchemaMode::Immutable: - case SchemaMode::ReadOnlyAlternative: - ObjectStore::verify_compatible_for_immutable_and_readonly(changes); - break; - - case SchemaMode::Additive: - ObjectStore::verify_valid_additive_changes(changes); - break; - - case SchemaMode::Manual: - ObjectStore::verify_no_changes_required(changes); - break; - } - - set_schema(m_schema, std::move(schema)); -} - -void Realm::update_schema(Schema schema, uint64_t version, MigrationFunction migration_function, - DataInitializationFunction initialization_function, bool in_transaction) -{ - schema.validate(); - - Schema actual_schema = get_full_schema(); - std::vector required_changes = actual_schema.compare(schema); - - if (!schema_change_needs_write_transaction(schema, required_changes, version)) { - set_schema(actual_schema, std::move(schema)); - return; - } - // Either the schema version has changed or we need to do non-migration changes - - if (!in_transaction) { - transaction::begin_without_validation(*m_shared_group); - - // Beginning the write transaction may have advanced the version and left - // us with nothing to do if someone else initialized the schema on disk - if (m_new_schema) { - actual_schema = *m_new_schema; - required_changes = actual_schema.compare(schema); - if (!schema_change_needs_write_transaction(schema, required_changes, version)) { - cancel_transaction(); - cache_new_schema(); - set_schema(actual_schema, std::move(schema)); - return; - } - } - cache_new_schema(); - } - - // Cancel the write transaction if we exit this function before committing it - auto cleanup = util::make_scope_exit([&]() noexcept { - // When in_transaction is true, caller is responsible to cancel the transaction. - if (!in_transaction && is_in_transaction()) - cancel_transaction(); - }); - - uint64_t old_schema_version = m_schema_version; - bool additive = m_config.schema_mode == SchemaMode::Additive; - if (migration_function && !additive) { - auto wrapper = [&] { - SharedRealm old_realm(new Realm(m_config, nullptr)); - // Need to open in read-write mode so that it uses a SharedGroup, but - // users shouldn't actually be able to write via the old realm - old_realm->m_config.schema_mode = SchemaMode::Immutable; - migration_function(old_realm, shared_from_this(), m_schema); - }; - - // migration function needs to see the target schema on the "new" Realm - std::swap(m_schema, schema); - std::swap(m_schema_version, version); - m_in_migration = true; - auto restore = util::make_scope_exit([&]() noexcept { - std::swap(m_schema, schema); - std::swap(m_schema_version, version); - m_in_migration = false; - }); - - ObjectStore::apply_schema_changes(read_group(), version, m_schema, m_schema_version, - m_config.schema_mode, required_changes, util::none, wrapper); - } - else { - util::Optional sync_user_id; -#if REALM_ENABLE_SYNC - if (m_config.sync_config && m_config.sync_config->is_partial) - sync_user_id = m_config.sync_config->user->identity(); -#endif - ObjectStore::apply_schema_changes(read_group(), m_schema_version, schema, version, - m_config.schema_mode, required_changes, std::move(sync_user_id)); - REALM_ASSERT_DEBUG(additive || (required_changes = ObjectStore::schema_from_group(read_group()).compare(schema)).empty()); - } - - if (initialization_function && old_schema_version == ObjectStore::NotVersioned) { - // Initialization function needs to see the latest schema - uint64_t temp_version = ObjectStore::get_schema_version(read_group()); - std::swap(m_schema, schema); - std::swap(m_schema_version, temp_version); - auto restore = util::make_scope_exit([&]() noexcept { - std::swap(m_schema, schema); - std::swap(m_schema_version, temp_version); - }); - initialization_function(shared_from_this()); - } - - if (!in_transaction) { - commit_transaction(); - } - - m_schema = std::move(schema); - m_schema_version = ObjectStore::get_schema_version(read_group()); - m_dynamic_schema = false; - m_coordinator->clear_schema_cache_and_set_schema_version(version); - notify_schema_changed(); -} - -void Realm::add_schema_change_handler() -{ - if (m_config.immutable()) - return; - m_group->set_schema_change_notification_handler([&] { - m_new_schema = ObjectStore::schema_from_group(read_group()); - m_schema_version = ObjectStore::get_schema_version(read_group()); - if (m_dynamic_schema) { - // FIXME: This invalidates any pointers to the object schemas within the schema vector, - // which will cause problems for anyone that caches such a pointer. - m_schema = *m_new_schema; - } - else - m_schema.copy_table_columns_from(*m_new_schema); - - notify_schema_changed(); - }); -} - -void Realm::cache_new_schema() -{ - if (!m_shared_group) - return; - - auto new_version = m_shared_group->get_version_of_current_transaction().version; - if (m_coordinator) { - if (m_new_schema) - m_coordinator->cache_schema(std::move(*m_new_schema), m_schema_version, new_version); - else - m_coordinator->advance_schema_cache(m_schema_transaction_version, new_version); - } - m_schema_transaction_version = new_version; - m_new_schema = util::none; -} - -void Realm::translate_schema_error() -{ - // Open another copy of the file to read the new (incompatible) schema without changing - // our read transaction - auto config = m_config; - config.schema = util::none; - auto realm = Realm::make_shared_realm(std::move(config), nullptr); - auto& new_schema = realm->schema(); - - // Should always throw - ObjectStore::verify_valid_external_changes(m_schema.compare(new_schema, true)); - - // Something strange happened so just rethrow the old exception - throw; -} - -void Realm::notify_schema_changed() -{ - if (m_binding_context) { - m_binding_context->schema_did_change(m_schema); - } -} - -static void check_read_write(const Realm* realm) -{ - if (realm->config().immutable()) { - throw InvalidTransactionException("Can't perform transactions on read-only Realms."); - } -} - -static void check_write(const Realm* realm) -{ - if (realm->config().immutable() || realm->config().read_only_alternative()) { - throw InvalidTransactionException("Can't perform transactions on read-only Realms."); - } -} - -void Realm::verify_thread() const -{ - if (!m_execution_context.contains()) - return; - - auto thread_id = m_execution_context.get(); - if (thread_id != std::this_thread::get_id()) - throw IncorrectThreadException(); -} - -void Realm::verify_in_write() const -{ - if (!is_in_transaction()) { - throw InvalidTransactionException("Cannot modify managed objects outside of a write transaction."); - } -} - -void Realm::verify_open() const -{ - if (is_closed()) { - throw ClosedRealmException(); - } -} - -VersionID Realm::read_transaction_version() const -{ - verify_thread(); - verify_open(); - check_read_write(this); - return m_shared_group->get_version_of_current_transaction(); -} - -bool Realm::is_in_transaction() const noexcept -{ - if (!m_shared_group) { - return false; - } - return m_shared_group->get_transact_stage() == SharedGroup::transact_Writing; -} - -void Realm::begin_transaction() -{ - check_write(this); - verify_thread(); - - if (is_in_transaction()) { - throw InvalidTransactionException("The Realm is already in a write transaction"); - } - - // Any of the callbacks to user code below could drop the last remaining - // strong reference to `this` - auto retain_self = shared_from_this(); - - // If we're already in the middle of sending notifications, just begin the - // write transaction without sending more notifications. If this actually - // advances the read version this could leave the user in an inconsistent - // state, but that's unavoidable. - if (m_is_sending_notifications) { - _impl::NotifierPackage notifiers; - transaction::begin(m_shared_group, m_binding_context.get(), notifiers); - return; - } - - // make sure we have a read transaction - read_group(); - - m_is_sending_notifications = true; - auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); - - try { - m_coordinator->promote_to_write(*this); - } - catch (_impl::UnsupportedSchemaChange const&) { - translate_schema_error(); - } - cache_new_schema(); -} - -void Realm::commit_transaction() -{ - check_write(this); - verify_thread(); - - if (!is_in_transaction()) { - throw InvalidTransactionException("Can't commit a non-existing write transaction"); - } - - if (auto audit = audit_context()) { - auto prev_version = m_shared_group->pin_version(); - m_coordinator->commit_write(*this); - audit->record_write(prev_version, m_shared_group->get_version_of_current_transaction()); - m_shared_group->unpin_version(prev_version); - } - else { - m_coordinator->commit_write(*this); - } - cache_new_schema(); - invalidate_permission_cache(); -} - -void Realm::cancel_transaction() -{ - check_write(this); - verify_thread(); - - if (!is_in_transaction()) { - throw InvalidTransactionException("Can't cancel a non-existing write transaction"); - } - - transaction::cancel(*m_shared_group, m_binding_context.get()); - invalidate_permission_cache(); -} - -void Realm::invalidate() -{ - verify_open(); - verify_thread(); - check_read_write(this); - - if (m_is_sending_notifications) { - return; - } - - if (is_in_transaction()) { - cancel_transaction(); - } - if (!m_group) { - return; - } - - m_permissions_cache = nullptr; - m_table_info_cache = nullptr; - m_shared_group->end_read(); - m_group = nullptr; -} - -bool Realm::compact() -{ - verify_thread(); - - if (m_config.immutable() || m_config.read_only_alternative()) { - throw InvalidTransactionException("Can't compact a read-only Realm"); - } - if (is_in_transaction()) { - throw InvalidTransactionException("Can't compact a Realm within a write transaction"); - } - - verify_open(); - // FIXME: when enum columns are ready, optimise all tables in a write transaction - if (m_group) { - m_shared_group->end_read(); - } - m_group = nullptr; - - return m_shared_group->compact(); -} - -void Realm::write_copy(StringData path, BinaryData key) -{ - if (key.data() && key.size() != 64) { - throw InvalidEncryptionKeyException(); - } - verify_thread(); - try { - read_group().write(path, key.data()); - } - catch (...) { - translate_file_exception(path); - } -} - -OwnedBinaryData Realm::write_copy() -{ - verify_thread(); - BinaryData buffer = read_group().write_to_mem(); - - // Since OwnedBinaryData does not have a constructor directly taking - // ownership of BinaryData, we have to do this to avoid copying the buffer - return OwnedBinaryData(std::unique_ptr((char*)buffer.data()), buffer.size()); -} - -void Realm::notify() -{ - if (is_closed() || is_in_transaction()) { - return; - } - - verify_thread(); - invalidate_permission_cache(); - - // Any of the callbacks to user code below could drop the last remaining - // strong reference to `this` - auto retain_self = shared_from_this(); - - if (m_binding_context) { - m_binding_context->before_notify(); - if (is_closed() || is_in_transaction()) { - return; - } - } - - auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); - if (!m_shared_group->has_changed()) { - m_is_sending_notifications = true; - m_coordinator->process_available_async(*this); - return; - } - - if (m_binding_context) { - m_binding_context->changes_available(); - - // changes_available() may have advanced the read version, and if - // so we don't need to do anything further - if (!m_shared_group->has_changed()) - return; - } - - m_is_sending_notifications = true; - if (m_auto_refresh) { - if (m_group) { - try { - m_coordinator->advance_to_ready(*this); - } - catch (_impl::UnsupportedSchemaChange const&) { - translate_schema_error(); - } - cache_new_schema(); - } - else { - if (m_binding_context) { - m_binding_context->did_change({}, {}); - } - if (!is_closed()) { - m_coordinator->process_available_async(*this); - } - } - } -} - -bool Realm::refresh() -{ - verify_thread(); - check_read_write(this); - - // can't be any new changes if we're in a write transaction - if (is_in_transaction()) { - return false; - } - // don't advance if we're already in the process of advancing as that just - // makes things needlessly complicated - if (m_is_sending_notifications) { - return false; - } - invalidate_permission_cache(); - - // Any of the callbacks to user code below could drop the last remaining - // strong reference to `this` - auto retain_self = shared_from_this(); - - m_is_sending_notifications = true; - auto cleanup = util::make_scope_exit([this]() noexcept { m_is_sending_notifications = false; }); - - if (m_binding_context) { - m_binding_context->before_notify(); - } - if (m_group) { - try { - bool version_changed = m_coordinator->advance_to_latest(*this); - cache_new_schema(); - return version_changed; - } - catch (_impl::UnsupportedSchemaChange const&) { - translate_schema_error(); - } - } - - // No current read transaction, so just create a new one - read_group(); - m_coordinator->process_available_async(*this); - return true; -} - -bool Realm::can_deliver_notifications() const noexcept -{ - if (m_config.immutable() || !m_config.automatic_change_notifications) { - return false; - } - - if (m_binding_context && !m_binding_context->can_deliver_notifications()) { - return false; - } - - return true; -} - -uint64_t Realm::get_schema_version(const Realm::Config &config) -{ - auto coordinator = RealmCoordinator::get_existing_coordinator(config.path); - if (coordinator) { - return coordinator->get_schema_version(); - } - - return ObjectStore::get_schema_version(Realm(config, nullptr).read_group()); -} - -void Realm::close() -{ - if (m_coordinator) { - m_coordinator->unregister_realm(this); - } - - m_permissions_cache = nullptr; - m_table_info_cache = nullptr; - m_group = nullptr; - m_shared_group = nullptr; - m_history = nullptr; - m_read_only_group = nullptr; - m_binding_context = nullptr; - m_coordinator = nullptr; -} - -util::Optional Realm::file_format_upgraded_from_version() const -{ - if (upgrade_initial_version != upgrade_final_version) { - return upgrade_initial_version; - } - return util::none; -} - -template -realm::ThreadSafeReference Realm::obtain_thread_safe_reference(T const& value) -{ - verify_thread(); - if (is_in_transaction()) { - throw InvalidTransactionException("Cannot obtain thread safe reference during a write transaction."); - } - return ThreadSafeReference(value); -} - -template ThreadSafeReference Realm::obtain_thread_safe_reference(Object const& value); -template ThreadSafeReference Realm::obtain_thread_safe_reference(List const& value); -template ThreadSafeReference Realm::obtain_thread_safe_reference(Results const& value); - -template -T Realm::resolve_thread_safe_reference(ThreadSafeReference reference) -{ - verify_thread(); - if (is_in_transaction()) { - throw InvalidTransactionException("Cannot resolve thread safe reference during a write transaction."); - } - if (reference.is_invalidated()) { - throw std::logic_error("Cannot resolve thread safe reference more than once."); - } - if (!reference.has_same_config(*this)) { - throw MismatchedRealmException("Cannot resolve thread safe reference in Realm with different configuration " - "than the source Realm."); - } - invalidate_permission_cache(); - - // Any of the callbacks to user code below could drop the last remaining - // strong reference to `this` - auto retain_self = shared_from_this(); - - // Ensure we're on the same version as the reference - if (!m_group) { - // A read transaction doesn't yet exist, so create at the reference's version - begin_read(reference.m_version_id); - } - else { - // A read transaction does exist, but let's make sure that its version matches the reference's - auto current_version = m_shared_group->get_version_of_current_transaction(); - VersionID reference_version(reference.m_version_id); - - if (reference_version == current_version) { - return std::move(reference).import_into_realm(shared_from_this()); - } - - refresh(); - - current_version = m_shared_group->get_version_of_current_transaction(); - - // If the reference's version is behind, advance it to our version - if (reference_version < current_version) { - // Duplicate config for uncached Realm so we don't advance the user's Realm - Realm::Config config = m_coordinator->get_config(); - config.automatic_change_notifications = false; - config.cache = false; - config.schema = util::none; - SharedRealm temporary_realm = m_coordinator->get_realm(config); - temporary_realm->begin_read(reference_version); - - // With reference imported, advance temporary Realm to our version - T imported_value = std::move(reference).import_into_realm(temporary_realm); - transaction::advance(*temporary_realm->m_shared_group, nullptr, current_version); - if (!imported_value.is_valid()) - return T{}; - reference = ThreadSafeReference(imported_value); - } - } - - return std::move(reference).import_into_realm(shared_from_this()); -} - -template Object Realm::resolve_thread_safe_reference(ThreadSafeReference reference); -template List Realm::resolve_thread_safe_reference(ThreadSafeReference reference); -template Results Realm::resolve_thread_safe_reference(ThreadSafeReference reference); - -AuditInterface* Realm::audit_context() const noexcept -{ - return m_coordinator ? m_coordinator->audit_context() : nullptr; -} - -#if REALM_ENABLE_SYNC -static_assert(static_cast(ComputedPrivileges::Read) == static_cast(sync::Privilege::Read), ""); -static_assert(static_cast(ComputedPrivileges::Update) == static_cast(sync::Privilege::Update), ""); -static_assert(static_cast(ComputedPrivileges::Delete) == static_cast(sync::Privilege::Delete), ""); -static_assert(static_cast(ComputedPrivileges::SetPermissions) == static_cast(sync::Privilege::SetPermissions), ""); -static_assert(static_cast(ComputedPrivileges::Query) == static_cast(sync::Privilege::Query), ""); -static_assert(static_cast(ComputedPrivileges::Create) == static_cast(sync::Privilege::Create), ""); -static_assert(static_cast(ComputedPrivileges::ModifySchema) == static_cast(sync::Privilege::ModifySchema), ""); - -static constexpr const uint8_t s_allRealmPrivileges = sync::Privilege::Read - | sync::Privilege::Update - | sync::Privilege::SetPermissions - | sync::Privilege::ModifySchema; -static constexpr const uint8_t s_allClassPrivileges = sync::Privilege::Read - | sync::Privilege::Update - | sync::Privilege::Create - | sync::Privilege::Query - | sync::Privilege::SetPermissions; -static constexpr const uint8_t s_allObjectPrivileges = sync::Privilege::Read - | sync::Privilege::Update - | sync::Privilege::Delete - | sync::Privilege::SetPermissions; - -bool Realm::init_permission_cache() -{ - verify_thread(); - - if (m_permissions_cache) { - // Rather than trying to track changes to permissions tables, just skip the caching - // entirely within write transactions for now - if (is_in_transaction()) - m_permissions_cache->clear(); - return true; - } - - // Admin users bypass permissions checks outside of the logic in PermissionsCache - if (m_config.sync_config && m_config.sync_config->is_partial && !m_config.sync_config->user->is_admin()) { -#if REALM_SYNC_VER_MAJOR == 3 && (REALM_SYNC_VER_MINOR < 13 || (REALM_SYNC_VER_MINOR == 13 && REALM_SYNC_VER_PATCH < 3)) - m_permissions_cache = std::make_unique(read_group(), m_config.sync_config->user->identity()); -#else - m_table_info_cache = std::make_unique(read_group()); - m_permissions_cache = std::make_unique(read_group(), *m_table_info_cache, - m_config.sync_config->user->identity()); -#endif - return true; - } - return false; -} - -void Realm::invalidate_permission_cache() -{ - if (m_permissions_cache) - m_permissions_cache->clear(); -} - -ComputedPrivileges Realm::get_privileges() -{ - if (!init_permission_cache()) - return static_cast(s_allRealmPrivileges); - return static_cast(m_permissions_cache->get_realm_privileges() & s_allRealmPrivileges); -} - -static uint8_t inherited_mask(uint32_t privileges) -{ - uint8_t mask = ~0; - if (!(privileges & sync::Privilege::Read)) - mask = 0; - else if (!(privileges & sync::Privilege::Update)) - mask = static_cast(sync::Privilege::Read | sync::Privilege::Query); - return mask; -} - -ComputedPrivileges Realm::get_privileges(StringData object_type) -{ - if (!init_permission_cache()) - return static_cast(s_allClassPrivileges); - auto privileges = inherited_mask(m_permissions_cache->get_realm_privileges()) - & m_permissions_cache->get_class_privileges(object_type); - return static_cast(privileges & s_allClassPrivileges); -} - -ComputedPrivileges Realm::get_privileges(RowExpr row) -{ - if (!init_permission_cache()) - return static_cast(s_allObjectPrivileges); - - auto& table = *row.get_table(); - auto object_type = ObjectStore::object_type_for_table_name(table.get_name()); - sync::GlobalID global_id{object_type, sync::object_id_for_row(read_group(), table, row.get_index())}; - auto privileges = inherited_mask(m_permissions_cache->get_realm_privileges()) - & inherited_mask(m_permissions_cache->get_class_privileges(object_type)) - & m_permissions_cache->get_object_privileges(global_id); - return static_cast(privileges & s_allObjectPrivileges); -} -#else -void Realm::invalidate_permission_cache() { } -#endif - -MismatchedConfigException::MismatchedConfigException(StringData message, StringData path) -: std::logic_error(util::format(message.data(), path)) { } - -MismatchedRealmException::MismatchedRealmException(StringData message) -: std::logic_error(message.data()) { } - -// FIXME Those are exposed for Java async queries, mainly because of handover related methods. -SharedGroup& RealmFriend::get_shared_group(Realm& realm) -{ - return *realm.m_shared_group; -} - -Group& RealmFriend::read_group_to(Realm& realm, VersionID version) -{ - if (realm.m_group && realm.m_shared_group->get_version_of_current_transaction() == version) - return *realm.m_group; - - if (realm.m_group) - realm.m_shared_group->end_read(); - realm.begin_read(version); - return *realm.m_group; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp deleted file mode 100644 index 3189cd5..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/async_open_task.cpp +++ /dev/null @@ -1,89 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2019 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/async_open_task.hpp" - -#include "impl/realm_coordinator.hpp" -#include "sync/sync_manager.hpp" -#include "sync/sync_session.hpp" -#include "thread_safe_reference.hpp" - -namespace realm { - -AsyncOpenTask::AsyncOpenTask(std::shared_ptr<_impl::RealmCoordinator> coordinator, std::shared_ptr session) -: m_coordinator(coordinator) -, m_session(session) -{ -} - -void AsyncOpenTask::start(std::function, std::exception_ptr)> callback) -{ - auto session = m_session.load(); - if (!session) - return; - - std::shared_ptr self(shared_from_this()); - session->wait_for_download_completion([callback, self, this](std::error_code ec) { - auto session = m_session.exchange(nullptr); - if (!session) - return; // Swallow all events if the task as been canceled. - - // Release our references to the coordinator after calling the callback - auto coordinator = std::move(m_coordinator); - m_coordinator = nullptr; - - if (ec) - return callback({}, std::make_exception_ptr(std::system_error(ec))); - - ThreadSafeReference realm; - try { - realm = coordinator->get_unbound_realm(); - } - catch (...) { - return callback({}, std::current_exception()); - } - callback(std::move(realm), nullptr); - }); -} - -void AsyncOpenTask::cancel() -{ - if (auto session = m_session.exchange(nullptr)) { - // Does a better way exists for canceling the download? - session->log_out(); - m_coordinator = nullptr; - } -} - -uint64_t AsyncOpenTask::register_download_progress_notifier(std::function callback) -{ - if (auto session = m_session.load()) { - return session->register_progress_notifier(callback, realm::SyncSession::NotifierType::download, false); - } - else { - return 0; - } -} - -void AsyncOpenTask::unregister_download_progress_notifier(uint64_t token) -{ - if (auto session = m_session.load()) - session->unregister_progress_notifier(token); -} - -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp deleted file mode 100644 index ad040a4..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/network_reachability_observer.cpp +++ /dev/null @@ -1,127 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/impl/apple/network_reachability_observer.hpp" - -#if NETWORK_REACHABILITY_AVAILABLE - -using namespace realm; -using namespace realm::_impl; - -namespace { - -NetworkReachabilityStatus reachability_status_for_flags(SCNetworkReachabilityFlags flags) -{ - if (!(flags & kSCNetworkReachabilityFlagsReachable)) - return NotReachable; - - if (flags & kSCNetworkReachabilityFlagsConnectionRequired) { - if (!(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) || - (flags & kSCNetworkReachabilityFlagsInterventionRequired)) - return NotReachable; - } - - NetworkReachabilityStatus status = ReachableViaWiFi; - -#if TARGET_OS_IPHONE - if (flags & kSCNetworkReachabilityFlagsIsWWAN) - status = ReachableViaWWAN; -#endif - - return status; -} - -} // (anonymous namespace) - -NetworkReachabilityObserver::NetworkReachabilityObserver(util::Optional hostname, - std::function handler) -: m_callback_queue(dispatch_queue_create("io.realm.sync.reachability", DISPATCH_QUEUE_SERIAL)) -, m_change_handler(std::move(handler)) -{ - if (hostname) { - m_reachability_ref = util::adoptCF(SystemConfiguration::shared().network_reachability_create_with_name(nullptr, - hostname->c_str())); - } else { - struct sockaddr zeroAddress = {}; - zeroAddress.sa_len = sizeof(zeroAddress); - zeroAddress.sa_family = AF_INET; - - m_reachability_ref = util::adoptCF(SystemConfiguration::shared().network_reachability_create_with_address(nullptr, - &zeroAddress)); - } -} - -NetworkReachabilityObserver::~NetworkReachabilityObserver() -{ - stop_observing(); - dispatch_release(m_callback_queue); -} - -NetworkReachabilityStatus NetworkReachabilityObserver::reachability_status() const -{ - SCNetworkReachabilityFlags flags; - - if (SystemConfiguration::shared().network_reachability_get_flags(m_reachability_ref.get(), &flags)) - return reachability_status_for_flags(flags); - - return NotReachable; -} - -bool NetworkReachabilityObserver::start_observing() -{ - m_previous_status = reachability_status(); - - auto callback = [](SCNetworkReachabilityRef, SCNetworkReachabilityFlags, void* self) { - static_cast(self)->reachability_changed(); - }; - - SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr}; - - if (!SystemConfiguration::shared().network_reachability_set_callback(m_reachability_ref.get(), callback, &context)) - return false; - - if (!SystemConfiguration::shared().network_reachability_set_dispatch_queue(m_reachability_ref.get(), m_callback_queue)) - return false; - - return true; -} - -void NetworkReachabilityObserver::stop_observing() -{ - SystemConfiguration::shared().network_reachability_set_dispatch_queue(m_reachability_ref.get(), nullptr); - SystemConfiguration::shared().network_reachability_set_callback(m_reachability_ref.get(), nullptr, nullptr); - - // Wait for all previously-enqueued blocks to execute to guarantee that - // no callback will be called after returning from this method - dispatch_sync(m_callback_queue, ^{}); -} - -void NetworkReachabilityObserver::reachability_changed() -{ - auto current_status = reachability_status(); - - // When observing reachability of the specific host the callback might be called - // several times (because of DNS queries) with the same reachability flags while - // the caller should be notified only when the reachability status is really changed. - if (current_status != m_previous_status) { - m_change_handler(current_status); - m_previous_status = current_status; - } -} - -#endif diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp deleted file mode 100644 index 6c4c127..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/apple/system_configuration.cpp +++ /dev/null @@ -1,98 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/impl/apple/system_configuration.hpp" - -#if NETWORK_REACHABILITY_AVAILABLE - -#include -#include "dlfcn.h" - -using namespace realm; -using namespace realm::_impl; - -SystemConfiguration::SystemConfiguration() -{ - m_framework_handle = dlopen("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration", RTLD_LAZY); - - if (m_framework_handle) { - m_create_with_name = (create_with_name_t)dlsym(m_framework_handle, "SCNetworkReachabilityCreateWithName"); - m_create_with_address = (create_with_address_t)dlsym(m_framework_handle, "SCNetworkReachabilityCreateWithAddress"); - m_set_dispatch_queue = (set_dispatch_queue_t)dlsym(m_framework_handle, "SCNetworkReachabilitySetDispatchQueue"); - m_set_callback = (set_callback_t)dlsym(m_framework_handle, "SCNetworkReachabilitySetCallback"); - m_get_flags = (get_flags_t)dlsym(m_framework_handle, "SCNetworkReachabilityGetFlags"); - } else { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - asl_log(nullptr, nullptr, ASL_LEVEL_WARNING, "network reachability is not available"); -#pragma clang diagnostic pop - } -} - -SystemConfiguration& SystemConfiguration::shared() -{ - static SystemConfiguration system_configuration; - - return system_configuration; -} - -SCNetworkReachabilityRef SystemConfiguration::network_reachability_create_with_name(CFAllocatorRef allocator, - const char *hostname) -{ - if (m_create_with_name) - return m_create_with_name(allocator, hostname); - - return nullptr; -} - -SCNetworkReachabilityRef SystemConfiguration::network_reachability_create_with_address(CFAllocatorRef allocator, - const sockaddr *address) -{ - if (m_create_with_address) - return m_create_with_address(allocator, address); - - return nullptr; -} - -bool SystemConfiguration::network_reachability_set_dispatch_queue(SCNetworkReachabilityRef target, dispatch_queue_t queue) -{ - if (m_set_dispatch_queue) - return m_set_dispatch_queue(target, queue); - - return false; -} - -bool SystemConfiguration::network_reachability_set_callback(SCNetworkReachabilityRef target, - SCNetworkReachabilityCallBack callback, - SCNetworkReachabilityContext *context) -{ - if (m_set_callback) - return m_set_callback(target, callback, context); - - return false; -} - -bool SystemConfiguration::network_reachability_get_flags(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags *flags) -{ - if (m_get_flags) - return m_get_flags(target, flags); - - return false; -} - -#endif // NETWORK_REACHABILITY_AVAILABLE diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp deleted file mode 100644 index 8022847..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_file.cpp +++ /dev/null @@ -1,358 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/impl/sync_file.hpp" - -#include -#include -#include - -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include - -inline static int mkstemp(char* _template) { return _open(_mktemp(_template), _O_CREAT | _O_TEMPORARY, _S_IREAD | _S_IWRITE); } -#else -#include -#endif - - -using File = realm::util::File; - -namespace realm { - -namespace { - -uint8_t value_of_hex_digit(char hex_digit) -{ - if (hex_digit >= '0' && hex_digit <= '9') { - return hex_digit - '0'; - } else if (hex_digit >= 'A' && hex_digit <= 'F') { - return 10 + hex_digit - 'A'; - } else if (hex_digit >= 'a' && hex_digit <= 'f') { - return 10 + hex_digit - 'a'; - } else { - throw std::invalid_argument("Cannot get the value of a character that isn't a hex digit."); - } -} - -bool filename_is_reserved(const std::string& filename) { - return (filename == "." || filename == ".."); -} - -bool character_is_unreserved(char character) -{ - bool is_capital_letter = (character >= 'A' && character <= 'Z'); - bool is_lowercase_letter = (character >= 'a' && character <= 'z'); - bool is_number = (character >= '0' && character <= '9'); - bool is_allowed_symbol = (character == '-' || character == '_' || character == '.'); - return is_capital_letter || is_lowercase_letter || is_number || is_allowed_symbol; -} - -char decoded_char_for(const std::string& percent_encoding, size_t index) -{ - if (index+2 >= percent_encoding.length()) { - throw std::invalid_argument("Malformed string: not enough characters after '%' before end of string."); - } - REALM_ASSERT(percent_encoding[index] == '%'); - return (16*value_of_hex_digit(percent_encoding[index + 1])) + value_of_hex_digit(percent_encoding[index + 2]); -} - -} // (anonymous namespace) - -namespace util { - -std::string make_percent_encoded_string(const std::string& raw_string) -{ - std::string buffer; - buffer.reserve(raw_string.size()); - for (size_t i=0; i 0); - std::string escaped = util::make_percent_encoded_string(local_identity); - if (filename_is_reserved(escaped)) - throw std::invalid_argument("A user can't have an identifier reserved by the filesystem."); - - auto user_path = file_path_by_appending_component(get_base_sync_directory(), - escaped, - util::FilePathType::Directory); - util::try_make_dir(user_path); - return user_path; -} - -void SyncFileManager::remove_user_directory(const std::string& local_identity) const -{ - REALM_ASSERT(local_identity.length() > 0); - const auto& escaped = util::make_percent_encoded_string(local_identity); - if (filename_is_reserved(escaped)) - throw std::invalid_argument("A user can't have an identifier reserved by the filesystem."); - - auto user_path = file_path_by_appending_component(get_base_sync_directory(), - escaped, - util::FilePathType::Directory); - util::try_remove_dir_recursive(user_path); -} - -bool SyncFileManager::try_rename_user_directory(const std::string& old_name, const std::string& new_name) const -{ - REALM_ASSERT_DEBUG(old_name.length() > 0 && new_name.length() > 0); - const auto& old_name_escaped = util::make_percent_encoded_string(old_name); - const auto& new_name_escaped = util::make_percent_encoded_string(new_name); - const std::string& base = get_base_sync_directory(); - if (filename_is_reserved(old_name_escaped) || filename_is_reserved(new_name_escaped)) - throw std::invalid_argument("A user directory can't be renamed using a reserved identifier."); - - const auto& old_path = file_path_by_appending_component(base, old_name_escaped, util::FilePathType::Directory); - const auto& new_path = file_path_by_appending_component(base, new_name_escaped, util::FilePathType::Directory); - - try { - File::move(old_path, new_path); - } catch (File::NotFound const&) { - return false; - } - return true; -} - -bool SyncFileManager::remove_realm(const std::string& absolute_path) const -{ - REALM_ASSERT(absolute_path.length() > 0); - bool success = true; - // Remove the Realm file (e.g. "example.realm"). - success = File::try_remove(absolute_path); - // Remove the lock file (e.g. "example.realm.lock"). - auto lock_path = util::file_path_by_appending_extension(absolute_path, "lock"); - success = File::try_remove(lock_path); - // Remove the management directory (e.g. "example.realm.management"). - auto management_path = util::file_path_by_appending_extension(absolute_path, "management"); - try { - util::try_remove_dir_recursive(management_path); - } - catch (File::AccessError const&) { - success = false; - } - return success; -} - -bool SyncFileManager::copy_realm_file(const std::string& old_path, const std::string& new_path) const -{ - REALM_ASSERT(old_path.length() > 0); - try { - if (File::exists(new_path)) { - return false; - } - File::copy(old_path, new_path); - } - catch (File::NotFound const&) { - return false; - } - catch (File::AccessError const&) { - return false; - } - return true; -} - -bool SyncFileManager::remove_realm(const std::string& local_identity, const std::string& raw_realm_path) const -{ - REALM_ASSERT(local_identity.length() > 0); - REALM_ASSERT(raw_realm_path.length() > 0); - if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path)) - throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem."); - - auto escaped = util::make_percent_encoded_string(raw_realm_path); - auto realm_path = util::file_path_by_appending_component(user_directory(local_identity), escaped); - return remove_realm(realm_path); -} - -std::string SyncFileManager::path(const std::string& local_identity, const std::string& raw_realm_path) const -{ - REALM_ASSERT(local_identity.length() > 0); - REALM_ASSERT(raw_realm_path.length() > 0); - if (filename_is_reserved(local_identity) || filename_is_reserved(raw_realm_path)) - throw std::invalid_argument("A user or Realm can't have an identifier reserved by the filesystem."); - - auto escaped = util::make_percent_encoded_string(raw_realm_path); - return util::file_path_by_appending_component(user_directory(local_identity), escaped); -} - -std::string SyncFileManager::metadata_path() const -{ - auto dir_path = file_path_by_appending_component(get_utility_directory(), - c_metadata_directory, - util::FilePathType::Directory); - util::try_make_dir(dir_path); - return util::file_path_by_appending_component(dir_path, c_metadata_realm); -} - -bool SyncFileManager::remove_metadata_realm() const -{ - auto dir_path = file_path_by_appending_component(get_utility_directory(), - c_metadata_directory, - util::FilePathType::Directory); - try { - util::try_remove_dir_recursive(dir_path); - return true; - } - catch (File::AccessError const&) { - return false; - } -} - -} // realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp deleted file mode 100644 index 99dbee4..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/sync_metadata.cpp +++ /dev/null @@ -1,466 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/impl/sync_metadata.hpp" - -#include "object_schema.hpp" -#include "object_store.hpp" -#include "property.hpp" -#include "results.hpp" -#include "schema.hpp" -#include "util/uuid.hpp" -#if REALM_PLATFORM_APPLE -#include "impl/apple/keychain_helper.hpp" -#endif - -#include -#include - -namespace { -static const char * const c_sync_userMetadata = "UserMetadata"; -static const char * const c_sync_marked_for_removal = "marked_for_removal"; -static const char * const c_sync_identity = "identity"; -static const char * const c_sync_local_uuid = "local_uuid"; -static const char * const c_sync_auth_server_url = "auth_server_url"; -static const char * const c_sync_user_token = "user_token"; -static const char * const c_sync_user_is_admin = "user_is_admin"; - -static const char * const c_sync_fileActionMetadata = "FileActionMetadata"; -static const char * const c_sync_original_name = "original_name"; -static const char * const c_sync_new_name = "new_name"; -static const char * const c_sync_action = "action"; -static const char * const c_sync_url = "url"; - -static const char * const c_sync_clientMetadata = "ClientMetadata"; -static const char * const c_sync_uuid = "uuid"; - -realm::Schema make_schema() -{ - using namespace realm; - return Schema{ - {c_sync_userMetadata, { - {c_sync_identity, PropertyType::String}, - {c_sync_local_uuid, PropertyType::String}, - {c_sync_marked_for_removal, PropertyType::Bool}, - {c_sync_user_token, PropertyType::String|PropertyType::Nullable}, - {c_sync_auth_server_url, PropertyType::String}, - {c_sync_user_is_admin, PropertyType::Bool}, - }}, - {c_sync_fileActionMetadata, { - {c_sync_original_name, PropertyType::String, Property::IsPrimary{true}}, - {c_sync_new_name, PropertyType::String|PropertyType::Nullable}, - {c_sync_action, PropertyType::Int}, - {c_sync_url, PropertyType::String}, - {c_sync_identity, PropertyType::String}, - }}, - {c_sync_clientMetadata, { - {c_sync_uuid, PropertyType::String}, - }} - }; -} - -} // anonymous namespace - -namespace realm { - -// MARK: - Sync metadata manager - -SyncMetadataManager::SyncMetadataManager(std::string path, - bool should_encrypt, - util::Optional> encryption_key) -{ - constexpr uint64_t SCHEMA_VERSION = 2; - - Realm::Config config; - config.automatic_change_notifications = false; - config.path = path; - config.schema = make_schema(); - config.schema_version = SCHEMA_VERSION; - config.schema_mode = SchemaMode::Automatic; -#if REALM_PLATFORM_APPLE - if (should_encrypt && !encryption_key) { - encryption_key = keychain::metadata_realm_encryption_key(File::exists(path)); - } -#endif - if (should_encrypt) { - if (!encryption_key) { - throw std::invalid_argument("Metadata Realm encryption was specified, but no encryption key was provided."); - } - config.encryption_key = std::move(*encryption_key); - } - - config.migration_function = [](SharedRealm old_realm, SharedRealm realm, Schema&) { - if (old_realm->schema_version() < 2) { - TableRef old_table = ObjectStore::table_for_object_type(old_realm->read_group(), c_sync_userMetadata); - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); - - // Get all the SyncUserMetadata objects. - Results results(old_realm, *old_table); - - // Column indices. - size_t old_idx_identity = old_table->get_column_index(c_sync_identity); - size_t old_idx_url = old_table->get_column_index(c_sync_auth_server_url); - size_t idx_local_uuid = table->get_column_index(c_sync_local_uuid); - size_t idx_url = table->get_column_index(c_sync_auth_server_url); - - for (size_t i = 0; i < results.size(); i++) { - RowExpr entry = results.get(i); - // Set the UUID equal to the user identity for existing users. - auto identity = entry.get_string(old_idx_identity); - table->set_string(idx_local_uuid, entry.get_index(), identity); - // Migrate the auth server URLs to a non-nullable property. - auto url = entry.get_string(old_idx_url); - table->set_string(idx_url, entry.get_index(), url.is_null() ? "" : url); - } - } - }; - - SharedRealm realm = Realm::get_shared_realm(config); - - // Get data about the (hardcoded) schemas - auto object_schema = realm->schema().find(c_sync_userMetadata); - m_user_schema = { - object_schema->persisted_properties[0].table_column, - object_schema->persisted_properties[1].table_column, - object_schema->persisted_properties[2].table_column, - object_schema->persisted_properties[3].table_column, - object_schema->persisted_properties[4].table_column, - object_schema->persisted_properties[5].table_column, - }; - - object_schema = realm->schema().find(c_sync_fileActionMetadata); - m_file_action_schema = { - object_schema->persisted_properties[0].table_column, - object_schema->persisted_properties[1].table_column, - object_schema->persisted_properties[2].table_column, - object_schema->persisted_properties[3].table_column, - object_schema->persisted_properties[4].table_column, - }; - - object_schema = realm->schema().find(c_sync_clientMetadata); - m_client_schema = { - object_schema->persisted_properties[0].table_column, - }; - - m_metadata_config = std::move(config); - - m_client_uuid = [&]() -> std::string { - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_clientMetadata); - if (table->is_empty()) { - realm->begin_transaction(); - if (table->is_empty()) { - size_t idx = table->add_empty_row(); - REALM_ASSERT_DEBUG(idx == 0); - auto uuid = uuid_string(); - table->set_string(m_client_schema.idx_uuid, idx, uuid); - realm->commit_transaction(); - return uuid; - } - realm->cancel_transaction(); - } - return table->get_string(m_client_schema.idx_uuid, 0); - }(); -} - -SyncUserMetadataResults SyncMetadataManager::all_unmarked_users() const -{ - return get_users(false); -} - -SyncUserMetadataResults SyncMetadataManager::all_users_marked_for_removal() const -{ - return get_users(true); -} - -SyncUserMetadataResults SyncMetadataManager::get_users(bool marked) const -{ - auto realm = get_realm(); - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); - Query query = table->where().equal(m_user_schema.idx_marked_for_removal, marked); - - Results results(realm, std::move(query)); - return SyncUserMetadataResults(std::move(results), std::move(realm), m_user_schema); -} - -SyncFileActionMetadataResults SyncMetadataManager::all_pending_actions() const -{ - auto realm = get_realm(); - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata); - Results results(realm, table->where()); - return SyncFileActionMetadataResults(std::move(results), std::move(realm), m_file_action_schema); -} - -util::Optional SyncMetadataManager::get_or_make_user_metadata(const std::string& identity, - const std::string& url, - bool make_if_absent) const -{ - auto realm = get_realm(); - auto& schema = m_user_schema; - - // Retrieve or create the row for this object. - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_userMetadata); - Query query = table->where().equal(schema.idx_identity, identity).equal(schema.idx_auth_server_url, url); - Results results(realm, std::move(query)); - REALM_ASSERT_DEBUG(results.size() < 2); - auto row = results.first(); - - if (!row) { - if (!make_if_absent) - return none; - - realm->begin_transaction(); - // Check the results again. - row = results.first(); - if (!row) { - auto row = table->get(table->add_empty_row()); - std::string uuid = util::uuid_string(); - row.set_string(schema.idx_identity, identity); - row.set_string(schema.idx_auth_server_url, url); - row.set_string(schema.idx_local_uuid, uuid); - row.set_bool(schema.idx_user_is_admin, false); - row.set_bool(schema.idx_marked_for_removal, false); - realm->commit_transaction(); - return SyncUserMetadata(schema, std::move(realm), std::move(row)); - } else { - // Someone beat us to adding this user. - if (row->get_bool(schema.idx_marked_for_removal)) { - // User is dead. Revive or return none. - if (make_if_absent) { - row->set_bool(schema.idx_marked_for_removal, false); - realm->commit_transaction(); - } else { - realm->cancel_transaction(); - return none; - } - } else { - // User is alive, nothing else to do. - realm->cancel_transaction(); - } - return SyncUserMetadata(schema, std::move(realm), std::move(*row)); - } - } - - // Got an existing user. - if (row->get_bool(schema.idx_marked_for_removal)) { - // User is dead. Revive or return none. - if (make_if_absent) { - realm->begin_transaction(); - row->set_bool(schema.idx_marked_for_removal, false); - realm->commit_transaction(); - } else { - return none; - } - } - return SyncUserMetadata(schema, std::move(realm), std::move(*row)); -} - -void SyncMetadataManager::make_file_action_metadata(StringData original_name, - StringData url, - StringData local_uuid, - SyncFileActionMetadata::Action action, - StringData new_name) const -{ - // This function can't use get_shared_realm() because it's called on a - // background thread and that's currently not supported by the libuv - // implementation of EventLoopSignal - std::unique_ptr history; - std::unique_ptr shared_group; - std::unique_ptr read_only_group; - Realm::open_with_config(m_metadata_config, history, shared_group, read_only_group, nullptr); - - // Retrieve or create the row for this object. - WriteTransaction wt(*shared_group); - TableRef table = ObjectStore::table_for_object_type(wt.get_group(), c_sync_fileActionMetadata); - - auto& schema = m_file_action_schema; - size_t row_idx = table->find_first_string(schema.idx_original_name, original_name); - if (row_idx == not_found) { - row_idx = table->add_empty_row(); - table->set_string(schema.idx_original_name, row_idx, original_name); - } - table->set_string(schema.idx_new_name, row_idx, new_name); - table->set_int(schema.idx_action, row_idx, static_cast(action)); - table->set_string(schema.idx_url, row_idx, url); - table->set_string(schema.idx_user_identity, row_idx, local_uuid); - wt.commit(); -} - -util::Optional SyncMetadataManager::get_file_action_metadata(StringData original_name) const -{ - auto realm = get_realm(); - auto& schema = m_file_action_schema; - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), c_sync_fileActionMetadata); - size_t row_idx = table->find_first_string(schema.idx_original_name, original_name); - if (row_idx == not_found) - return none; - - return SyncFileActionMetadata(std::move(schema), std::move(realm), table->get(row_idx)); -} - -std::shared_ptr SyncMetadataManager::get_realm() const -{ - auto realm = Realm::get_shared_realm(m_metadata_config); - realm->refresh(); - return realm; -} - -// MARK: - Sync user metadata - -SyncUserMetadata::SyncUserMetadata(Schema schema, SharedRealm realm, RowExpr row) -: m_realm(std::move(realm)) -, m_schema(std::move(schema)) -, m_row(row) -{ } - -std::string SyncUserMetadata::identity() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_identity); -} - -std::string SyncUserMetadata::local_uuid() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_local_uuid); -} - -util::Optional SyncUserMetadata::user_token() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - StringData result = m_row.get_string(m_schema.idx_user_token); - return result.is_null() ? util::none : util::make_optional(std::string(result)); -} - -std::string SyncUserMetadata::auth_server_url() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_auth_server_url); -} - -bool SyncUserMetadata::is_admin() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_bool(m_schema.idx_user_is_admin); -} - -void SyncUserMetadata::set_user_token(util::Optional user_token) -{ - if (m_invalid) - return; - - REALM_ASSERT_DEBUG(m_realm); - m_realm->verify_thread(); - m_realm->begin_transaction(); - m_row.set_string(m_schema.idx_user_token, *user_token); - m_realm->commit_transaction(); -} - -void SyncUserMetadata::set_is_admin(bool is_admin) -{ - if (m_invalid) - return; - - REALM_ASSERT_DEBUG(m_realm); - m_realm->verify_thread(); - m_realm->begin_transaction(); - m_row.set_bool(m_schema.idx_user_is_admin, is_admin); - m_realm->commit_transaction(); -} - -void SyncUserMetadata::mark_for_removal() -{ - if (m_invalid) - return; - - m_realm->verify_thread(); - m_realm->begin_transaction(); - m_row.set_bool(m_schema.idx_marked_for_removal, true); - m_realm->commit_transaction(); -} - -void SyncUserMetadata::remove() -{ - m_invalid = true; - m_realm->begin_transaction(); - TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_userMetadata); - table->move_last_over(m_row.get_index()); - m_realm->commit_transaction(); - m_realm = nullptr; -} - -// MARK: - File action metadata - -SyncFileActionMetadata::SyncFileActionMetadata(Schema schema, SharedRealm realm, RowExpr row) -: m_realm(std::move(realm)) -, m_schema(std::move(schema)) -, m_row(row) -{ } - -std::string SyncFileActionMetadata::original_name() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_original_name); -} - -util::Optional SyncFileActionMetadata::new_name() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - StringData result = m_row.get_string(m_schema.idx_new_name); - return result.is_null() ? util::none : util::make_optional(std::string(result)); -} - -std::string SyncFileActionMetadata::user_local_uuid() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_user_identity); -} - -SyncFileActionMetadata::Action SyncFileActionMetadata::action() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return static_cast(m_row.get_int(m_schema.idx_action)); -} - -std::string SyncFileActionMetadata::url() const -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - return m_row.get_string(m_schema.idx_url); -} - -void SyncFileActionMetadata::remove() -{ - REALM_ASSERT(m_realm); - m_realm->verify_thread(); - m_realm->begin_transaction(); - TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), c_sync_fileActionMetadata); - table->move_last_over(m_row.get_index()); - m_realm->commit_transaction(); - m_realm = nullptr; -} - -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp deleted file mode 100644 index b11b397..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/impl/work_queue.cpp +++ /dev/null @@ -1,80 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2018 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/impl/work_queue.hpp" - -#include - -namespace realm { -namespace _impl { -namespace partial_sync { - -WorkQueue::~WorkQueue() -{ - { - std::unique_lock lock(m_mutex); - m_stopping = true; - } - m_cv.notify_one(); - - if (m_thread.joinable()) - m_thread.join(); -} - -void WorkQueue::enqueue(std::function function) -{ - { - std::unique_lock lock(m_mutex); - m_queue.push_back(std::move(function)); - - if (m_stopped) - create_thread(); - } - m_cv.notify_one(); -} - -void WorkQueue::create_thread() -{ - if (m_thread.joinable()) - m_thread.join(); - - m_thread = std::thread([this] { - std::vector> queue; - - std::unique_lock lock(m_mutex); - while (!m_stopping && - m_cv.wait_for(lock, std::chrono::milliseconds(500), - [&] { return !m_queue.empty() || m_stopping; })) { - - swap(queue, m_queue); - - lock.unlock(); - for (auto& f : queue) - f(); - queue.clear(); - lock.lock(); - } - - m_stopped = true; - }); - m_stopped = false; -} - -} // namespace partial_sync -} // namespace _impl -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp deleted file mode 100644 index 1b104c6..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/partial_sync.cpp +++ /dev/null @@ -1,877 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/partial_sync.hpp" - -#include "impl/collection_notifier.hpp" -#include "impl/notification_wrapper.hpp" -#include "impl/object_accessor_impl.hpp" -#include "impl/realm_coordinator.hpp" -#include "object_schema.hpp" -#include "results.hpp" -#include "shared_realm.hpp" -#include "sync/impl/work_queue.hpp" -#include "sync/subscription_state.hpp" -#include "sync/sync_config.hpp" -#include "sync/sync_session.hpp" - -#include -#include - -#include -#include - -using namespace std::chrono; - -namespace { - - // Delete all subscriptions that are no longer relevant. - // This method must be called within a write transaction. - void cleanup_subscriptions(realm::Group& group, realm::Timestamp now) - { - // Remove all subscriptions no longer considered "active" - // "inactive" is currently defined as any subscription with an `expires_at` < now()` - // - // Note, that we do not check if someone is actively using the subscription right now (this - // is also hard to get right). This does leave some loop holes where a subscription might be - // removed while still in use. E.g. consider a Kiosk app showing a screen 24/7 with a background - // job that accidentially triggers the cleanup codepath. This case is considered rare, but should - // still be documented. - auto table = realm::ObjectStore::table_for_object_type(group, realm::partial_sync::result_sets_type_name); - - size_t expires_at_col_ndx = table->get_column_index(realm::partial_sync::property_expires_at); - realm::TableView results = table->where().less(expires_at_col_ndx, now).find_all(); - results.clear(realm::RemoveMode::unordered); - } - - // Calculates the expiry date, claming at the high end if a timestamp overflows - realm::Timestamp calculate_expiry_date(realm::Timestamp starting_time, int64_t user_ttl_ms) - { - auto tp = starting_time.get_time_point(); - using time_point = decltype(tp); - milliseconds ttl(user_ttl_ms); - if (time_point::max() - ttl < tp) - return time_point::max(); - return tp + ttl; - } - - using namespace ::realm; - using namespace ::realm::partial_sync; - struct ParitalSyncProperty { - const char *name; - DataType type; - bool nullable; - bool indexed; - }; - - static constexpr const ParitalSyncProperty s_partial_sync_schema[] = { - {property_query, type_String, false, false}, - {property_matches_property_name, type_String, false, false}, - {property_status, type_Int, false, false}, - {property_error_message, type_String, false, false}, - {property_query_parse_counter, type_Int, false, false}, - - // Add columns not required by Sync, but used by the bindings to offer better tracking of subscriptions. - // These columns are not automatically added by the server, so we need to add them manually if needed. - - // Name used to uniquely identify a subscription. If a name isn't provided for a subscription one will be - // autogenerated. - {property_name, type_String, false, true}, - - // Timestamp for when then the subscription is created. This should only be set the first time the subscription - // is created. - {property_created_at, type_Timestamp, false, false}, - - // Timestamp for when the subscription is either updated or someone resubscribes to it. - {property_updated_at, type_Timestamp, false, false}, - - // Relative time-to-live in milliseconds. This indicates the period from when a subscription was last updated - // to when it isn't considered valid anymore and can be safely deleted. Realm will attempt to perform this - // cleanup automatically either when the app is started or someone discards the subscription token for it. - {property_time_to_live, type_Int, true, false}, // null = infinite TTL - - // Timestamp representing the fixed point in time when this subscription isn't valid anymore and can - // be safely deleted. This value should be considered read-only from the perspective of any Bindings - // and should never be modified by itself, but only updated whenever the `updatedAt` or `timefield is. - {property_expires_at, type_Timestamp, true, false}, // null = Subscription never expires - }; -} - -namespace realm { - -namespace _impl { -using namespace ::realm::partial_sync; - -void initialize_schema(Group& group) -{ - std::string result_sets_table_name = ObjectStore::table_name_for_object_type(result_sets_type_name); - TableRef table = group.get_table(result_sets_table_name); - if (!table) { - // Create the schema required by Sync - table = sync::create_table(group, result_sets_table_name); - } - - // Create all required properties which don't already exist - for (auto& property : s_partial_sync_schema) { - if (table->get_column_index(property.name) != npos) - continue; - size_t idx = table->add_column(property.type, property.name, property.nullable); - if (property.indexed) - table->add_search_index(idx); - } - - // Remove any subscriptions no longer relevant - cleanup_subscriptions(group, system_clock::now()); -} - -void ensure_partial_sync_schema_initialized(Realm& realm) -{ - auto was_in_read = realm.is_in_read_transaction(); - auto cleanup = util::make_scope_exit([&]() noexcept { - if (realm.is_in_transaction()) - realm.cancel_transaction(); - if (!was_in_read) - realm.invalidate(); - }); - - auto has_all_required_columns = [](auto& table) -> bool { - return std::all_of(std::begin(s_partial_sync_schema), std::end(s_partial_sync_schema), - [&](auto& property) { return table.get_column_index(property.name) != npos; }); - }; - - auto& group = realm.read_group(); - // Check if the result sets table already has the expected number of columns - auto table = ObjectStore::table_for_object_type(group, result_sets_type_name); - if (table && has_all_required_columns(*table)) - return; - - realm.begin_transaction(); - // Recheck after starting the transaction as it refreshes - if (!table) - table = ObjectStore::table_for_object_type(group, result_sets_type_name); - if (table && has_all_required_columns(*table)) - return; - initialize_schema(group); - realm.commit_transaction(); -} - -// A stripped-down version of WriteTransaction that can promote an existing read transaction -// and that notifies the sync session after committing a change. -class WriteTransactionNotifyingSync { -public: - WriteTransactionNotifyingSync(Realm::Config const& config, SharedGroup& sg) - : m_config(config) - , m_shared_group(&sg) - { - if (m_shared_group->get_transact_stage() == SharedGroup::transact_Reading) - LangBindHelper::promote_to_write(*m_shared_group); - else - m_shared_group->begin_write(); - } - - ~WriteTransactionNotifyingSync() - { - if (m_shared_group) - m_shared_group->rollback(); - } - - SharedGroup::version_type commit() - { - REALM_ASSERT(m_shared_group); - auto version = m_shared_group->commit(); - m_shared_group = nullptr; - - auto session = SyncManager::shared().get_session(m_config.path, *m_config.sync_config, false); - SyncSession::Internal::nonsync_transact_notify(*session, version); - return version; - } - - void rollback() - { - REALM_ASSERT(m_shared_group); - m_shared_group->rollback(); - m_shared_group = nullptr; - } - - Group& get_group() const noexcept - { - REALM_ASSERT(m_shared_group); - return _impl::SharedGroupFriend::get_group(*m_shared_group); - } - -private: - Realm::Config const& m_config; - SharedGroup* m_shared_group; -}; - -// Provides a convenient way for code in this file to access private details of `Realm` -// without having to add friend declarations for each individual use. -class PartialSyncHelper { -public: - static decltype(auto) get_shared_group(Realm& realm) - { - return Realm::Internal::get_shared_group(realm); - } - - static decltype(auto) get_coordinator(Realm& realm) - { - return Realm::Internal::get_coordinator(realm); - } -}; - -template -static auto export_for_handover(Realm& realm, Args&&... args) -{ - auto& sg = *PartialSyncHelper::get_shared_group(realm); - sg.pin_version(); - auto handover = sg.export_for_handover(std::forward(args)...); - // We need to store the handover object in a shared_ptr because it's captured - // in a std::function<>, which requires copyable objects - return std::make_shared(std::move(handover)); -} - -template -static auto import_from_handover(SharedGroup& sg, std::unique_ptr>& handover) -{ - sg.begin_read(handover->version); - auto obj = sg.import_from_handover(std::move(handover)); - sg.unpin_version(sg.get_version_of_current_transaction()); - return *obj; -} - -} // namespace _impl - -namespace partial_sync { - -InvalidRealmStateException::InvalidRealmStateException(const std::string& msg) -: std::logic_error(msg) -{} - -ExistingSubscriptionException::ExistingSubscriptionException(const std::string& msg) -: std::runtime_error(msg) -{} - -QueryTypeMismatchException::QueryTypeMismatchException(const std::string& msg) -: std::logic_error(msg) -{} - -namespace { - -template -void with_open_shared_group(Realm::Config const& config, F&& function) -{ - std::unique_ptr history; - std::unique_ptr sg; - std::unique_ptr read_only_group; - Realm::open_with_config(config, history, sg, read_only_group, nullptr); - - function(*sg); -} - -struct ResultSetsColumns { - ResultSetsColumns(Table& table, std::string const& matches_property_name) - { - name = table.get_column_index(property_name); - REALM_ASSERT(name != npos); - - query = table.get_column_index(property_query); - REALM_ASSERT(query != npos); - - error_message = table.get_column_index(property_error_message); - REALM_ASSERT(error_message != npos); - - status = table.get_column_index(property_status); - REALM_ASSERT(status != npos); - - this->matches_property_name = table.get_column_index(property_matches_property_name); - REALM_ASSERT(this->matches_property_name != npos); - - created_at = table.get_column_index(property_created_at); - REALM_ASSERT(created_at != npos); - - updated_at = table.get_column_index(property_updated_at); - REALM_ASSERT(updated_at != npos); - - expires_at = table.get_column_index(property_expires_at); - REALM_ASSERT(expires_at != npos); - - time_to_live = table.get_column_index(property_time_to_live); - REALM_ASSERT(time_to_live != npos); - - // This may be `npos` if the column does not yet exist. - matches_property = table.get_column_index(matches_property_name); - } - - size_t name; - size_t query; - size_t error_message; - size_t status; - size_t matches_property_name; - size_t matches_property; - size_t created_at; - size_t updated_at; - size_t expires_at; - size_t time_to_live; -}; - -// Performs the logic of actually writing the subscription (if needed) to the Realm and making sure -// that the `matches_property` field is setup correctly. This method will throw if the query cannot -// be serialized or the name is already used by another subscription. -// -// The row of the resulting subscription is returned. If an old subscription exists that matches -// the one about to be created, a new subscription is not created, but the old one is returned -// instead. -// -// If `update = true` and if a subscription with `name` already exists, its query and time_to_live -// will be updated instead of an exception being thrown if the query parsed in was different than -// the persisted query. -Row write_subscription(std::string const& object_type, std::string const& name, std::string const& query, - util::Optional time_to_live_ms, bool update, Group& group) -{ - Timestamp now = system_clock::now(); - auto matches_property = std::string(object_type) + "_matches"; - - auto table = ObjectStore::table_for_object_type(group, result_sets_type_name); - ResultSetsColumns columns(*table, matches_property); - - // Update schema if needed. - if (columns.matches_property == npos) { - auto target_table = ObjectStore::table_for_object_type(group, object_type); - columns.matches_property = table->add_column_link(type_LinkList, matches_property, *target_table); - } - else { - // FIXME: Validate that the column type and link target are correct. - } - - // Find existing subscription (if any) - auto row_ndx = table->find_first_string(columns.name, name); - if (row_ndx != npos) { - - // Check that we don't attempt to replace an existing query with a query on a new type. - // There is nothing that prevents Sync from handling this, but allowing it will complicate - // Binding API's, so for now it is disallowed. - auto existing_matching_property = table->get_string(columns.matches_property_name, row_ndx); - if (existing_matching_property != matches_property) { - throw QueryTypeMismatchException(util::format("Replacing an existing query with a query on " - "a different type is not allowed: %1 vs. %2 for %3", - existing_matching_property, matches_property, name)); - } - - // If an subscription exist, we only update the query and TTL if allowed to. - // TODO: Consider how Binding API's are going to use this. It might make sense to disallow - // updating TTL using this API and instead require updates to TTL to go through a managed Subscription. - if (update) { - // If the query changed we must reset state to force the server to re-evaluate the subscription. - if (table->get_string(columns.query, row_ndx) != query) { - table->set_string(columns.error_message, row_ndx, ""); - table->set_int(columns.status, row_ndx, 0); - } - table->set_string(columns.query, row_ndx, query); - table->set(columns.time_to_live, row_ndx, time_to_live_ms); - } - else { - StringData existing_query = table->get_string(columns.query, row_ndx); - if (existing_query != query) - throw ExistingSubscriptionException(util::format("An existing subscription exists with the name '%1' " - "but with a different query: '%1' vs '%2'", - name, existing_query, query)); - } - - } - else { - // No existing subscription was found. Create a new one - row_ndx = sync::create_object(group, *table); - table->set_string(columns.name, row_ndx, name); - table->set_string(columns.query, row_ndx, query); - table->set_string(columns.matches_property_name, row_ndx, matches_property); - table->set_timestamp(columns.created_at, row_ndx, now); - table->set(columns.time_to_live, row_ndx, time_to_live_ms); - } - - // Always set updated_at/expires_at when a subscription is touched, no matter if it is new, updated or someone just - // resubscribes. - table->set_timestamp(columns.updated_at, row_ndx, now); - if (table->is_null(columns.time_to_live, row_ndx) || table->get_int(columns.time_to_live, row_ndx) == std::numeric_limits::max()) { - table->set_null(columns.expires_at, row_ndx); - } - else { - table->set_timestamp(columns.expires_at, row_ndx, calculate_expiry_date(now, table->get_int(columns.time_to_live, row_ndx))); - } - - // Fetch subscription first and return it. Cleanup needs to be performed after as it might delete subscription - // causing the row_ndx to change. - Row subscription = table->get(row_ndx); - cleanup_subscriptions(group, now); - return subscription; -} - -void enqueue_registration(Realm& realm, std::string object_type, std::string query, std::string name, - util::Optional time_to_live, bool update, - std::function callback) -{ - auto config = realm.config(); - - auto& work_queue = _impl::PartialSyncHelper::get_coordinator(realm).partial_sync_work_queue(); - work_queue.enqueue([object_type=std::move(object_type), query=std::move(query), name=std::move(name), - callback=std::move(callback), config=std::move(config), time_to_live=time_to_live, update=update] { - try { - with_open_shared_group(config, [&](SharedGroup& sg) { - _impl::WriteTransactionNotifyingSync write(config, sg); - write_subscription(object_type, name, query, time_to_live, update, write.get_group()); - write.commit(); - }); - } catch (...) { - callback(std::current_exception()); - return; - } - - callback(nullptr); - }); -} - -void enqueue_unregistration(Object result_set, std::function callback) -{ - auto realm = result_set.realm(); - auto config = realm->config(); - auto& work_queue = _impl::PartialSyncHelper::get_coordinator(*realm).partial_sync_work_queue(); - - // Export a reference to the __ResultSets row so we can hand it to the worker thread. - auto handover = _impl::export_for_handover(*realm, Row(result_set.row())); - - work_queue.enqueue([handover=std::move(handover), callback=std::move(callback), - config=std::move(config)] () { - with_open_shared_group(config, [&](SharedGroup& sg) { - Row row = _impl::import_from_handover(sg, *handover); - _impl::WriteTransactionNotifyingSync write(config, sg); - if (row.is_attached()) { - row.move_last_over(); - write.commit(); - } - else { - write.rollback(); - } - }); - callback(); - }); -} - -template -void enqueue_unregistration(Results const& result_set, std::shared_ptr notifier, - std::function callback) -{ - auto realm = result_set.get_realm(); - auto config = realm->config(); - auto& work_queue = _impl::PartialSyncHelper::get_coordinator(*realm).partial_sync_work_queue(); - - // Export a reference to the query which will match the __ResultSets row - // once it's created so we can hand it to the worker thread - Query q = result_set.get_query(); - auto handover = _impl::export_for_handover(*realm, q, MutableSourcePayload::Move); - - work_queue.enqueue([handover=std::move(handover), callback=std::move(callback), - config=std::move(config), notifier=std::move(notifier)] () { - with_open_shared_group(config, [&](SharedGroup& sg) { - Query query = _impl::import_from_handover(sg, *handover); - - // If creating the subscription failed there might be another - // pre-existing subscription which matches our query, so we need to - // not remove that - if (notifier->failed()) - return; - - _impl::WriteTransactionNotifyingSync write(config, sg); - size_t row = query.find(); - if (row != npos) { - query.get_table()->move_last_over(row); - write.commit(); - } - else { - // If unsubscribe() is called twice before the subscription is - // even created the row might already be gone - write.rollback(); - } - }); - callback(); - }); -} - -std::string default_name_for_query(const std::string& query, const std::string& object_type) -{ - return util::format("[%1] %2", object_type, query); -} - -} // unnamed namespace - - -struct Subscription::Notifier : public _impl::CollectionNotifier { - enum State { - Creating, - Complete, - Removed, - }; - - Notifier(std::shared_ptr realm) - : _impl::CollectionNotifier(std::move(realm)) - , m_coordinator(&_impl::PartialSyncHelper::get_coordinator(*get_realm())) - { - } - - void release_data() noexcept override { } - void run() override - { - std::unique_lock lock(m_mutex); - if (m_has_results_to_deliver) { - // Mark the object as being modified so that CollectionNotifier is aware - // that there are changes to deliver. - m_changes.modify(0); - } - } - - void deliver(SharedGroup&) override - { - std::unique_lock lock(m_mutex); - m_error = m_pending_error; - m_pending_error = nullptr; - - m_state = m_pending_state; - m_has_results_to_deliver = false; - } - - void finished_subscribing(std::exception_ptr error) - { - { - std::unique_lock lock(m_mutex); - m_pending_error = error; - m_pending_state = Complete; - m_has_results_to_deliver = true; - m_failed = error != nullptr; - } - - // Trigger processing of change notifications. - m_coordinator->wake_up_notifier_worker(); - } - - void finished_unsubscribing() - { - { - std::unique_lock lock(m_mutex); - - m_pending_state = Removed; - m_has_results_to_deliver = true; - } - - // Trigger processing of change notifications. - m_coordinator->wake_up_notifier_worker(); - } - - std::exception_ptr error() const - { - std::unique_lock lock(m_mutex); - return m_error; - } - - State state() const - { - std::unique_lock lock(m_mutex); - return m_state; - } - - bool failed() const - { - std::unique_lock lock(m_mutex); - return m_failed; - } - -private: - void do_attach_to(SharedGroup&) override { } - void do_detach_from(SharedGroup&) override { } - - void do_prepare_handover(SharedGroup&) override - { - add_changes(std::move(m_changes)); - } - - bool do_add_required_change_info(_impl::TransactionChangeInfo&) override { return false; } - bool prepare_to_deliver() override - { - std::lock_guard lock(m_mutex); - return m_has_results_to_deliver; - - } - - _impl::RealmCoordinator *m_coordinator; - - mutable std::mutex m_mutex; - _impl::CollectionChangeBuilder m_changes; - std::exception_ptr m_pending_error = nullptr; - std::exception_ptr m_error = nullptr; - bool m_has_results_to_deliver = false; - bool m_failed = false; - - State m_state = Creating; - State m_pending_state = Creating; -}; - -Subscription subscribe(Results const& results, SubscriptionOptions options) -{ - auto realm = results.get_realm(); - - auto sync_config = realm->config().sync_config; - if (!sync_config || !sync_config->is_partial) - throw InvalidRealmStateException("A Subscription can only be created in a Query-based Realm."); - - auto query = results.get_query().get_description(); // Throws if the query cannot be serialized. - if (!results.get_descriptor_ordering().is_empty()) { - query += " " + results.get_descriptor_ordering().get_description(results.get_query().get_table()); - } - - if (options.inclusions.is_valid()) { - query += " " + options.inclusions.get_description(results.get_query().get_table()); - } - - std::string name = options.user_provided_name ? std::move(*options.user_provided_name) - : default_name_for_query(query, results.get_object_type()); - - Subscription subscription(name, results.get_object_type(), realm); - std::weak_ptr weak_notifier = subscription.m_notifier; - enqueue_registration(*realm, results.get_object_type(), std::move(query), std::move(name), std::move(options.time_to_live_ms), options.update, - [weak_notifier=std::move(weak_notifier)](std::exception_ptr error) { - if (auto notifier = weak_notifier.lock()) - notifier->finished_subscribing(error); - }); - return subscription; -} - -Row subscribe_blocking(Results const& results, util::Optional user_provided_name, - util::Optional time_to_live_ms, bool update) -{ - - auto realm = results.get_realm(); - if (!realm->is_in_transaction()) { - throw InvalidRealmStateException("The subscription can only be created inside a write transaction."); - } - auto sync_config = realm->config().sync_config; - if (!sync_config || !sync_config->is_partial) { - throw InvalidRealmStateException("A Subscription can only be created in a Query-based Realm."); - } - - auto query = results.get_query().get_description(); // Throws if the query cannot be serialized. - if (!results.get_descriptor_ordering().is_empty()) { - query += " " + results.get_descriptor_ordering().get_description(results.get_query().get_table()); - } - std::string name = user_provided_name ? std::move(*user_provided_name) - : default_name_for_query(query, results.get_object_type()); - return write_subscription(results.get_object_type(), name, query, time_to_live_ms, update, realm->read_group()); -} - -void unsubscribe(Subscription& subscription) -{ - if (auto result_set_object = subscription.result_set_object()) { - // The subscription has its result set object, so we can queue up the unsubscription immediately. - std::weak_ptr weak_notifier = subscription.m_notifier; - enqueue_unregistration(*result_set_object, [weak_notifier=std::move(weak_notifier)]() { - if (auto notifier = weak_notifier.lock()) - notifier->finished_unsubscribing(); - }); - return; - } - - switch (subscription.state()) { - case SubscriptionState::Creating: { - // The result set object is in the process of being created. Try unsubscribing again once it exists. - std::weak_ptr weak_notifier = subscription.m_notifier; - enqueue_unregistration(subscription.m_result_sets, subscription.m_notifier, [weak_notifier=std::move(weak_notifier)]() { - if (auto notifier = weak_notifier.lock()) - notifier->finished_unsubscribing(); - }); - return; - } - - case SubscriptionState::Error: - // We encountered an error when creating the subscription. There's nothing to remove, so just - // mark the subscription as removed. - subscription.m_notifier->finished_unsubscribing(); - break; - - case SubscriptionState::Invalidated: - // Nothing to do. We have already removed the subscription. - break; - - case SubscriptionState::Pending: - case SubscriptionState::Complete: - // This should not be reachable as these states require the result set object to exist. - REALM_ASSERT(false); - break; - } -} - -void unsubscribe(Object&& subscription) -{ - REALM_ASSERT(subscription.get_object_schema().name == result_sets_type_name); - auto realm = subscription.realm(); - enqueue_unregistration(std::move(subscription), [=] { - // The partial sync worker thread bypasses the normal machinery which - // would trigger notifications since it does its own notification things - // in the other cases, so manually trigger it here. - _impl::PartialSyncHelper::get_coordinator(*realm).wake_up_notifier_worker(); - }); -} - -Subscription::Subscription(std::string name, std::string object_type, std::shared_ptr realm) -: m_object_schema(realm->read_group(), result_sets_type_name) -{ - // FIXME: Why can't I do this in the initializer list? - m_notifier = std::make_shared(realm); - _impl::RealmCoordinator::register_notifier(m_notifier); - - auto matches_property = std::string(object_type) + "_matches"; - - m_wrapper_created_at = system_clock::now(); - TableRef table = ObjectStore::table_for_object_type(realm->read_group(), result_sets_type_name); - Query query = table->where(); - query.equal(m_object_schema.property_for_name(property_name)->table_column, name); - query.equal(m_object_schema.property_for_name(property_matches_property_name)->table_column, matches_property); - m_result_sets = Results(std::move(realm), std::move(query)); -} - -Subscription::~Subscription() = default; -Subscription::Subscription(Subscription&&) = default; -Subscription& Subscription::operator=(Subscription&&) = default; - -SubscriptionNotificationToken Subscription::add_notification_callback(std::function callback) -{ - auto callback_wrapper = std::make_shared(SubscriptionCallbackWrapper{callback, none}); - auto result_sets_token = m_result_sets.add_notification_callback([this, callback_wrapper] (CollectionChangeSet, std::exception_ptr) { - run_callback(*callback_wrapper); - }); - NotificationToken registration_token(m_notifier, m_notifier->add_callback([this, callback_wrapper] (CollectionChangeSet, std::exception_ptr) { - run_callback(*callback_wrapper); - })); - - return SubscriptionNotificationToken{std::move(registration_token), std::move(result_sets_token)}; -} - -util::Optional Subscription::result_set_object() const -{ - if (m_notifier->state() == Notifier::Complete) { - if (auto row = m_result_sets.first()) - return Object(m_result_sets.get_realm(), m_object_schema, *row); - } - - return util::none; -} - -void Subscription::run_callback(SubscriptionCallbackWrapper& callback_wrapper) { - // Store reference to underlying subscription object the first time we encounter it. - // Used to track if anyone is later deleting it. - if (!m_result_sets_object && m_result_sets.size() > 0) { - auto row = m_result_sets.first().value(); - m_result_sets_object = util::Optional(row); - } - - // Verify this is a state change we actually want to report to the user - auto new_state = state(); - if (callback_wrapper.last_state && callback_wrapper.last_state.value() == new_state) - return; - - callback_wrapper.last_state = util::Optional(new_state); - - // Finally trigger callback - callback_wrapper.callback(); -} - -SubscriptionState Subscription::state() const -{ - // State transitions are complex due to multiple source being able to create and modify the subscriptions. - // This means that there are unavoidable race conditions with regard to the states and we just make - // a best effort to provide a sensible experience for the end user. - // - // In particular this means the following: - // - // - There is no guarantee that a user will see all the states from `Creating -> Pending -> Complete` - // They might only see `Pending -> Complete` or `Complete` - // - // What we do guarantee is: - // - // - States will never be reported twice in a row for the same callback. This could e.g. happen if some property - // like `updated_at` was updated while the status was still `Pending`, but these properties are not important - // until the subscription is actually created. So we intentionally swallow all duplicated state notifications. - // - // - When calling `subscribe()` with `update = true` we will never report `Complete` until the updated subscription - // reaches that state. - - // Errors take precedence over all other notifications - if (m_notifier->error()) - return SubscriptionState::Error; - - // In some cases the subscription already exists. In that case we just report the state of the __ResultSets object. - if (auto object = result_set_object()) { - CppContext context; - auto state = static_cast(any_cast(object->get_property_value(context, property_status))); - auto updated_at = any_cast(object->get_property_value(context, property_updated_at)); - - if (updated_at < m_wrapper_created_at) { - // If the `updated_at` property on an existing subscription wasn't updated after the wrapper was created, - // it meant the query callback triggered before the async write completed. In that case we don't want - // to return the state associated with the subscription before it was updated. So we override the state - // in the actual subscription and return the expected state after the update. - return partial_sync::SubscriptionState::Pending; - } else { - return state; - } - } - - // If no existing subscription exist, we can use the state of the Notifier as an indication of the underlying - // progress. - switch (m_notifier->state()) { - case Notifier::Creating: - return SubscriptionState::Creating; - case Notifier::Removed: - return SubscriptionState::Invalidated; - case Notifier::Complete: - break; - } - - // If we previously had a reference to the subscription and that is now gone, we interpret that as - // someone deleted the subscription (without using the explict unsubscribe API). - if (m_result_sets_object && !m_result_sets_object->is_attached()) { - return SubscriptionState::Invalidated; - } - - // We may not have an object even if the subscription has completed if the completion callback fired - // but the result sets callback is yet to fire. - return SubscriptionState::Creating; -} - -std::exception_ptr Subscription::error() const -{ - if (auto error = m_notifier->error()) - return error; - - if (auto object = result_set_object()) { - CppContext context; - auto message = any_cast(object->get_property_value(context, "error_message")); - if (message.size()) - return make_exception_ptr(std::runtime_error(message)); - } - - return nullptr; -} - -} // namespace partial_sync -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp deleted file mode 100644 index 3adea0a..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_config.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/sync_config.hpp" - -#include "sync/sync_manager.hpp" - -#include - -namespace realm { - -std::string SyncConfig::partial_sync_identifier(const SyncUser& user) -{ - std::string raw_identifier = SyncManager::shared().client_uuid() + "/" + user.local_identity(); - - // The type of the argument to sha1() changed in sync 3.11.1. Implicitly - // convert to either char or unsigned char so that both signatures work. - struct cast { - uint8_t* value; - operator uint8_t*() { return value; } - operator char*() { return reinterpret_cast(value); } - }; - uint8_t identifier[20]; - sync::crypto::sha1(raw_identifier.data(), raw_identifier.size(), cast{&identifier[0]}); - - std::stringstream ss; - ss << std::hex << std::setfill('0'); - for (uint8_t c : identifier) - ss << std::setw(2) << (unsigned)c; - return ss.str(); -} - -std::string SyncConfig::realm_url() const -{ - REALM_ASSERT(reference_realm_url.length() > 0); - REALM_ASSERT(user); - - if (!is_partial) - return reference_realm_url; - - std::string base_url = reference_realm_url; - if (base_url.back() == '/') - base_url.pop_back(); - - if (custom_partial_sync_identifier) - return util::format("%1/__partial/%2", base_url, *custom_partial_sync_identifier); - return util::format("%1/__partial/%2/%3", base_url, user->identity(), partial_sync_identifier(*user)); -} - -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp deleted file mode 100644 index 757e3b8..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_manager.cpp +++ /dev/null @@ -1,534 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/sync_manager.hpp" - -#include "sync/impl/sync_client.hpp" -#include "sync/impl/sync_file.hpp" -#include "sync/impl/sync_metadata.hpp" -#include "sync/sync_session.hpp" -#include "sync/sync_user.hpp" - -using namespace realm; -using namespace realm::_impl; - -constexpr const char SyncManager::c_admin_identity[]; - -SyncManager& SyncManager::shared() -{ - // The singleton is heap-allocated in order to fix an issue when running unit tests where tests would crash after - // they were done running because the manager was destroyed too early. - static SyncManager& manager = *new SyncManager; - return manager; -} - -void SyncManager::configure(SyncClientConfig config) -{ - { - std::lock_guard lock(m_mutex); - m_config = std::move(config); - if (m_sync_client) - return; - } - - struct UserCreationData { - std::string identity; - std::string user_token; - std::string server_url; - bool is_admin; - }; - - std::vector users_to_add; - { - std::lock_guard lock(m_file_system_mutex); - - // Set up the file manager. - if (m_file_manager) { - // Changing the base path for tests requires calling reset_for_testing() - // first, and otherwise isn't supported - REALM_ASSERT(m_file_manager->base_path() == m_config.base_file_path); - } else { - m_file_manager = std::make_unique(m_config.base_file_path); - } - - // Set up the metadata manager, and perform initial loading/purging work. - if (m_metadata_manager || m_config.metadata_mode == MetadataMode::NoMetadata) { - return; - } - - bool encrypt = m_config.metadata_mode == MetadataMode::Encryption; - try { - m_metadata_manager = std::make_unique(m_file_manager->metadata_path(), - encrypt, - m_config.custom_encryption_key); - } catch (RealmFileException const& ex) { - if (m_config.reset_metadata_on_error && m_file_manager->remove_metadata_realm()) { - m_metadata_manager = std::make_unique(m_file_manager->metadata_path(), - encrypt, - std::move(m_config.custom_encryption_key)); - } else { - throw; - } - } - - REALM_ASSERT(m_metadata_manager); - m_client_uuid = m_metadata_manager->client_uuid(); - - // Perform our "on next startup" actions such as deleting Realm files - // which we couldn't delete immediately due to them being in use - std::vector completed_actions; - SyncFileActionMetadataResults file_actions = m_metadata_manager->all_pending_actions(); - for (size_t i = 0; i < file_actions.size(); i++) { - auto file_action = file_actions.get(i); - if (run_file_action(file_action)) { - completed_actions.emplace_back(std::move(file_action)); - } - } - for (auto& action : completed_actions) { - action.remove(); - } - - // Load persisted users into the users map. - SyncUserMetadataResults users = m_metadata_manager->all_unmarked_users(); - for (size_t i = 0; i < users.size(); i++) { - // Note that 'admin' style users are not persisted. - auto user_data = users.get(i); - if (auto user_token = user_data.user_token()) { - users_to_add.push_back(UserCreationData{ - user_data.identity(), - std::move(*user_token), - user_data.auth_server_url(), - user_data.is_admin() - }); - } - } - - // Delete any users marked for death. - std::vector dead_users; - SyncUserMetadataResults users_to_remove = m_metadata_manager->all_users_marked_for_removal(); - dead_users.reserve(users_to_remove.size()); - for (size_t i = 0; i < users_to_remove.size(); i++) { - auto user = users_to_remove.get(i); - // FIXME: delete user data in a different way? (This deletes a logged-out user's data as soon as the app - // launches again, which might not be how some apps want to treat their data.) - try { - m_file_manager->remove_user_directory(user.local_uuid()); - dead_users.emplace_back(std::move(user)); - } catch (util::File::AccessError const&) { - continue; - } - } - for (auto& user : dead_users) { - user.remove(); - } - } - { - std::lock_guard lock(m_user_mutex); - for (auto& user_data : users_to_add) { - auto& identity = user_data.identity; - auto& server_url = user_data.server_url; - auto user = std::make_shared(user_data.user_token, identity, server_url); - user->set_is_admin(user_data.is_admin); - m_users.insert({ {identity, server_url}, std::move(user) }); - } - } -} - -bool SyncManager::immediately_run_file_actions(const std::string& realm_path) -{ - if (!m_metadata_manager) { - return false; - } - if (auto metadata = m_metadata_manager->get_file_action_metadata(realm_path)) { - if (run_file_action(*metadata)) { - metadata->remove(); - return true; - } - } - return false; -} - -// Perform a file action. Returns whether or not the file action can be removed. -bool SyncManager::run_file_action(const SyncFileActionMetadata& md) -{ - switch (md.action()) { - case SyncFileActionMetadata::Action::DeleteRealm: - // Delete all the files for the given Realm. - m_file_manager->remove_realm(md.original_name()); - return true; - case SyncFileActionMetadata::Action::BackUpThenDeleteRealm: - // Copy the primary Realm file to the recovery dir, and then delete the Realm. - auto new_name = md.new_name(); - auto original_name = md.original_name(); - if (!util::File::exists(original_name)) { - // The Realm file doesn't exist anymore. - return true; - } - if (new_name && !util::File::exists(*new_name) && m_file_manager->copy_realm_file(original_name, *new_name)) { - // We successfully copied the Realm file to the recovery directory. - m_file_manager->remove_realm(original_name); - return true; - } - return false; - } - return false; -} - -void SyncManager::reset_for_testing() -{ - std::lock_guard lock(m_file_system_mutex); - m_file_manager = nullptr; - m_metadata_manager = nullptr; - m_client_uuid = util::none; - - { - // Destroy all the users. - std::lock_guard lock(m_user_mutex); - m_users.clear(); - m_admin_token_users.clear(); - } - { - std::lock_guard lock(m_mutex); - - // Stop the client. This will abort any uploads that inactive sessions are waiting for. - if (m_sync_client) - m_sync_client->stop(); - - { - std::lock_guard lock(m_session_mutex); - // Callers of `SyncManager::reset_for_testing` should ensure there are no existing sessions - // prior to calling `reset_for_testing`. - bool no_sessions = !do_has_existing_sessions(); - REALM_ASSERT_RELEASE(no_sessions); - - // Destroy any inactive sessions. - // FIXME: We shouldn't have any inactive sessions at this point! Sessions are expected to - // remain inactive until their final upload completes, at which point they are unregistered - // and destroyed. Our call to `sync::Client::stop` above aborts all uploads, so all sessions - // should have already been destroyed. - m_sessions.clear(); - } - - // Destroy the client now that we have no remaining sessions. - m_sync_client = nullptr; - - // Reset even more state. - m_config = {}; - } -} - -void SyncManager::set_log_level(util::Logger::Level level) noexcept -{ - std::lock_guard lock(m_mutex); - m_config.log_level = level; -} - -void SyncManager::set_logger_factory(SyncLoggerFactory& factory) noexcept -{ - std::lock_guard lock(m_mutex); - m_config.logger_factory = &factory; -} - -std::unique_ptr SyncManager::make_logger() const -{ - if (m_config.logger_factory) { - return m_config.logger_factory->make_logger(m_config.log_level); // Throws - } - - auto stderr_logger = std::make_unique(); // Throws - stderr_logger->set_level_threshold(m_config.log_level); - return std::unique_ptr(stderr_logger.release()); -} - -void SyncManager::set_user_agent(std::string user_agent) -{ - std::lock_guard lock(m_mutex); - m_config.user_agent_application_info = std::move(user_agent); -} - -void SyncManager::set_timeouts(SyncClientTimeouts timeouts) -{ - std::lock_guard lock(m_mutex); - m_config.timeouts = timeouts; -} - -void SyncManager::reconnect() -{ - std::lock_guard lock(m_session_mutex); - for (auto& it : m_sessions) { - it.second->handle_reconnect(); - } -} - -util::Logger::Level SyncManager::log_level() const noexcept -{ - std::lock_guard lock(m_mutex); - return m_config.log_level; -} - -bool SyncManager::perform_metadata_update(std::function update_function) const -{ - std::lock_guard lock(m_file_system_mutex); - if (!m_metadata_manager) { - return false; - } - update_function(*m_metadata_manager); - return true; -} - -std::shared_ptr SyncManager::get_user(const SyncUserIdentifier& identifier, std::string refresh_token) -{ - std::lock_guard lock(m_user_mutex); - auto it = m_users.find(identifier); - if (it == m_users.end()) { - // No existing user. - auto new_user = std::make_shared(std::move(refresh_token), - identifier.user_id, - identifier.auth_server_url, - none, - SyncUser::TokenType::Normal); - m_users.insert({ identifier, new_user }); - return new_user; - } else { - auto user = it->second; - if (user->state() == SyncUser::State::Error) { - return nullptr; - } - user->update_refresh_token(std::move(refresh_token)); - return user; - } -} - -std::shared_ptr SyncManager::get_admin_token_user_from_identity(const std::string& identity, - util::Optional server_url, - const std::string& token) -{ - if (server_url) - return get_admin_token_user(*server_url, token, identity); - - std::lock_guard lock(m_user_mutex); - // Look up the user based off the identity. - // No server URL, so no migration possible. - auto it = m_admin_token_users.find(identity); - if (it == m_admin_token_users.end()) { - // No existing user. - auto new_user = std::make_shared(token, - c_admin_identity, - std::move(server_url), - identity, - SyncUser::TokenType::Admin); - m_admin_token_users.insert({ identity, new_user }); - return new_user; - } else { - return it->second; - } -} - -std::shared_ptr SyncManager::get_admin_token_user(const std::string& server_url, - const std::string& token, - util::Optional old_identity) -{ - std::shared_ptr user; - { - std::lock_guard lock(m_user_mutex); - // Look up the user based off the server URL. - auto it = m_admin_token_users.find(server_url); - if (it != m_admin_token_users.end()) - return it->second; - - // No existing user. - user = std::make_shared(token, - c_admin_identity, - server_url, - c_admin_identity + server_url, - SyncUser::TokenType::Admin); - m_admin_token_users.insert({ server_url, user }); - } - if (old_identity) { - // Try renaming the user's directory to use our new naming standard, if applicable. - std::lock_guard fm_lock(m_file_system_mutex); - if (m_file_manager) - m_file_manager->try_rename_user_directory(*old_identity, c_admin_identity + server_url); - } - return user; -} - -std::vector> SyncManager::all_logged_in_users() const -{ - std::lock_guard lock(m_user_mutex); - std::vector> users; - users.reserve(m_users.size() + m_admin_token_users.size()); - for (auto& it : m_users) { - auto user = it.second; - if (user->state() == SyncUser::State::Active) { - users.emplace_back(std::move(user)); - } - } - for (auto& it : m_admin_token_users) { - users.emplace_back(std::move(it.second)); - } - return users; -} - -std::shared_ptr SyncManager::get_current_user() const -{ - std::lock_guard lock(m_user_mutex); - - auto is_active_user = [](auto& el) { return el.second->state() == SyncUser::State::Active; }; - auto it = std::find_if(m_users.begin(), m_users.end(), is_active_user); - if (it == m_users.end()) - return nullptr; - - if (std::find_if(std::next(it), m_users.end(), is_active_user) != m_users.end()) - throw std::logic_error("Current user is not valid if more that one valid, logged-in user exists."); - - return it->second; -} - -std::shared_ptr SyncManager::get_existing_logged_in_user(const SyncUserIdentifier& identifier) const -{ - std::lock_guard lock(m_user_mutex); - auto it = m_users.find(identifier); - if (it == m_users.end()) - return nullptr; - - auto user = it->second; - return user->state() == SyncUser::State::Active ? user : nullptr; -} - -std::string SyncManager::path_for_realm(const SyncUser& user, const std::string& raw_realm_url) const -{ - std::lock_guard lock(m_file_system_mutex); - REALM_ASSERT(m_file_manager); - return m_file_manager->path(user.local_identity(), raw_realm_url); -} - -std::string SyncManager::recovery_directory_path(util::Optional const& custom_dir_name) const -{ - std::lock_guard lock(m_file_system_mutex); - REALM_ASSERT(m_file_manager); - return m_file_manager->recovery_directory_path(custom_dir_name); -} - -std::shared_ptr SyncManager::get_existing_active_session(const std::string& path) const -{ - std::lock_guard lock(m_session_mutex); - if (auto session = get_existing_session_locked(path)) { - if (auto external_reference = session->existing_external_reference()) - return external_reference; - } - return nullptr; -} - -std::shared_ptr SyncManager::get_existing_session_locked(const std::string& path) const -{ - REALM_ASSERT(!m_session_mutex.try_lock()); - auto it = m_sessions.find(path); - return it == m_sessions.end() ? nullptr : it->second; -} - -std::shared_ptr SyncManager::get_existing_session(const std::string& path) const -{ - std::lock_guard lock(m_session_mutex); - if (auto session = get_existing_session_locked(path)) - return session->external_reference(); - - return nullptr; -} - -std::shared_ptr SyncManager::get_session(const std::string& path, const SyncConfig& sync_config, bool force_client_resync) -{ - auto& client = get_sync_client(); // Throws - - std::lock_guard lock(m_session_mutex); - if (auto session = get_existing_session_locked(path)) { - sync_config.user->register_session(session); - return session->external_reference(); - } - - auto shared_session = SyncSession::create(client, path, sync_config, force_client_resync); - m_sessions[path] = shared_session; - - // Create the external reference immediately to ensure that the session will become - // inactive if an exception is thrown in the following code. - auto external_reference = shared_session->external_reference(); - - sync_config.user->register_session(std::move(shared_session)); - - return external_reference; -} - - -bool SyncManager::has_existing_sessions() -{ - std::lock_guard lock(m_session_mutex); - return do_has_existing_sessions(); -} - -bool SyncManager::do_has_existing_sessions(){ - return std::any_of(m_sessions.begin(), m_sessions.end(), [](auto& element){ - return element.second->existing_external_reference(); - }); -} - -void SyncManager::unregister_session(const std::string& path) -{ - std::lock_guard lock(m_session_mutex); - auto it = m_sessions.find(path); - REALM_ASSERT(it != m_sessions.end()); - - // If the session has an active external reference, leave it be. This will happen if the session - // moves to an inactive state while still externally reference, for instance, as a result of - // the session's user being logged out. - if (it->second->existing_external_reference()) - return; - - m_sessions.erase(path); -} - -void SyncManager::enable_session_multiplexing() -{ - std::lock_guard lock(m_mutex); - if (m_config.multiplex_sessions) - return; // Already enabled, we can ignore - - if (m_sync_client) - throw std::logic_error("Cannot enable session multiplexing after creating the sync client"); - - m_config.multiplex_sessions = true; -} - -SyncClient& SyncManager::get_sync_client() const -{ - std::lock_guard lock(m_mutex); - if (!m_sync_client) - m_sync_client = create_sync_client(); // Throws - return *m_sync_client; -} - -std::unique_ptr SyncManager::create_sync_client() const -{ - REALM_ASSERT(!m_mutex.try_lock()); - return std::make_unique(make_logger(), m_config); -} - -std::string SyncManager::client_uuid() const -{ - REALM_ASSERT(m_client_uuid); - return *m_client_uuid; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp deleted file mode 100644 index 4143bb9..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_permission.cpp +++ /dev/null @@ -1,370 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/sync_permission.hpp" - -#include "impl/notification_wrapper.hpp" -#include "impl/object_accessor_impl.hpp" -#include "object_schema.hpp" -#include "property.hpp" - -#include "sync/sync_config.hpp" -#include "sync/sync_manager.hpp" -#include "sync/sync_session.hpp" -#include "sync/sync_user.hpp" -#include "util/event_loop_signal.hpp" -#include "util/uuid.hpp" - -#include - -using namespace realm; -using namespace std::chrono; - -// MARK: - Utility - -namespace { - -// Make a handler that extracts either an exception pointer, or the string value -// of the property with the specified name. -Permissions::AsyncOperationHandler make_handler_extracting_property(std::string property, - Permissions::PermissionOfferCallback callback) -{ - return [property=std::move(property), - callback=std::move(callback)](Object* object, std::exception_ptr exception) { - if (exception) { - callback(none, exception); - } else { - CppContext context; - auto token = any_cast(object->get_property_value(context, property)); - callback(util::make_optional(std::move(token)), nullptr); - } - }; -} - -AccessLevel extract_access_level(Object& permission, CppContext& context) -{ - auto may_manage = permission.get_property_value(context, "mayManage"); - if (may_manage.has_value() && any_cast(may_manage)) - return AccessLevel::Admin; - - auto may_write = permission.get_property_value(context, "mayWrite"); - if (may_write.has_value() && any_cast(may_write)) - return AccessLevel::Write; - - auto may_read = permission.get_property_value(context, "mayRead"); - if (may_read.has_value() && any_cast(may_read)) - return AccessLevel::Read; - - return AccessLevel::None; -} - -/// Turn a system time point value into the 64-bit integer representing ns since the Unix epoch. -int64_t ns_since_unix_epoch(const system_clock::time_point& point) -{ - tm unix_epoch{}; - unix_epoch.tm_year = 70; - time_t epoch_time = mktime(&unix_epoch); - auto epoch_point = system_clock::from_time_t(epoch_time); - return duration_cast(point - epoch_point).count(); -} - -} // anonymous namespace - -// MARK: - Permission - -Permission::Permission(Object& permission) -{ - CppContext context; - path = any_cast(permission.get_property_value(context, "path")); - access = extract_access_level(permission, context); - condition = Condition(any_cast(permission.get_property_value(context, "userId"))); - updated_at = any_cast(permission.get_property_value(context, "updatedAt")); -} - -Permission::Permission(std::string path, AccessLevel access, Condition condition, Timestamp updated_at) -: path(std::move(path)) -, access(access) -, condition(std::move(condition)) -, updated_at(std::move(updated_at)) -{ } - -std::string Permission::description_for_access_level(AccessLevel level) -{ - switch (level) { - case AccessLevel::None: return "none"; - case AccessLevel::Read: return "read"; - case AccessLevel::Write: return "write"; - case AccessLevel::Admin: return "admin"; - } - REALM_UNREACHABLE(); -} - -bool Permission::paths_are_equivalent(std::string path_1, std::string path_2, - const std::string& user_id_1, const std::string& user_id_2) -{ - REALM_ASSERT_DEBUG(path_1.length() > 0); - REALM_ASSERT_DEBUG(path_2.length() > 0); - if (path_1 == path_2) { - // If both paths are identical and contain `/~/`, the user IDs must match. - return (path_1.find("/~/") == std::string::npos) || (user_id_1 == user_id_2); - } - // Make substitutions for the first `/~/` in the string. - size_t index = path_1.find("/~/"); - if (index != std::string::npos) - path_1.replace(index + 1, 1, user_id_1); - - index = path_2.find("/~/"); - if (index != std::string::npos) - path_2.replace(index + 1, 1, user_id_2); - - return path_1 == path_2; -} - -// MARK: - Permissions - -void Permissions::get_permissions(std::shared_ptr user, - PermissionResultsCallback callback, - const ConfigMaker& make_config) -{ - auto realm = Permissions::permission_realm(user, make_config); - auto table = ObjectStore::table_for_object_type(realm->read_group(), "Permission"); - auto results = std::make_shared<_impl::NotificationWrapper>(std::move(realm), *table); - - // `get_permissions` works by temporarily adding an async notifier to the permission Realm. - // This notifier will run the `async` callback until the Realm contains permissions or - // an error happens. When either of these two things happen, the notifier will be - // unregistered by nulling out the `results_wrapper` container. - auto async = [results, callback=std::move(callback)](CollectionChangeSet, std::exception_ptr ex) mutable { - if (ex) { - callback(Results(), ex); - results.reset(); - return; - } - if (results->size() > 0) { - // We monitor the raw results. The presence of a `__management` Realm indicates - // that the permissions have been downloaded (hence, we wait until size > 0). - TableRef table = ObjectStore::table_for_object_type(results->get_realm()->read_group(), "Permission"); - size_t col_idx = table->get_descriptor()->get_column_index("path"); - auto query = !(table->column(col_idx).ends_with("/__permission") - || table->column(col_idx).ends_with("/__perm") - || table->column(col_idx).ends_with("/__management")); - // Call the callback with our new permissions object. This object will exclude the - // private Realms. - callback(results->filter(std::move(query)), nullptr); - results.reset(); - } - }; - results->add_notification_callback(std::move(async)); -} - -void Permissions::set_permission(std::shared_ptr user, - Permission permission, - PermissionChangeCallback callback, - const ConfigMaker& make_config) -{ - auto props = AnyDict{ - {"userId", permission.condition.user_id}, - {"realmUrl", user->server_url() + permission.path}, - {"mayRead", permission.access != AccessLevel::None}, - {"mayWrite", permission.access == AccessLevel::Write || permission.access == AccessLevel::Admin}, - {"mayManage", permission.access == AccessLevel::Admin}, - }; - if (permission.condition.type == Permission::Condition::Type::KeyValue) { - props.insert({"metadataKey", permission.condition.key_value.first}); - props.insert({"metadataValue", permission.condition.key_value.second}); - } - auto cb = [callback=std::move(callback)](Object*, std::exception_ptr exception) { - callback(exception); - }; - perform_async_operation("PermissionChange", std::move(user), std::move(cb), std::move(props), make_config); -} - -void Permissions::delete_permission(std::shared_ptr user, - Permission permission, - PermissionChangeCallback callback, - const ConfigMaker& make_config) -{ - permission.access = AccessLevel::None; - set_permission(std::move(user), std::move(permission), std::move(callback), make_config); -} - -void Permissions::make_offer(std::shared_ptr user, - PermissionOffer offer, - PermissionOfferCallback callback, - const ConfigMaker& make_config) -{ - auto props = AnyDict{ - {"expiresAt", std::move(offer.expiration)}, - {"userId", user->identity()}, - {"realmUrl", user->server_url() + offer.path}, - {"mayRead", offer.access != AccessLevel::None}, - {"mayWrite", offer.access == AccessLevel::Write || offer.access == AccessLevel::Admin}, - {"mayManage", offer.access == AccessLevel::Admin}, - }; - perform_async_operation("PermissionOffer", - std::move(user), - make_handler_extracting_property("token", std::move(callback)), - std::move(props), - make_config); -} - -void Permissions::accept_offer(std::shared_ptr user, - const std::string& token, - PermissionOfferCallback callback, - const ConfigMaker& make_config) -{ - perform_async_operation("PermissionOfferResponse", - std::move(user), - make_handler_extracting_property("realmUrl", std::move(callback)), - AnyDict{ {"token", token} }, - make_config); -} - -void Permissions::perform_async_operation(const std::string& object_type, - std::shared_ptr user, - AsyncOperationHandler handler, - AnyDict additional_props, - const ConfigMaker& make_config) -{; - auto realm = Permissions::management_realm(std::move(user), make_config); - CppContext context; - - // Get the current time. - int64_t ns_since_epoch = ns_since_unix_epoch(system_clock::now()); - int64_t s_arg = ns_since_epoch / (int64_t)Timestamp::nanoseconds_per_second; - int32_t ns_arg = ns_since_epoch % Timestamp::nanoseconds_per_second; - - auto props = AnyDict{ - {"id", util::uuid_string()}, - {"createdAt", Timestamp(s_arg, ns_arg)}, - {"updatedAt", Timestamp(s_arg, ns_arg)}, - }; - props.insert(additional_props.begin(), additional_props.end()); - - // Write the permission object. - realm->begin_transaction(); - auto raw = Object::create(context, realm, *realm->schema().find(object_type), std::move(props)); - auto object = std::make_shared<_impl::NotificationWrapper>(std::move(raw)); - realm->commit_transaction(); - - // Observe the permission object until the permission change has been processed or failed. - // The notifier is automatically unregistered upon the completion of the permission - // change, one way or another. - auto block = [object, handler=std::move(handler)](CollectionChangeSet, std::exception_ptr ex) mutable { - if (ex) { - handler(nullptr, ex); - object.reset(); - return; - } - - CppContext context; - auto status_code = object->get_property_value(context, "statusCode"); - if (!status_code.has_value()) { - // Continue waiting for the sync server to complete the operation. - return; - } - - // Determine whether an error happened or not. - if (auto code = any_cast(status_code)) { - // The permission change failed because an error was returned from the server. - auto status = object->get_property_value(context, "statusMessage"); - std::string error_str = (status.has_value() - ? any_cast(status) - : util::format("Error code: %1", code)); - handler(nullptr, std::make_exception_ptr(PermissionActionException(error_str, code))); - } - else { - handler(object.get(), nullptr); - } - object.reset(); - }; - object->add_notification_callback(std::move(block)); -} - -SharedRealm Permissions::management_realm(std::shared_ptr user, const ConfigMaker& make_config) -{ - // FIXME: maybe we should cache the management Realm on the user, so we don't need to open it every time. - const auto realm_url = util::format("realm%1/~/__management", user->server_url().substr(4)); - Realm::Config config = make_config(user, std::move(realm_url)); - config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately; - config.schema = Schema{ - {"PermissionChange", { - Property{"id", PropertyType::String, Property::IsPrimary{true}}, - Property{"createdAt", PropertyType::Date}, - Property{"updatedAt", PropertyType::Date}, - Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, - Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, - Property{"userId", PropertyType::String}, - Property{"metadataKey", PropertyType::String|PropertyType::Nullable}, - Property{"metadataValue", PropertyType::String|PropertyType::Nullable}, - Property{"metadataNameSpace", PropertyType::String|PropertyType::Nullable}, - Property{"realmUrl", PropertyType::String}, - Property{"mayRead", PropertyType::Bool|PropertyType::Nullable}, - Property{"mayWrite", PropertyType::Bool|PropertyType::Nullable}, - Property{"mayManage", PropertyType::Bool|PropertyType::Nullable}, - }}, - {"PermissionOffer", { - Property{"id", PropertyType::String, Property::IsPrimary{true}}, - Property{"createdAt", PropertyType::Date}, - Property{"updatedAt", PropertyType::Date}, - Property{"expiresAt", PropertyType::Date|PropertyType::Nullable}, - Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, - Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, - Property{"token", PropertyType::String|PropertyType::Nullable}, - Property{"realmUrl", PropertyType::String}, - Property{"mayRead", PropertyType::Bool}, - Property{"mayWrite", PropertyType::Bool}, - Property{"mayManage", PropertyType::Bool}, - }}, - {"PermissionOfferResponse", { - Property{"id", PropertyType::String, Property::IsPrimary{true}}, - Property{"createdAt", PropertyType::Date}, - Property{"updatedAt", PropertyType::Date}, - Property{"statusCode", PropertyType::Int|PropertyType::Nullable}, - Property{"statusMessage", PropertyType::String|PropertyType::Nullable}, - Property{"token", PropertyType::String}, - Property{"realmUrl", PropertyType::String|PropertyType::Nullable}, - }}, - }; - config.schema_version = 0; - auto shared_realm = Realm::get_shared_realm(std::move(config)); - user->register_management_session(shared_realm->config().path); - return shared_realm; -} - -SharedRealm Permissions::permission_realm(std::shared_ptr user, const ConfigMaker& make_config) -{ - // FIXME: maybe we should cache the permission Realm on the user, so we don't need to open it every time. - const auto realm_url = util::format("realm%1/~/__permission", user->server_url().substr(4)); - Realm::Config config = make_config(user, std::move(realm_url)); - config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately; - config.schema = Schema{ - {"Permission", { - {"updatedAt", PropertyType::Date}, - {"userId", PropertyType::String}, - {"path", PropertyType::String}, - {"mayRead", PropertyType::Bool}, - {"mayWrite", PropertyType::Bool}, - {"mayManage", PropertyType::Bool}, - }} - }; - config.schema_version = 0; - auto shared_realm = Realm::get_shared_realm(std::move(config)); - user->register_permission_session(shared_realm->config().path); - return shared_realm; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp deleted file mode 100644 index f75891c..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_session.cpp +++ /dev/null @@ -1,1150 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/sync_session.hpp" - -#include "sync/impl/sync_client.hpp" -#include "sync/impl/sync_file.hpp" -#include "sync/impl/sync_metadata.hpp" -#include "sync/sync_manager.hpp" -#include "sync/sync_user.hpp" - -#include -#include - -using namespace realm; -using namespace realm::_impl; -using namespace realm::_impl::sync_session_states; - -using SessionWaiterPointer = void(sync::Session::*)(std::function); - -constexpr const char SyncError::c_original_file_path_key[]; -constexpr const char SyncError::c_recovery_file_path_key[]; - -/// A state which a `SyncSession` can currently be within. State classes handle various actions -/// and state transitions. -/// -/// STATES: -/// -/// WAITING_FOR_ACCESS_TOKEN: upon entering this state, the binding is informed -/// that the session wants an access token. The session is now waiting for the -/// binding to provide the token. -/// From: INACTIVE -/// To: -/// * ACTIVE: when the binding successfully refreshes the token -/// * INACTIVE: if asked to log out, or if asked to close and the stop policy -/// is Immediate. -/// -/// ACTIVE: the session is connected to the Realm Object Server and is actively -/// transferring data. -/// From: WAITING_FOR_ACCESS_TOKEN, DYING -/// To: -/// * WAITING_FOR_ACCESS_TOKEN: if the session is informed (through the error -/// handler) that the token expired -/// * INACTIVE: if asked to log out, or if asked to close and the stop policy -/// is Immediate. -/// * DYING: if asked to close and the stop policy is AfterChangesUploaded -/// -/// DYING: the session is performing clean-up work in preparation to be destroyed. -/// From: ACTIVE -/// To: -/// * INACTIVE: when the clean-up work completes, if the session wasn't -/// revived, or if explicitly asked to log out before the -/// clean-up work begins -/// * ACTIVE: if the session is revived -/// -/// INACTIVE: the user owning this session has logged out, the `sync::Session` -/// owned by this session is destroyed, and the session is quiescent. -/// Note that a session briefly enters this state before being destroyed, but -/// it can also enter this state and stay there if the user has been logged out. -/// From: initial, WAITING_FOR_ACCESS_TOKEN, ACTIVE, DYING -/// To: -/// * WAITING_FOR_ACCESS_TOKEN: if the session is revived -/// -struct SyncSession::State { - virtual ~State() { } - - // Move the given session into this state. All state transitions MUST be carried out through this method. - virtual void enter_state(std::unique_lock&, SyncSession&) const { } - - virtual void refresh_access_token(std::unique_lock&, - SyncSession&, std::string, - const util::Optional&) const { } - - // Returns true iff the lock is still locked when the method returns. - virtual bool access_token_expired(std::unique_lock&, SyncSession&) const { return true; } - - virtual void nonsync_transact_notify(std::unique_lock&, SyncSession&, sync::version_type) const { } - - // Perform any work needed to reactivate a session that is not already active. - // Returns true iff the session should ask the binding to get a token for `bind()`. - virtual bool revive_if_needed(std::unique_lock&, SyncSession&) const { return false; } - - // Perform any work needed to respond to the application regaining network connectivity. - virtual void handle_reconnect(std::unique_lock&, SyncSession&) const { }; - - // The user that owns this session has been logged out, and the session should take appropriate action. - virtual void log_out(std::unique_lock&, SyncSession&) const { } - - // The session should be closed and moved to `inactive`, in accordance with its stop policy and other state. - virtual void close(std::unique_lock&, SyncSession&) const { } - - // Returns true iff the error has been fully handled and the error handler should immediately return. - virtual bool handle_error(std::unique_lock&, SyncSession&, const SyncError&) const { return false; } - - // Register a handler to wait for sync session uploads, downloads, or synchronization. - // PRECONDITION: the session state lock must be held at the time this method is called, until after it returns. - virtual void wait_for_completion(SyncSession&, _impl::SyncProgressNotifier::NotifierType) const { } - - virtual void override_server(std::unique_lock&, SyncSession&, std::string, int) const { } - - static const State& waiting_for_access_token; - static const State& active; - static const State& dying; - static const State& inactive; -}; - -struct sync_session_states::WaitingForAccessToken : public SyncSession::State { - void enter_state(std::unique_lock&, SyncSession& session) const override - { - session.m_deferred_close = false; - } - - void refresh_access_token(std::unique_lock& lock, SyncSession& session, - std::string access_token, - const util::Optional& server_url) const override - { - session.create_sync_session(); - - // Since the sync session was previously unbound, it's safe to do this from the - // calling thread. - if (!session.m_server_url) { - session.m_server_url = server_url; - } - if (session.m_session_has_been_bound) { - session.m_session->refresh(std::move(access_token)); - session.m_session->cancel_reconnect_delay(); - } else { - session.m_session->bind(*session.m_server_url, std::move(access_token)); - session.m_session_has_been_bound = true; - } - - if (session.m_server_override) - session.m_session->override_server(session.m_server_override->address, session.m_server_override->port); - - // Handle any deferred commit notification. - if (session.m_deferred_commit_notification) { - session.m_session->nonsync_transact_notify(*session.m_deferred_commit_notification); - session.m_deferred_commit_notification = util::none; - } - - session.advance_state(lock, active); - if (session.m_deferred_close) { - session.m_state->close(lock, session); - } - } - - void log_out(std::unique_lock& lock, SyncSession& session) const override - { - session.advance_state(lock, inactive); - } - - bool revive_if_needed(std::unique_lock&, SyncSession& session) const override - { - session.m_deferred_close = false; - return false; - } - - void handle_reconnect(std::unique_lock& lock, SyncSession& session) const override - { - // Ask the binding to retry getting the token for this session. - std::shared_ptr session_ptr = session.shared_from_this(); - lock.unlock(); - session.m_config.bind_session_handler(session_ptr->m_realm_path, session_ptr->m_config, session_ptr); - } - - void nonsync_transact_notify(std::unique_lock&, - SyncSession& session, - sync::version_type version) const override - { - // Notify at first available opportunity. - session.m_deferred_commit_notification = version; - } - - void close(std::unique_lock& lock, SyncSession& session) const override - { - switch (session.m_config.stop_policy) { - case SyncSessionStopPolicy::Immediately: - // Immediately kill the session. - session.advance_state(lock, inactive); - break; - case SyncSessionStopPolicy::LiveIndefinitely: - case SyncSessionStopPolicy::AfterChangesUploaded: - // Defer handling closing the session until after the login response succeeds. - session.m_deferred_close = true; - break; - } - } - - void override_server(std::unique_lock&, SyncSession& session, - std::string address, int port) const override - { - session.m_server_override = SyncSession::ServerOverride{address, port}; - } -}; - -struct sync_session_states::Active : public SyncSession::State { - void enter_state(std::unique_lock&, SyncSession& session) const override - { - // Register all the pending wait-for-completion blocks. This can - // potentially add a redundant callback if we're coming from the Dying - // state, but that's okay (we won't call the user callbacks twice). - if (!session.m_upload_completion_callbacks.empty()) - session.add_completion_callback(_impl::SyncProgressNotifier::NotifierType::upload); - if (!session.m_download_completion_callbacks.empty()) - session.add_completion_callback(_impl::SyncProgressNotifier::NotifierType::download); - } - - void refresh_access_token(std::unique_lock&, SyncSession& session, - std::string access_token, - const util::Optional&) const override - { - session.m_session->refresh(std::move(access_token)); - // Cancel the session's reconnection delay. This is important if the - // token is being refreshed as a response to a 202 (token expired) - // error, or similar non-fatal sync errors. - session.m_session->cancel_reconnect_delay(); - } - - bool access_token_expired(std::unique_lock& lock, SyncSession& session) const override - { - session.advance_state(lock, waiting_for_access_token); - std::shared_ptr session_ptr = session.shared_from_this(); - lock.unlock(); - session.m_config.bind_session_handler(session_ptr->m_realm_path, session_ptr->m_config, session_ptr); - return false; - } - - void log_out(std::unique_lock& lock, SyncSession& session) const override - { - session.advance_state(lock, inactive); - } - - void nonsync_transact_notify(std::unique_lock&, SyncSession& session, - sync::version_type version) const override - { - // Fully ready sync session, notify immediately. - session.m_session->nonsync_transact_notify(version); - } - - void close(std::unique_lock& lock, SyncSession& session) const override - { - switch (session.m_config.stop_policy) { - case SyncSessionStopPolicy::Immediately: - session.advance_state(lock, inactive); - break; - case SyncSessionStopPolicy::LiveIndefinitely: - // Don't do anything; session lives forever. - break; - case SyncSessionStopPolicy::AfterChangesUploaded: - // Wait for all pending changes to upload. - session.advance_state(lock, dying); - break; - } - } - - void wait_for_completion(SyncSession& session, _impl::SyncProgressNotifier::NotifierType direction) const override - { - REALM_ASSERT(session.m_session); - session.add_completion_callback(direction); - } - - void handle_reconnect(std::unique_lock&, SyncSession& session) const override - { - session.m_session->cancel_reconnect_delay(); - } - - void override_server(std::unique_lock&, SyncSession& session, - std::string address, int port) const override - { - session.m_server_override = SyncSession::ServerOverride{address, port}; - session.m_session->override_server(address, port); - } -}; - -struct sync_session_states::Dying : public SyncSession::State { - void enter_state(std::unique_lock& lock, SyncSession& session) const override - { - // If we have no session, we cannot possibly upload anything. - if (!session.m_session) { - session.advance_state(lock, inactive); - return; - } - - size_t current_death_count = ++session.m_death_count; - std::weak_ptr weak_session = session.shared_from_this(); - session.m_session->async_wait_for_upload_completion([weak_session, current_death_count](std::error_code) { - if (auto session = weak_session.lock()) { - std::unique_lock lock(session->m_state_mutex); - if (session->m_state == &State::dying && session->m_death_count == current_death_count) { - session->advance_state(lock, inactive); - } - } - }); - } - - bool handle_error(std::unique_lock& lock, SyncSession& session, const SyncError& error) const override - { - if (error.is_fatal) { - session.advance_state(lock, inactive); - } - // If the error isn't fatal, don't change state, but don't - // allow it to be reported either. - // FIXME: What if the token expires while a session is dying? - // Should we allow the token to be refreshed so that changes - // can finish being uploaded? - return true; - } - - bool revive_if_needed(std::unique_lock& lock, SyncSession& session) const override - { - // Revive. - session.advance_state(lock, active); - return false; - } - - void log_out(std::unique_lock& lock, SyncSession& session) const override - { - session.advance_state(lock, inactive); - } - - void wait_for_completion(SyncSession& session, _impl::SyncProgressNotifier::NotifierType direction) const override - { - REALM_ASSERT(session.m_session); - session.add_completion_callback(direction); - } - - void override_server(std::unique_lock&, SyncSession& session, - std::string address, int port) const override - { - session.m_server_override = SyncSession::ServerOverride{address, port}; - session.m_session->override_server(address, port); - } -}; - -struct sync_session_states::Inactive : public SyncSession::State { - void enter_state(std::unique_lock& lock, SyncSession& session) const override - { - // Manually set the disconnected state. Sync would also do this, but - // since the underlying SyncSession object already have been destroyed, - // we are not able to get the callback. - auto old_state = session.m_connection_state; - auto new_state = session.m_connection_state = SyncSession::ConnectionState::Disconnected; - - auto download_waits = std::move(session.m_download_completion_callbacks); - auto upload_waits = std::move(session.m_upload_completion_callbacks); - session.m_download_completion_callbacks.clear(); - session.m_upload_completion_callbacks.clear(); - - session.m_session = nullptr; - session.unregister(lock); // releases lock - - // Send notifications after releasing the lock to prevent deadlocks in the callback. - if (old_state != new_state) { - session.m_connection_change_notifier.invoke_callbacks(old_state, session.connection_state()); - } - - // Inform any queued-up completion handlers that they were cancelled. - for (auto& callback : download_waits) - callback(make_error_code(util::error::operation_aborted)); - for (auto& callback : upload_waits) - callback(make_error_code(util::error::operation_aborted)); - } - - bool revive_if_needed(std::unique_lock& lock, SyncSession& session) const override - { - session.advance_state(lock, waiting_for_access_token); - return true; - } - - void override_server(std::unique_lock&, SyncSession& session, - std::string address, int port) const override - { - session.m_server_override = SyncSession::ServerOverride{address, port}; - } - - void close(std::unique_lock& lock, SyncSession& session) const override - { - session.unregister(lock); // releases lock - } -}; - - -const SyncSession::State& SyncSession::State::waiting_for_access_token = WaitingForAccessToken(); -const SyncSession::State& SyncSession::State::active = Active(); -const SyncSession::State& SyncSession::State::dying = Dying(); -const SyncSession::State& SyncSession::State::inactive = Inactive(); - -SyncSession::SyncSession(SyncClient& client, std::string realm_path, SyncConfig config, bool force_client_resync) -: m_state(&State::inactive) -, m_config(std::move(config)) -, m_force_client_resync(force_client_resync) -, m_realm_path(std::move(realm_path)) -, m_client(client) -{ - // Sync history validation ensures that the history within the Realm file is in a format that can be used - // by the version of realm-sync that we're using. Validation is enabled by default when the binding manually - // opens a sync session (via `SyncManager::get_session`), but is disabled when the sync session is opened - // as a side effect of opening a `Realm`. In that case, the sync history has already been validated by the - // act of opening the `Realm` so it's not necessary to repeat it here. - if (m_config.validate_sync_history) { - Realm::Config realm_config; - realm_config.path = m_realm_path; - realm_config.schema_mode = SchemaMode::Additive; - realm_config.force_sync_history = true; - realm_config.cache = false; - - if (m_config.realm_encryption_key) { - realm_config.encryption_key.resize(64); - std::copy(m_config.realm_encryption_key->begin(), m_config.realm_encryption_key->end(), - realm_config.encryption_key.begin()); - } - - std::unique_ptr history; - std::unique_ptr shared_group; - std::unique_ptr read_only_group; - Realm::open_with_config(realm_config, history, shared_group, read_only_group, nullptr); - } -} - -std::string SyncSession::get_recovery_file_path() -{ - return util::reserve_unique_file_name(SyncManager::shared().recovery_directory_path(m_config.recovery_directory), - util::create_timestamped_template("recovered_realm")); -} - -void SyncSession::update_error_and_mark_file_for_deletion(SyncError& error, ShouldBackup should_backup) -{ - // Add a SyncFileActionMetadata marking the Realm as needing to be deleted. - std::string recovery_path; - auto original_path = path(); - error.user_info[SyncError::c_original_file_path_key] = original_path; - if (should_backup == ShouldBackup::yes) { - recovery_path = get_recovery_file_path(); - error.user_info[SyncError::c_recovery_file_path_key] = recovery_path; - } - using Action = SyncFileActionMetadata::Action; - auto action = should_backup == ShouldBackup::yes ? Action::BackUpThenDeleteRealm : Action::DeleteRealm; - SyncManager::shared().perform_metadata_update([this, action, - original_path=std::move(original_path), - recovery_path=std::move(recovery_path)](const auto& manager) { - auto realm_url = m_config.realm_url(); - manager.make_file_action_metadata(original_path, realm_url, m_config.user->identity(), action, recovery_path); - }); -} - -// This method should only be called from within the error handler callback registered upon the underlying `m_session`. -void SyncSession::handle_error(SyncError error) -{ - enum class NextStateAfterError { none, inactive, error }; - auto next_state = error.is_fatal ? NextStateAfterError::error : NextStateAfterError::none; - auto error_code = error.error_code; - - { - // See if the current state wishes to take responsibility for handling the error. - std::unique_lock lock(m_state_mutex); - if (m_state->handle_error(lock, *this, error)) { - return; - } - } - - if (error.is_client_reset_requested()) { - switch (m_config.client_resync_mode) { - case ClientResyncMode::Manual: - break; - case ClientResyncMode::DiscardLocal: - case ClientResyncMode::Recover: { - // Performing a client resync requires tearing down our current - // sync session and creating a new one with a forced client - // reset. This will result in session completion handlers firing - // when the old session is torn down, which we don't want as this - // is supposed to be transparent to the user. - // - // To avoid this, we need to do two things: move the completion - // handlers aside temporarily so that moving to the inactive - // state doesn't clear them, and track which sync::Session each - // completion notification came from so that we can ignore - // notifications from the old session. - { - std::unique_lock lock(m_state_mutex); - m_force_client_resync = true; - - ++m_client_resync_counter; - auto download_handlers = std::move(m_download_completion_callbacks); - auto upload_handlers = std::move(m_upload_completion_callbacks); - - advance_state(lock, State::inactive); - - m_download_completion_callbacks = std::move(download_handlers); - m_upload_completion_callbacks = std::move(upload_handlers); - } - revive_if_needed(); - return; - } - } - } - - if (error_code.category() == realm::sync::protocol_error_category()) { - using ProtocolError = realm::sync::ProtocolError; - switch (static_cast(error_code.value())) { - // Connection level errors - case ProtocolError::connection_closed: - case ProtocolError::other_error: - // Not real errors, don't need to be reported to the binding. - return; - case ProtocolError::unknown_message: - case ProtocolError::bad_syntax: - case ProtocolError::limits_exceeded: - case ProtocolError::wrong_protocol_version: - case ProtocolError::bad_session_ident: - case ProtocolError::reuse_of_session_ident: - case ProtocolError::bound_in_other_session: - case ProtocolError::bad_message_order: - case ProtocolError::bad_client_version: - case ProtocolError::illegal_realm_path: - case ProtocolError::no_such_realm: - case ProtocolError::bad_changeset: - case ProtocolError::bad_changeset_header_syntax: - case ProtocolError::bad_changeset_size: - case ProtocolError::bad_changesets: - case ProtocolError::bad_decompression: - case ProtocolError::partial_sync_disabled: - case ProtocolError::unsupported_session_feature: - case ProtocolError::transact_before_upload: - break; - // Session errors - case ProtocolError::session_closed: - case ProtocolError::other_session_error: - case ProtocolError::disabled_session: - // The binding doesn't need to be aware of these because they are strictly informational, and do not - // represent actual errors. - return; - case ProtocolError::token_expired: { - std::unique_lock lock(m_state_mutex); - // This isn't an error from the binding's point of view. If we're connected we'll - // simply ask the binding to log in again. - m_state->access_token_expired(lock, *this); - return; - } - case ProtocolError::bad_authentication: { - std::shared_ptr user_to_invalidate; - next_state = NextStateAfterError::none; - { - std::unique_lock lock(m_state_mutex); - user_to_invalidate = user(); - cancel_pending_waits(lock, error.error_code); - } - if (user_to_invalidate) - user_to_invalidate->invalidate(); - break; - } - case ProtocolError::permission_denied: { - next_state = NextStateAfterError::inactive; - update_error_and_mark_file_for_deletion(error, ShouldBackup::no); - break; - } - case ProtocolError::bad_client_file: - case ProtocolError::bad_client_file_ident: - case ProtocolError::bad_origin_file_ident: - case ProtocolError::bad_server_file_ident: - case ProtocolError::bad_server_version: - case ProtocolError::client_file_blacklisted: - case ProtocolError::diverging_histories: - case ProtocolError::server_file_deleted: - case ProtocolError::user_blacklisted: - case ProtocolError::client_file_expired: - next_state = NextStateAfterError::inactive; - update_error_and_mark_file_for_deletion(error, ShouldBackup::yes); - break; - } - } else if (error_code.category() == realm::sync::client_error_category()) { - using ClientError = realm::sync::Client::Error; - switch (static_cast(error_code.value())) { - case ClientError::connection_closed: - case ClientError::pong_timeout: - // Not real errors, don't need to be reported to the binding. - return; - case ClientError::bad_changeset: - case ClientError::bad_changeset_header_syntax: - case ClientError::bad_changeset_size: - case ClientError::bad_client_file_ident: - case ClientError::bad_client_file_ident_salt: - case ClientError::bad_client_version: - case ClientError::bad_compression: - case ClientError::bad_error_code: - case ClientError::bad_file_ident: - case ClientError::bad_message_order: - case ClientError::bad_origin_file_ident: - case ClientError::bad_progress: - case ClientError::bad_protocol_from_server: - case ClientError::bad_request_ident: - case ClientError::bad_server_version: - case ClientError::bad_session_ident: - case ClientError::bad_state_message: - case ClientError::bad_syntax: - case ClientError::bad_timestamp: - case ClientError::client_too_new_for_server: - case ClientError::client_too_old_for_server: - case ClientError::connect_timeout: - case ClientError::limits_exceeded: - case ClientError::protocol_mismatch: - case ClientError::ssl_server_cert_rejected: - case ClientError::unknown_message: - case ClientError::missing_protocol_feature: - case ClientError::bad_serial_transact_status: - case ClientError::bad_object_id_substitutions: - case ClientError::http_tunnel_failed: - // Don't do anything special for these errors. - // Future functionality may require special-case handling for existing - // errors, or newly introduced error codes. - break; - } - } else { - // Unrecognized error code. - error.is_unrecognized_by_client = true; - } - switch (next_state) { - case NextStateAfterError::none: - if (m_config.cancel_waits_on_nonfatal_error) { - std::unique_lock lock(m_state_mutex); - cancel_pending_waits(lock, error.error_code); - } - break; - case NextStateAfterError::inactive: { - std::unique_lock lock(m_state_mutex); - advance_state(lock, State::inactive); - break; - } - case NextStateAfterError::error: { - std::unique_lock lock(m_state_mutex); - cancel_pending_waits(lock, error.error_code); - break; - } - } - if (m_config.error_handler) { - m_config.error_handler(shared_from_this(), std::move(error)); - } -} - -void SyncSession::cancel_pending_waits(std::unique_lock& lock, std::error_code error) -{ - auto download = std::move(m_download_completion_callbacks); - auto upload = std::move(m_upload_completion_callbacks); - lock.unlock(); - - // Inform any queued-up completion handlers that they were cancelled. - for (auto& callback : download) - callback(error); - for (auto& callback : upload) - callback(error); -} - -void SyncSession::handle_progress_update(uint64_t downloaded, uint64_t downloadable, - uint64_t uploaded, uint64_t uploadable, - uint64_t download_version, uint64_t snapshot_version) -{ - m_progress_notifier.update(downloaded, downloadable, uploaded, uploadable, download_version, snapshot_version); -} - -void SyncSession::create_sync_session() -{ - if (m_session) - return; - - sync::Session::Config session_config; - session_config.changeset_cooker = m_config.transformer; - session_config.encryption_key = m_config.realm_encryption_key; - session_config.verify_servers_ssl_certificate = m_config.client_validate_ssl; - session_config.ssl_trust_certificate_path = m_config.ssl_trust_certificate_path; - session_config.ssl_verify_callback = m_config.ssl_verify_callback; - session_config.proxy_config = m_config.proxy_config; - session_config.multiplex_ident = m_multiplex_identity; - - if (m_config.authorization_header_name) { - session_config.authorization_header_name = *m_config.authorization_header_name; - } - session_config.custom_http_headers = m_config.custom_http_headers; - - if (m_config.url_prefix) { - session_config.url_prefix = *m_config.url_prefix; - } - - if (m_force_client_resync) { - std::string metadata_dir = m_realm_path + ".resync"; - util::try_make_dir(metadata_dir); - - sync::Session::Config::ClientReset config; - config.metadata_dir = metadata_dir; - if (m_config.client_resync_mode != ClientResyncMode::Recover) - config.recover_local_changes = false; - session_config.client_reset_config = config; - } - - m_session = m_client.make_session(m_realm_path, std::move(session_config)); - - // The next time we get a token, call `bind()` instead of `refresh()`. - m_session_has_been_bound = false; - - std::weak_ptr weak_self = shared_from_this(); - - // Configure the sync transaction callback. - auto wrapped_callback = [this, weak_self](VersionID old_version, VersionID new_version) { - if (auto self = weak_self.lock()) { - if (m_sync_transact_callback) { - m_sync_transact_callback(old_version, new_version); - } - } - }; - m_session->set_sync_transact_callback(std::move(wrapped_callback)); - - // Set up the wrapped progress handler callback - m_session->set_progress_handler([weak_self](uint_fast64_t downloaded, uint_fast64_t downloadable, - uint_fast64_t uploaded, uint_fast64_t uploadable, - uint_fast64_t progress_version, uint_fast64_t snapshot_version) { - if (auto self = weak_self.lock()) { - self->handle_progress_update(downloaded, downloadable, uploaded, - uploadable, progress_version, snapshot_version); - } - }); - - // Sets up the connection state listener. This callback is used for both reporting errors as well as changes to the - // connection state. - m_session->set_connection_state_change_listener([weak_self](sync::Session::ConnectionState state, - const sync::Session::ErrorInfo* error) { - // If the OS SyncSession object is destroyed, we ignore any events from the underlying Session as there is - // nothing useful we can do with them. - if (auto self = weak_self.lock()) { - std::unique_lock lock(self->m_state_mutex); - auto old_state = self->m_connection_state; - using cs = sync::Session::ConnectionState; - switch (state) { - case cs::disconnected: self->m_connection_state = ConnectionState::Disconnected; break; - case cs::connecting: self->m_connection_state = ConnectionState::Connecting; break; - case cs::connected: self->m_connection_state = ConnectionState::Connected; break; - default: REALM_UNREACHABLE(); - } - auto new_state = self->m_connection_state; - lock.unlock(); - self->m_connection_change_notifier.invoke_callbacks(old_state, new_state); - if (error) { - self->handle_error(SyncError{error->error_code, std::move(error->detailed_message), error->is_fatal}); - } - } - }); -} - -void SyncSession::set_sync_transact_callback(std::function callback) -{ - m_sync_transact_callback = std::move(callback); -} - -void SyncSession::advance_state(std::unique_lock& lock, const State& state) -{ - REALM_ASSERT(lock.owns_lock()); - REALM_ASSERT(&state != m_state); - m_state = &state; - m_state->enter_state(lock, *this); -} - -void SyncSession::nonsync_transact_notify(sync::version_type version) -{ - m_progress_notifier.set_local_version(version); - - std::unique_lock lock(m_state_mutex); - m_state->nonsync_transact_notify(lock, *this, version); -} - -void SyncSession::revive_if_needed() -{ - util::Optional&> handler; - { - std::unique_lock lock(m_state_mutex); - if (m_state->revive_if_needed(lock, *this)) - handler = m_config.bind_session_handler; - } - if (handler) - handler.value()(m_realm_path, m_config, shared_from_this()); -} - -void SyncSession::handle_reconnect() -{ - std::unique_lock lock(m_state_mutex); - m_state->handle_reconnect(lock, *this); -} - -void SyncSession::log_out() -{ - std::unique_lock lock(m_state_mutex); - m_state->log_out(lock, *this); -} - -void SyncSession::close() -{ - std::unique_lock lock(m_state_mutex); - m_state->close(lock, *this); -} - -void SyncSession::unregister(std::unique_lock& lock) -{ - REALM_ASSERT(lock.owns_lock()); - REALM_ASSERT(m_state == &State::inactive); // Must stop an active session before unregistering. - - lock.unlock(); - SyncManager::shared().unregister_session(m_realm_path); -} - -void SyncSession::add_completion_callback(_impl::SyncProgressNotifier::NotifierType direction) -{ - bool is_download = direction == _impl::SyncProgressNotifier::NotifierType::download; - - int resync_counter = m_client_resync_counter; - std::weak_ptr weak_self = shared_from_this(); - auto waiter = is_download ? &sync::Session::async_wait_for_download_completion - : &sync::Session::async_wait_for_upload_completion; - (m_session.get()->*waiter)([resync_counter, weak_self, is_download](std::error_code ec) { - auto self = weak_self.lock(); - if (!self) - return; - std::unique_lock lock(self->m_state_mutex); - if (resync_counter != self->m_client_resync_counter) { - // This callback was registered on a previous sync session and not - // the current one, so we want to simply discard completion - // notifications from it - return; - } - auto callbacks = std::move(is_download ? self->m_download_completion_callbacks - : self->m_upload_completion_callbacks); - lock.unlock(); - for (auto& callback : callbacks) - callback(ec); - }); -} - -void SyncSession::wait_for_upload_completion(std::function callback) -{ - std::unique_lock lock(m_state_mutex); - if (m_upload_completion_callbacks.empty()) - m_state->wait_for_completion(*this, _impl::SyncProgressNotifier::NotifierType::upload); - m_upload_completion_callbacks.push_back(std::move(callback)); -} - -void SyncSession::wait_for_download_completion(std::function callback) -{ - std::unique_lock lock(m_state_mutex); - if (m_download_completion_callbacks.empty()) - m_state->wait_for_completion(*this, _impl::SyncProgressNotifier::NotifierType::download); - m_download_completion_callbacks.push_back(std::move(callback)); -} - -uint64_t SyncSession::register_progress_notifier(std::function notifier, - NotifierType direction, bool is_streaming) -{ - return m_progress_notifier.register_callback(std::move(notifier), direction, is_streaming); -} - -void SyncSession::unregister_progress_notifier(uint64_t token) -{ - m_progress_notifier.unregister_callback(token); -} - -uint64_t SyncSession::register_connection_change_callback(std::function callback) -{ - return m_connection_change_notifier.add_callback(callback); -} - -void SyncSession::unregister_connection_change_callback(uint64_t token) -{ - m_connection_change_notifier.remove_callback(token); -} - -void SyncSession::refresh_access_token(std::string access_token, util::Optional server_url) -{ - std::unique_lock lock(m_state_mutex); - if (!m_server_url && !server_url) { - // The first time this method is called, the server URL must be provided. - return; - } - m_state->refresh_access_token(lock, *this, std::move(access_token), server_url); -} - -void SyncSession::override_server(std::string address, int port) -{ - std::unique_lock lock(m_state_mutex); - m_state->override_server(lock, *this, std::move(address), port); -} - -void SyncSession::set_multiplex_identifier(std::string multiplex_identity) -{ - m_multiplex_identity = std::move(multiplex_identity); -} - -void SyncSession::set_url_prefix(std::string url_prefix) -{ - m_config.url_prefix = std::move(url_prefix); -} - -SyncSession::PublicState SyncSession::get_public_state() const -{ - if (m_state == nullptr) { - return PublicState::Inactive; - } else if (m_state == &State::waiting_for_access_token) { - return PublicState::WaitingForAccessToken; - } else if (m_state == &State::active) { - return PublicState::Active; - } else if (m_state == &State::dying) { - return PublicState::Dying; - } else if (m_state == &State::inactive) { - return PublicState::Inactive; - } - REALM_UNREACHABLE(); -} - -SyncSession::PublicState SyncSession::state() const -{ - std::unique_lock lock(m_state_mutex); - return get_public_state(); -} - -SyncSession::ConnectionState SyncSession::connection_state() const -{ - std::unique_lock lock(m_state_mutex); - return m_connection_state; -} - -void SyncSession::update_configuration(SyncConfig new_config) -{ - while (true) { - std::unique_lock lock(m_state_mutex); - if (m_state != &State::inactive) { - // Changing the state releases the lock, which means that by the - // time we reacquire the lock the state may have changed again - // (either due to one of the callbacks being invoked or another - // thread coincidentally doing something). We just attempt to keep - // switching it to inactive until it stays there. - advance_state(lock, State::inactive); - continue; - } - - REALM_ASSERT(m_state == &State::inactive); - REALM_ASSERT(!m_session); - REALM_ASSERT(m_config.user == new_config.user); - REALM_ASSERT(m_config.reference_realm_url == new_config.reference_realm_url); - REALM_ASSERT(m_config.is_partial == new_config.is_partial); - m_config = std::move(new_config); - break; - } - revive_if_needed(); -} - -// Represents a reference to the SyncSession from outside of the sync subsystem. -// We attempt to keep the SyncSession in an active state as long as it has an external reference. -class SyncSession::ExternalReference { -public: - ExternalReference(std::shared_ptr session) : m_session(std::move(session)) - {} - - ~ExternalReference() - { - m_session->did_drop_external_reference(); - } - -private: - std::shared_ptr m_session; -}; - -std::shared_ptr SyncSession::external_reference() -{ - std::unique_lock lock(m_state_mutex); - - if (auto external_reference = m_external_reference.lock()) - return std::shared_ptr(external_reference, this); - - auto external_reference = std::make_shared(shared_from_this()); - m_external_reference = external_reference; - return std::shared_ptr(external_reference, this); -} - -std::shared_ptr SyncSession::existing_external_reference() -{ - std::unique_lock lock(m_state_mutex); - - if (auto external_reference = m_external_reference.lock()) - return std::shared_ptr(external_reference, this); - - return nullptr; -} - -void SyncSession::did_drop_external_reference() -{ - std::unique_lock lock(m_state_mutex); - - // If the session is being resurrected we should not close the session. - if (!m_external_reference.expired()) - return; - - m_state->close(lock, *this); -} - -uint64_t SyncProgressNotifier::register_callback(std::function notifier, - NotifierType direction, bool is_streaming) -{ - std::function invocation; - uint64_t token_value = 0; - { - std::lock_guard lock(m_mutex); - token_value = m_progress_notifier_token++; - NotifierPackage package{std::move(notifier), util::none, m_local_transaction_version, - is_streaming, direction == NotifierType::download}; - if (!m_current_progress) { - // Simply register the package, since we have no data yet. - m_packages.emplace(token_value, std::move(package)); - return token_value; - } - bool skip_registration = false; - invocation = package.create_invocation(*m_current_progress, skip_registration); - if (skip_registration) { - token_value = 0; - } else { - m_packages.emplace(token_value, std::move(package)); - } - } - invocation(); - return token_value; -} - -void SyncProgressNotifier::unregister_callback(uint64_t token) -{ - std::lock_guard lock(m_mutex); - m_packages.erase(token); -} - -void SyncProgressNotifier::update(uint64_t downloaded, uint64_t downloadable, - uint64_t uploaded, uint64_t uploadable, - uint64_t download_version, uint64_t snapshot_version) -{ - // Ignore progress messages from before we first receive a DOWNLOAD message - if (download_version == 0) - return; - - std::vector> invocations; - { - std::lock_guard lock(m_mutex); - m_current_progress = Progress{uploadable, downloadable, uploaded, downloaded, snapshot_version}; - - for (auto it = m_packages.begin(); it != m_packages.end(); ) { - bool should_delete = false; - invocations.emplace_back(it->second.create_invocation(*m_current_progress, should_delete)); - it = should_delete ? m_packages.erase(it) : std::next(it); - } - } - // Run the notifiers only after we've released the lock. - for (auto& invocation : invocations) - invocation(); -} - -void SyncProgressNotifier::set_local_version(uint64_t snapshot_version) -{ - std::lock_guard lock(m_mutex); - m_local_transaction_version = snapshot_version; -} - -std::function SyncProgressNotifier::NotifierPackage::create_invocation(Progress const& current_progress, bool& is_expired) -{ - uint64_t transferrable; - if (is_streaming) { - transferrable = is_download ? current_progress.downloadable : current_progress.uploadable; - } - else if (captured_transferrable) { - transferrable = *captured_transferrable; - } - else { - if (is_download) - captured_transferrable = current_progress.downloadable; - else { - // If the sync client has not yet processed all of the local - // transactions then the uploadable data is incorrect and we should - // not invoke the callback - if (snapshot_version > current_progress.snapshot_version) - return []{}; - captured_transferrable = current_progress.uploadable; - } - transferrable = *captured_transferrable; - } - - uint64_t transferred = is_download ? current_progress.downloaded : current_progress.uploaded; - // A notifier is expired if at least as many bytes have been transferred - // as were originally considered transferrable. - is_expired = !is_streaming && transferred >= transferrable; - return [=, notifier=notifier] { notifier(transferred, transferrable); }; -} - -uint64_t SyncSession::ConnectionChangeNotifier::add_callback(std::function callback) -{ - std::lock_guard lock(m_callback_mutex); - auto token = m_next_token++; - m_callbacks.push_back({std::move(callback), token}); - return token; -} - -void SyncSession::ConnectionChangeNotifier::remove_callback(uint64_t token) -{ - Callback old; - { - std::lock_guard lock(m_callback_mutex); - auto it = find_if(begin(m_callbacks), end(m_callbacks), - [=](const auto& c) { return c.token == token; }); - if (it == end(m_callbacks)) { - return; - } - - size_t idx = distance(begin(m_callbacks), it); - if (m_callback_index != npos) { - if (m_callback_index >= idx) - --m_callback_index; - } - --m_callback_count; - - old = std::move(*it); - m_callbacks.erase(it); - } -} - -void SyncSession::ConnectionChangeNotifier::invoke_callbacks(ConnectionState old_state, ConnectionState new_state) -{ - std::unique_lock lock(m_callback_mutex); - m_callback_count = m_callbacks.size(); - for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) { - // acquire a local reference to the callback so that removing the - // callback from within it can't result in a dangling pointer - auto cb = m_callbacks[m_callback_index].fn; - lock.unlock(); - cb(old_state, new_state); - lock.lock(); - } - m_callback_index = npos; -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp deleted file mode 100644 index b06dcde..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/sync/sync_user.cpp +++ /dev/null @@ -1,263 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "sync/sync_user.hpp" - -#include "sync/impl/sync_metadata.hpp" -#include "sync/sync_manager.hpp" -#include "sync/sync_session.hpp" - -namespace realm { - -SyncUserContextFactory SyncUser::s_binding_context_factory; -std::mutex SyncUser::s_binding_context_factory_mutex; - -SyncUser::SyncUser(std::string refresh_token, - std::string identity, - util::Optional server_url, - util::Optional local_identity, - TokenType token_type) -: m_state(State::Active) -, m_server_url(server_url.value_or("")) -, m_token_type(token_type) -, m_refresh_token(std::move(refresh_token)) -, m_identity(std::move(identity)) -{ - { - std::lock_guard lock(s_binding_context_factory_mutex); - if (s_binding_context_factory) { - m_binding_context = s_binding_context_factory(); - } - } - if (token_type == TokenType::Normal) { - REALM_ASSERT(m_server_url.length() > 0); - bool updated = SyncManager::shared().perform_metadata_update([=](const auto& manager) { - auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); - metadata->set_user_token(m_refresh_token); - m_is_admin = metadata->is_admin(); - m_local_identity = metadata->local_uuid(); - }); - if (!updated) - m_local_identity = m_identity; - } else { - // Admin token users. The local identity serves as the directory path. - REALM_ASSERT(local_identity); - m_local_identity = std::move(*local_identity); - } -} - -std::vector> SyncUser::all_sessions() -{ - std::lock_guard lock(m_mutex); - std::vector> sessions; - if (m_state == State::Error) { - return sessions; - } - for (auto it = m_sessions.begin(); it != m_sessions.end();) { - if (auto ptr_to_session = it->second.lock()) { - sessions.emplace_back(std::move(ptr_to_session)); - it++; - continue; - } - // This session is bad, destroy it. - it = m_sessions.erase(it); - } - return sessions; -} - -std::shared_ptr SyncUser::session_for_on_disk_path(const std::string& path) -{ - std::lock_guard lock(m_mutex); - if (m_state == State::Error) { - return nullptr; - } - auto it = m_sessions.find(path); - if (it == m_sessions.end()) { - return nullptr; - } - auto locked = it->second.lock(); - if (!locked) { - // Remove the session from the map, because it has fatally errored out or the entry is invalid. - m_sessions.erase(it); - } - return locked; -} - -void SyncUser::update_refresh_token(std::string token) -{ - std::vector> sessions_to_revive; - { - std::unique_lock lock(m_mutex); - if (auto session = m_management_session.lock()) - sessions_to_revive.emplace_back(std::move(session)); - - if (auto session = m_permission_session.lock()) - sessions_to_revive.emplace_back(std::move(session)); - - switch (m_state) { - case State::Error: - return; - case State::Active: - m_refresh_token = token; - break; - case State::LoggedOut: { - sessions_to_revive.reserve(m_waiting_sessions.size()); - m_refresh_token = token; - m_state = State::Active; - for (auto& pair : m_waiting_sessions) { - if (auto ptr = pair.second.lock()) { - m_sessions[pair.first] = ptr; - sessions_to_revive.emplace_back(std::move(ptr)); - } - } - m_waiting_sessions.clear(); - break; - } - } - // Update persistent user metadata. - if (m_token_type != TokenType::Admin) { - SyncManager::shared().perform_metadata_update([=](const auto& manager) { - auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); - metadata->set_user_token(token); - }); - } - } - // (Re)activate all pending sessions. - // Note that we do this after releasing the lock, since the session may - // need to access protected User state in the process of binding itself. - for (auto& session : sessions_to_revive) { - session->revive_if_needed(); - } -} - -void SyncUser::log_out() -{ - if (m_token_type == TokenType::Admin) { - // Admin-token users cannot be logged out. - return; - } - std::lock_guard lock(m_mutex); - if (m_state == State::LoggedOut) { - return; - } - m_state = State::LoggedOut; - // Move all active sessions into the waiting sessions pool. If the user is - // logged back in, they will automatically be reactivated. - for (auto& pair : m_sessions) { - if (auto ptr = pair.second.lock()) { - ptr->log_out(); - m_waiting_sessions[pair.first] = ptr; - } - } - m_sessions.clear(); - // Deactivate the sessions for the management and admin Realms. - if (auto session = m_management_session.lock()) - session->log_out(); - - if (auto session = m_permission_session.lock()) - session->log_out(); - - // Mark the user as 'dead' in the persisted metadata Realm. - SyncManager::shared().perform_metadata_update([=](const auto& manager) { - auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url, false); - if (metadata) - metadata->mark_for_removal(); - }); -} - -void SyncUser::set_is_admin(bool is_admin) -{ - if (m_token_type == TokenType::Admin) { - return; - } - m_is_admin = is_admin; - SyncManager::shared().perform_metadata_update([=](const auto& manager) { - auto metadata = manager.get_or_make_user_metadata(m_identity, m_server_url); - metadata->set_is_admin(is_admin); - }); -} - -void SyncUser::invalidate() -{ - std::lock_guard lock(m_mutex); - m_state = State::Error; -} - -std::string SyncUser::refresh_token() const -{ - std::lock_guard lock(m_mutex); - return m_refresh_token; -} - -SyncUser::State SyncUser::state() const -{ - std::lock_guard lock(m_mutex); - return m_state; -} - -void SyncUser::register_session(std::shared_ptr session) -{ - const std::string& path = session->path(); - std::unique_lock lock(m_mutex); - switch (m_state) { - case State::Active: - // Immediately ask the session to come online. - m_sessions[path] = session; - lock.unlock(); - session->revive_if_needed(); - break; - case State::LoggedOut: - m_waiting_sessions[path] = session; - break; - case State::Error: - break; - } -} - -void SyncUser::set_binding_context_factory(SyncUserContextFactory factory) -{ - std::lock_guard lock(s_binding_context_factory_mutex); - s_binding_context_factory = std::move(factory); -} - -void SyncUser::register_management_session(const std::string& path) -{ - std::lock_guard lock(m_mutex); - if (m_management_session.lock() || m_state == State::Error) - return; - - m_management_session = SyncManager::shared().get_existing_session(path); -} - -void SyncUser::register_permission_session(const std::string& path) -{ - std::lock_guard lock(m_mutex); - if (m_permission_session.lock() || m_state == State::Error) - return; - - m_permission_session = SyncManager::shared().get_existing_session(path); -} - -} - -namespace std { -size_t hash::operator()(const realm::SyncUserIdentifier& k) const -{ - return ((hash()(k.user_id) ^ (hash()(k.auth_server_url) << 1)) >> 1); -} -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp deleted file mode 100644 index 9469d89..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/thread_safe_reference.cpp +++ /dev/null @@ -1,123 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "thread_safe_reference.hpp" - -#include "impl/realm_coordinator.hpp" -#include "list.hpp" -#include "object.hpp" -#include "object_schema.hpp" -#include "results.hpp" - -#include - -using namespace realm; - -ThreadSafeReferenceBase::ThreadSafeReferenceBase(SharedRealm source_realm) : m_source_realm(std::move(source_realm)) -{ - m_source_realm->verify_thread(); - if (m_source_realm->is_in_transaction()) { - throw InvalidTransactionException("Cannot obtain thread safe reference during a write transaction."); - } - - try { - m_version_id = get_source_shared_group().pin_version(); - } catch (...) { - invalidate(); - throw; - } -} - -ThreadSafeReferenceBase::~ThreadSafeReferenceBase() -{ - if (!is_invalidated()) - invalidate(); -} - -template -V ThreadSafeReferenceBase::invalidate_after_import(Realm& destination_realm, T construct_with_shared_group) { - destination_realm.verify_thread(); - REALM_ASSERT_DEBUG(!m_source_realm->is_in_transaction()); - REALM_ASSERT_DEBUG(!is_invalidated()); - - SharedGroup& destination_shared_group = *Realm::Internal::get_shared_group(destination_realm); - auto unpin_version = util::make_scope_exit([&]() noexcept { invalidate(); }); - - return construct_with_shared_group(destination_shared_group); -} - -SharedGroup& ThreadSafeReferenceBase::get_source_shared_group() const { - return *Realm::Internal::get_shared_group(*m_source_realm); -} - -bool ThreadSafeReferenceBase::has_same_config(Realm& realm) const { - return &Realm::Internal::get_coordinator(*m_source_realm) == &Realm::Internal::get_coordinator(realm); -} - -void ThreadSafeReferenceBase::invalidate() { - REALM_ASSERT_DEBUG(m_source_realm); - SharedRealm thread_local_realm = Realm::Internal::get_coordinator(*m_source_realm).get_realm(); - Realm::Internal::get_shared_group(*thread_local_realm)->unpin_version(m_version_id); - m_source_realm = nullptr; -} - -ThreadSafeReference::ThreadSafeReference(List const& list) -: ThreadSafeReferenceBase(list.get_realm()) -, m_link_view(get_source_shared_group().export_linkview_for_handover(list.m_link_view)) -, m_table(get_source_shared_group().export_table_for_handover(list.m_table)) -{ } - -List ThreadSafeReference::import_into_realm(SharedRealm realm) && { - return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { - if (auto link_view = shared_group.import_linkview_from_handover(std::move(m_link_view))) - return List(std::move(realm), std::move(link_view)); - return List(std::move(realm), shared_group.import_table_from_handover(std::move(m_table))); - }); -} - -ThreadSafeReference::ThreadSafeReference(Object const& object) -: ThreadSafeReferenceBase(object.realm()) -, m_row(get_source_shared_group().export_for_handover(Row(object.row()))) -, m_object_schema_name(object.get_object_schema().name) { } - -Object ThreadSafeReference::import_into_realm(SharedRealm realm) && { - return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { - Row row = *shared_group.import_from_handover(std::move(m_row)); - auto object_schema = realm->schema().find(m_object_schema_name); - REALM_ASSERT_DEBUG(object_schema != realm->schema().end()); - return Object(std::move(realm), *object_schema, row); - }); -} - -ThreadSafeReference::ThreadSafeReference(Results const& results) -: ThreadSafeReferenceBase(results.get_realm()) -, m_query(get_source_shared_group().export_for_handover(results.get_query(), ConstSourcePayload::Copy)) -, m_ordering_patch([&]() { - DescriptorOrdering::HandoverPatch ordering_patch; - DescriptorOrdering::generate_patch(results.get_descriptor_ordering(), ordering_patch); - return ordering_patch; -}()){ } - -Results ThreadSafeReference::import_into_realm(SharedRealm realm) && { - return invalidate_after_import(*realm, [&](SharedGroup& shared_group) { - Query query = *shared_group.import_from_handover(std::move(m_query)); - Table& table = *query.get_table(); - DescriptorOrdering descriptors = DescriptorOrdering::create_from_and_consume_patch(m_ordering_patch, table); - return Results(std::move(realm), std::move(query), std::move(descriptors)); - }); -} diff --git a/Lesson14/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp b/Lesson14/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp deleted file mode 100644 index 0110002..0000000 --- a/Lesson14/Pods/Realm/Realm/ObjectStore/src/util/uuid.cpp +++ /dev/null @@ -1,80 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#include "util/uuid.hpp" - -#include -#include -#include -#include -#include - -namespace { - -// Seed `engine` with as much random state as it requires, based on the approach outlined in P0205R0. -// -template -T create_and_seed_engine() -{ - constexpr auto bytes_needed = T::state_size * sizeof(typename T::result_type); - - constexpr auto numbers_needed = sizeof(std::random_device::result_type) < sizeof(std::seed_seq::result_type) - ? (bytes_needed / sizeof(std::random_device::result_type)) - : (bytes_needed / sizeof(std::seed_seq::result_type)); - - std::array state; - std::random_device rd; - std::generate(begin(state), end(state), std::ref(rd)); - std::seed_seq seeds(begin(state), end(state)); - - T engine; - engine.seed(seeds); - return engine; -} - -} // unnamed namespace - -namespace realm { -namespace util { - -std::string uuid_string() -{ - static auto engine = create_and_seed_engine(); - - std::array uuid_bytes; - std::uniform_int_distribution distribution(0, std::numeric_limits::max()); - std::generate(begin(uuid_bytes), end(uuid_bytes), [&] { return distribution(engine); }); - - // Version 4 UUID. - uuid_bytes[6] = (uuid_bytes[6] & 0x0f) | 0x40; - // IETF variant. - uuid_bytes[8] = (uuid_bytes[8] & 0x3f) | 0x80; - - std::array uuid_formatted; - snprintf(uuid_formatted.data(), uuid_formatted.size(), - "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - uuid_bytes[0], uuid_bytes[1], uuid_bytes[2], uuid_bytes[3], - uuid_bytes[4], uuid_bytes[5], uuid_bytes[6], uuid_bytes[7], - uuid_bytes[8], uuid_bytes[9], uuid_bytes[10], uuid_bytes[11], - uuid_bytes[12], uuid_bytes[13], uuid_bytes[14], uuid_bytes[15]); - - return std::string(uuid_formatted.data(), uuid_formatted.size() - 1); -} - -} // namespace util -} // namespace realm diff --git a/Lesson14/Pods/Realm/Realm/RLMAccessor.mm b/Lesson14/Pods/Realm/Realm/RLMAccessor.mm deleted file mode 100644 index 48a288a..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMAccessor.mm +++ /dev/null @@ -1,808 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMAccessor.hpp" - -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObject_Private.hpp" -#import "RLMObservation.hpp" -#import "RLMProperty_Private.h" -#import "RLMRealm_Private.hpp" -#import "RLMResults_Private.hpp" -#import "RLMSchema_Private.h" -#import "RLMUtil.hpp" -#import "results.hpp" -#import "property.hpp" - -#import -#import -#import - -#pragma mark - Helper functions - -namespace { -template -T get(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) { - RLMVerifyAttached(obj); - return obj->_row.get(obj->_info->objectSchema->persisted_properties[index].table_column); -} - -template -id getBoxed(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) { - RLMVerifyAttached(obj); - auto& prop = obj->_info->objectSchema->persisted_properties[index]; - auto col = prop.table_column; - if (obj->_row.is_null(col)) { - return nil; - } - - RLMAccessorContext ctx(obj, &prop); - return ctx.box(obj->_row.get(col)); -} - -template -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, T val) { - RLMVerifyInWriteTransaction(obj); - obj->_row.set(colIndex, val); -} - -template -auto translateError(Fn&& fn) { - try { - return fn(); - } - catch (std::exception const& e) { - @throw RLMException(e); - } -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSString *const val) { - RLMVerifyInWriteTransaction(obj); - translateError([&] { - obj->_row.set(colIndex, RLMStringDataWithNSString(val)); - }); -} - -[[gnu::noinline]] -void setNull(realm::Row& row, size_t col) { - translateError([&] { row.set_null(col); }); -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, - NSUInteger colIndex, __unsafe_unretained NSDate *const date) { - RLMVerifyInWriteTransaction(obj); - if (date) { - obj->_row.set(colIndex, RLMTimestampForNSDate(date)); - } - else { - setNull(obj->_row, colIndex); - } -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSData *const data) { - RLMVerifyInWriteTransaction(obj); - translateError([&] { - obj->_row.set(colIndex, RLMBinaryDataForNSData(data)); - }); -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained RLMObjectBase *const val) { - RLMVerifyInWriteTransaction(obj); - if (!val) { - obj->_row.nullify_link(colIndex); - return; - } - - RLMAddObjectToRealm(val, obj->_realm, RLMUpdatePolicyError); - - // make sure it is the correct type - if (val->_row.get_table() != obj->_row.get_table()->get_link_target(colIndex)) { - @throw RLMException(@"Can't set object of type '%@' to property of type '%@'", - val->_objectSchema.className, - obj->_info->propertyForTableColumn(colIndex).objectClassName); - } - obj->_row.set_link(colIndex, val->_row.get_index()); -} - -// array getter/setter -RLMArray *getArray(__unsafe_unretained RLMObjectBase *const obj, NSUInteger propIndex) { - RLMVerifyAttached(obj); - auto prop = obj->_info->rlmObjectSchema.properties[propIndex]; - return [[RLMManagedArray alloc] initWithParent:obj property:prop]; -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained id const value) { - RLMVerifyInWriteTransaction(obj); - auto prop = obj->_info->propertyForTableColumn(colIndex); - RLMValidateValueForProperty(value, obj->_info->rlmObjectSchema, prop, true); - - realm::List list(obj->_realm->_realm, *obj->_row.get_table(), colIndex, obj->_row.get_index()); - RLMClassInfo *info = obj->_info; - if (list.get_type() == realm::PropertyType::Object) { - info = &obj->_info->linkTargetType(prop.index); - } - RLMAccessorContext ctx(*info); - translateError([&] { - list.assign(ctx, value, realm::CreatePolicy::ForceCreate); - }); -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSNumber *const intObject) { - RLMVerifyInWriteTransaction(obj); - - if (intObject) { - obj->_row.set(colIndex, intObject.longLongValue); - } - else { - setNull(obj->_row, colIndex); - } -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSNumber *const floatObject) { - RLMVerifyInWriteTransaction(obj); - - if (floatObject) { - obj->_row.set(colIndex, floatObject.floatValue); - } - else { - setNull(obj->_row, colIndex); - } -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSNumber *const doubleObject) { - RLMVerifyInWriteTransaction(obj); - - if (doubleObject) { - obj->_row.set(colIndex, doubleObject.doubleValue); - } - else { - setNull(obj->_row, colIndex); - } -} - -void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, - __unsafe_unretained NSNumber *const boolObject) { - RLMVerifyInWriteTransaction(obj); - - if (boolObject) { - obj->_row.set(colIndex, (bool)boolObject.boolValue); - } - else { - setNull(obj->_row, colIndex); - } -} - -RLMLinkingObjects *getLinkingObjects(__unsafe_unretained RLMObjectBase *const obj, - __unsafe_unretained RLMProperty *const property) { - RLMVerifyAttached(obj); - auto& objectInfo = obj->_realm->_info[property.objectClassName]; - auto& linkOrigin = obj->_info->objectSchema->computed_properties[property.index].link_origin_property_name; - auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin); - auto backlinkView = obj->_row.get_table()->get_backlink_view(obj->_row.get_index(), - objectInfo.table(), - linkingProperty->table_column); - realm::Results results(obj->_realm->_realm, std::move(backlinkView)); - return [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)]; -} - -// any getter/setter -template -id makeGetter(NSUInteger index) { - return ^(__unsafe_unretained RLMObjectBase *const obj) { - return static_cast(get(obj, index)); - }; -} - -template -id makeBoxedGetter(NSUInteger index) { - return ^(__unsafe_unretained RLMObjectBase *const obj) { - return getBoxed(obj, index); - }; -} -template -id makeOptionalGetter(NSUInteger index) { - return ^(__unsafe_unretained RLMObjectBase *const obj) { - return getBoxed>(obj, index); - }; -} -template -id makeNumberGetter(NSUInteger index, bool boxed, bool optional) { - if (optional) { - return makeOptionalGetter(index); - } - if (boxed) { - return makeBoxedGetter(index); - } - return makeGetter(index); -} - -// dynamic getter with column closure -id managedGetter(RLMProperty *prop, const char *type) { - NSUInteger index = prop.index; - if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) { - return ^id(__unsafe_unretained RLMObjectBase *const obj) { - return getArray(obj, index); - }; - } - - bool boxed = *type == '@'; - switch (prop.type) { - case RLMPropertyTypeInt: - if (prop.optional || boxed) { - return makeNumberGetter(index, boxed, prop.optional); - } - switch (*type) { - case 'c': return makeGetter(index); - case 's': return makeGetter(index); - case 'i': return makeGetter(index); - case 'l': return makeGetter(index); - case 'q': return makeGetter(index); - default: - @throw RLMException(@"Unexpected property type for Objective-C type code"); - } - case RLMPropertyTypeFloat: - return makeNumberGetter(index, boxed, prop.optional); - case RLMPropertyTypeDouble: - return makeNumberGetter(index, boxed, prop.optional); - case RLMPropertyTypeBool: - return makeNumberGetter(index, boxed, prop.optional); - case RLMPropertyTypeString: - return makeBoxedGetter(index); - case RLMPropertyTypeDate: - return makeBoxedGetter(index); - case RLMPropertyTypeData: - return makeBoxedGetter(index); - case RLMPropertyTypeObject: - return makeBoxedGetter(index); - case RLMPropertyTypeAny: - @throw RLMException(@"Cannot create accessor class for schema with Mixed properties"); - case RLMPropertyTypeLinkingObjects: - return ^(__unsafe_unretained RLMObjectBase *const obj) { - return getLinkingObjects(obj, prop); - }; - } -} - -template -id makeSetter(__unsafe_unretained RLMProperty *const prop) { - NSUInteger index = prop.index; - NSString *name = prop.name; - if (prop.isPrimary) { - return ^(__unused RLMObjectBase *obj, __unused ArgType val) { - @throw RLMException(@"Primary key can't be changed after an object is inserted."); - }; - } - - return ^(__unsafe_unretained RLMObjectBase *const obj, ArgType val) { - auto set = [&] { - setValue(obj, obj->_info->objectSchema->persisted_properties[index].table_column, - static_cast(val)); - }; - if (RLMObservationInfo *info = RLMGetObservationInfo(obj->_observationInfo, - obj->_row.get_index(), *obj->_info)) { - info->willChange(name); - set(); - info->didChange(name); - } - else { - set(); - } - }; -} - -// dynamic setter with column closure -id managedSetter(RLMProperty *prop, const char *type) { - if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) { - return makeSetter>(prop); - } - - bool boxed = prop.optional || *type == '@'; - switch (prop.type) { - case RLMPropertyTypeInt: - if (boxed) { - return makeSetter *>(prop); - } - switch (*type) { - case 'c': return makeSetter(prop); - case 's': return makeSetter(prop); - case 'i': return makeSetter(prop); - case 'l': return makeSetter(prop); - case 'q': return makeSetter(prop); - default: - @throw RLMException(@"Unexpected property type for Objective-C type code"); - } - case RLMPropertyTypeFloat: - return boxed ? makeSetter *>(prop) : makeSetter(prop); - case RLMPropertyTypeDouble: - return boxed ? makeSetter *>(prop) : makeSetter(prop); - case RLMPropertyTypeBool: - return boxed ? makeSetter *>(prop) : makeSetter(prop); - case RLMPropertyTypeString: return makeSetter(prop); - case RLMPropertyTypeDate: return makeSetter(prop); - case RLMPropertyTypeData: return makeSetter(prop); - case RLMPropertyTypeAny: return nil; - case RLMPropertyTypeLinkingObjects: return nil; - case RLMPropertyTypeObject: return makeSetter(prop); - } -} - -// call getter for superclass for property at colIndex -id superGet(RLMObjectBase *obj, NSString *propName) { - typedef id (*getter_type)(RLMObjectBase *, SEL); - RLMProperty *prop = obj->_objectSchema[propName]; - Class superClass = class_getSuperclass(obj.class); - getter_type superGetter = (getter_type)[superClass instanceMethodForSelector:prop.getterSel]; - return superGetter(obj, prop.getterSel); -} - -// call setter for superclass for property at colIndex -void superSet(RLMObjectBase *obj, NSString *propName, id val) { - typedef void (*setter_type)(RLMObjectBase *, SEL, RLMArray *ar); - RLMProperty *prop = obj->_objectSchema[propName]; - Class superClass = class_getSuperclass(obj.class); - setter_type superSetter = (setter_type)[superClass instanceMethodForSelector:prop.setterSel]; - superSetter(obj, prop.setterSel, val); -} - -// getter/setter for unmanaged object -id unmanagedGetter(RLMProperty *prop, const char *) { - // only override getters for RLMArray and linking objects properties - if (prop.type == RLMPropertyTypeLinkingObjects) { - return ^(RLMObjectBase *) { return [RLMResults emptyDetachedResults]; }; - } - if (prop.array) { - NSString *propName = prop.name; - if (prop.type == RLMPropertyTypeObject) { - NSString *objectClassName = prop.objectClassName; - return ^(RLMObjectBase *obj) { - id val = superGet(obj, propName); - if (!val) { - val = [[RLMArray alloc] initWithObjectClassName:objectClassName]; - superSet(obj, propName, val); - } - return val; - }; - } - auto type = prop.type; - auto optional = prop.optional; - return ^(RLMObjectBase *obj) { - id val = superGet(obj, propName); - if (!val) { - val = [[RLMArray alloc] initWithObjectType:type optional:optional]; - superSet(obj, propName, val); - } - return val; - }; - } - return nil; -} - -id unmanagedSetter(RLMProperty *prop, const char *) { - // Only RLMArray needs special handling for the unmanaged setter - if (!prop.array) { - return nil; - } - - NSString *propName = prop.name; - return ^(RLMObjectBase *obj, id values) { - auto prop = obj->_objectSchema[propName]; - RLMValidateValueForProperty(values, obj->_objectSchema, prop, true); - - // make copy when setting (as is the case for all other variants) - RLMArray *ar; - if (prop.type == RLMPropertyTypeObject) - ar = [[RLMArray alloc] initWithObjectClassName:prop.objectClassName]; - else - ar = [[RLMArray alloc] initWithObjectType:prop.type optional:prop.optional]; - [ar addObjects:values]; - superSet(obj, propName, ar); - }; -} - -void addMethod(Class cls, __unsafe_unretained RLMProperty *const prop, - id (*getter)(RLMProperty *, const char *), - id (*setter)(RLMProperty *, const char *)) { - SEL sel = prop.getterSel; - auto getterMethod = class_getInstanceMethod(cls, sel); - if (!getterMethod) { - return; - } - - const char *getterType = method_getTypeEncoding(getterMethod); - if (id block = getter(prop, getterType)) { - class_addMethod(cls, sel, imp_implementationWithBlock(block), getterType); - } - - if (!(sel = prop.setterSel)) { - return; - } - auto setterMethod = class_getInstanceMethod(cls, sel); - if (!setterMethod) { - return; - } - if (id block = setter(prop, getterType)) { // note: deliberately getterType as it's easier to grab the relevant type from - class_addMethod(cls, sel, imp_implementationWithBlock(block), method_getTypeEncoding(setterMethod)); - } -} - -Class createAccessorClass(Class objectClass, - RLMObjectSchema *schema, - const char *accessorClassName, - id (*getterGetter)(RLMProperty *, const char *), - id (*setterGetter)(RLMProperty *, const char *)) { - REALM_ASSERT_DEBUG(RLMIsObjectOrSubclass(objectClass)); - - // create and register proxy class which derives from object class - Class accClass = objc_allocateClassPair(objectClass, accessorClassName, 0); - if (!accClass) { - // Class with that name already exists, so just return the pre-existing one - // This should only happen for our standalone "accessors" - return objc_lookUpClass(accessorClassName); - } - - // override getters/setters for each propery - for (RLMProperty *prop in schema.properties) { - addMethod(accClass, prop, getterGetter, setterGetter); - } - for (RLMProperty *prop in schema.computedProperties) { - addMethod(accClass, prop, getterGetter, setterGetter); - } - - objc_registerClassPair(accClass); - - return accClass; -} -} // anonymous namespace - -#pragma mark - Public Interface - -Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name) { - return createAccessorClass(objectClass, schema, name, managedGetter, managedSetter); -} - -Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema) { - return createAccessorClass(objectClass, schema, - [@"RLM:Unmanaged " stringByAppendingString:schema.className].UTF8String, - unmanagedGetter, unmanagedSetter); -} - -// implement the class method className on accessors to return the className of the -// base object -void RLMReplaceClassNameMethod(Class accessorClass, NSString *className) { - Class metaClass = object_getClass(accessorClass); - IMP imp = imp_implementationWithBlock(^(Class){ return className; }); - class_addMethod(metaClass, @selector(className), imp, "@@:"); -} - -// implement the shared schema method -void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema *schema) { - Class metaClass = object_getClass(accessorClass); - IMP imp = imp_implementationWithBlock(^(Class cls) { - if (cls == accessorClass) { - return schema; - } - - // If we aren't being called directly on the class this was overriden - // for, the class is either a subclass which we haven't initialized yet, - // or it's a runtime-generated class which should use the parent's - // schema. We check for the latter by checking if the immediate - // descendent of the desired class is a class generated by us (there - // may be further subclasses not generated by us for things like KVO). - Class parent = class_getSuperclass(cls); - while (parent != accessorClass) { - cls = parent; - parent = class_getSuperclass(cls); - } - - static const char accessorClassPrefix[] = "RLM:"; - if (!strncmp(class_getName(cls), accessorClassPrefix, sizeof(accessorClassPrefix) - 1)) { - return schema; - } - - return [RLMSchema sharedSchemaForClass:cls]; - }); - class_addMethod(metaClass, @selector(sharedSchema), imp, "@@:"); -} - -void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id val) { - RLMVerifyAttached(obj); - RLMObjectSchema *schema = obj->_objectSchema; - RLMProperty *prop = schema[propName]; - if (!prop) { - @throw RLMException(@"Invalid property name '%@' for class '%@'.", - propName, obj->_objectSchema.className); - } - if (prop.isPrimary) { - @throw RLMException(@"Primary key can't be changed to '%@' after an object is inserted.", val); - } - RLMValidateValueForProperty(val, schema, prop, true); - RLMDynamicSet(obj, prop, RLMCoerceToNil(val)); -} - -// Precondition: the property is not a primary key -void RLMDynamicSet(__unsafe_unretained RLMObjectBase *const obj, - __unsafe_unretained RLMProperty *const prop, - __unsafe_unretained id const val) { - REALM_ASSERT_DEBUG(!prop.isPrimary); - realm::Object o(obj->_info->realm->_realm, *obj->_info->objectSchema, obj->_row); - RLMAccessorContext c(obj); - translateError([&] { - o.set_property_value(c, prop.columnName.UTF8String, val ?: NSNull.null); - }); -} - -id RLMDynamicGet(__unsafe_unretained RLMObjectBase *const obj, __unsafe_unretained RLMProperty *const prop) { - realm::Object o(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row); - RLMAccessorContext c(obj); - c.currentProperty = prop; - return translateError([&] { - return RLMCoerceToNil(o.get_property_value(c, prop.columnName.UTF8String)); - }); -} - -id RLMDynamicGetByName(__unsafe_unretained RLMObjectBase *const obj, - __unsafe_unretained NSString *const propName) { - RLMProperty *prop = obj->_objectSchema[propName]; - if (!prop) { - @throw RLMException(@"Invalid property name '%@' for class '%@'.", - propName, obj->_objectSchema.className); - } - return RLMDynamicGet(obj, prop); -} - -RLMAccessorContext::RLMAccessorContext(RLMAccessorContext& parent, realm::Property const& property) -: _realm(parent._realm) -, _info(property.type == realm::PropertyType::Object ? parent._info.linkTargetType(property) : parent._info) -, _promote_existing(parent._promote_existing) -{ -} - -RLMAccessorContext::RLMAccessorContext(RLMClassInfo& info, bool promote) -: _realm(info.realm), _info(info), _promote_existing(promote) -{ -} - -RLMAccessorContext::RLMAccessorContext(__unsafe_unretained RLMObjectBase *const parent, - const realm::Property *prop) -: _realm(parent->_realm) -, _info(prop && prop->type == realm::PropertyType::Object ? parent->_info->linkTargetType(*prop) - : *parent->_info) -, _parentObject(parent) -{ -} - -id RLMAccessorContext::defaultValue(__unsafe_unretained NSString *const key) { - if (!_defaultValues) { - _defaultValues = RLMDefaultValuesForObjectSchema(_info.rlmObjectSchema); - } - return _defaultValues[key]; -} - -id RLMAccessorContext::propertyValue(__unsafe_unretained id const obj, size_t propIndex, - __unsafe_unretained RLMProperty *const prop) { - // Property value from an NSArray - if ([obj respondsToSelector:@selector(objectAtIndex:)]) { - return propIndex < [obj count] ? [obj objectAtIndex:propIndex] : nil; - } - - // Property value from an NSDictionary - if ([obj respondsToSelector:@selector(objectForKey:)]) { - return [obj objectForKey:prop.name]; - } - - // Property value from an instance of this object type - id value; - if ([obj isKindOfClass:_info.rlmObjectSchema.objectClass] && prop.swiftIvar) { - if (prop.array) { - return static_cast(object_getIvar(obj, prop.swiftIvar))._rlmArray; - } - else { // optional - value = RLMGetOptional(static_cast(object_getIvar(obj, prop.swiftIvar))); - } - } - else { - // Property value from some object that's KVC-compatible - value = RLMValidatedValueForProperty(obj, [obj respondsToSelector:prop.getterSel] ? prop.getterName : prop.name, - _info.rlmObjectSchema.className); - } - return value ?: NSNull.null; -} - -id RLMAccessorContext::box(realm::List&& l) { - REALM_ASSERT(_parentObject); - REALM_ASSERT(currentProperty); - return [[RLMManagedArray alloc] initWithList:std::move(l) - parentInfo:_parentObject->_info - property:currentProperty]; -} - -id RLMAccessorContext::box(realm::Object&& o) { - REALM_ASSERT(currentProperty); - return RLMCreateObjectAccessor(_info.linkTargetType(currentProperty.index), o.row()); -} - -id RLMAccessorContext::box(realm::RowExpr r) { - return RLMCreateObjectAccessor(_info, r); -} - -id RLMAccessorContext::box(realm::Results&& r) { - REALM_ASSERT(currentProperty); - return [RLMResults resultsWithObjectInfo:_realm->_info[currentProperty.objectClassName] - results:std::move(r)]; -} - -template<> -realm::Timestamp RLMAccessorContext::unbox(__unsafe_unretained id const value, realm::CreatePolicy, size_t) { - id v = RLMCoerceToNil(value); - return RLMTimestampForNSDate(v); -} - -template<> -bool RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return [v boolValue]; -} -template<> -double RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return [v doubleValue]; -} -template<> -float RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return [v floatValue]; -} -template<> -long long RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return [v longLongValue]; -} -template<> -realm::BinaryData RLMAccessorContext::unbox(id v, realm::CreatePolicy, size_t) { - v = RLMCoerceToNil(v); - return RLMBinaryDataForNSData(v); -} -template<> -realm::StringData RLMAccessorContext::unbox(id v, realm::CreatePolicy, size_t) { - v = RLMCoerceToNil(v); - return RLMStringDataWithNSString(v); -} - -template -static auto to_optional(__unsafe_unretained id const value, Fn&& fn) { - id v = RLMCoerceToNil(value); - return v && v != NSNull.null ? realm::util::make_optional(fn(v)) : realm::util::none; -} - -template<> -realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return to_optional(v, [&](__unsafe_unretained id v) { return (bool)[v boolValue]; }); -} -template<> -realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return to_optional(v, [&](__unsafe_unretained id v) { return [v doubleValue]; }); -} -template<> -realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return to_optional(v, [&](__unsafe_unretained id v) { return [v floatValue]; }); -} -template<> -realm::util::Optional RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) { - return to_optional(v, [&](__unsafe_unretained id v) { return [v longLongValue]; }); -} - -template<> -realm::RowExpr RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy createPolicy, size_t) { - bool create = createPolicy != realm::CreatePolicy::Skip; - auto policy = static_cast(createPolicy); - RLMObjectBase *link = RLMDynamicCast(v); - if (!link) { - if (!create) - return realm::RowExpr(); - return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, policy)->_row; - } - - if (link.isInvalidated) { - if (create) { - @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted"); - } - else { - @throw RLMException(@"Object has been invalidated"); - } - } - - if (![link->_objectSchema.className isEqualToString:_info.rlmObjectSchema.className]) { - if (create && !_promote_existing) - return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, policy)->_row; - return link->_row; - } - - if (!link->_realm) { - if (!create) - return realm::RowExpr(); - if (!_promote_existing) - return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, policy)->_row; - RLMAddObjectToRealm(link, _realm, policy); - } - else if (link->_realm != _realm) { - if (_promote_existing) - @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm."); - return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, policy)->_row; - } - return link->_row; -} - -void RLMAccessorContext::will_change(realm::Row const& row, realm::Property const& prop) { - _observationInfo = RLMGetObservationInfo(nullptr, row.get_index(), _info); - if (_observationInfo) { - _kvoPropertyName = _info.propertyForTableColumn(prop.table_column).name; - _observationInfo->willChange(_kvoPropertyName); - } -} - -void RLMAccessorContext::did_change() { - if (_observationInfo) { - _observationInfo->didChange(_kvoPropertyName); - _kvoPropertyName = nil; - _observationInfo = nullptr; - } -} - -RLMOptionalId RLMAccessorContext::value_for_property(__unsafe_unretained id const obj, - realm::Property const&, size_t propIndex) { - auto prop = _info.rlmObjectSchema.properties[propIndex]; - id value = propertyValue(obj, propIndex, prop); - if (value) { - RLMValidateValueForProperty(value, _info.rlmObjectSchema, prop); - } - - if (_promote_existing && [obj isKindOfClass:_info.rlmObjectSchema.objectClass] && !prop.swiftIvar) { - // set the ivars for object and array properties to nil as otherwise the - // accessors retain objects that are no longer accessible via the properties - // this is mainly an issue when the object graph being added has cycles, - // as it's not obvious that the user has to set the *ivars* to nil to - // avoid leaking memory - if (prop.type == RLMPropertyTypeObject) { - ((void(*)(id, SEL, id))objc_msgSend)(obj, prop.setterSel, nil); - } - } - - return RLMOptionalId{value}; -} - -RLMOptionalId RLMAccessorContext::default_value_for_property(realm::ObjectSchema const&, - realm::Property const& prop) -{ - return RLMOptionalId{defaultValue(@(prop.name.c_str()))}; -} - -bool RLMAccessorContext::is_same_list(realm::List const& list, __unsafe_unretained id const v) const noexcept { - return [v respondsToSelector:@selector(isBackedByList:)] && [v isBackedByList:list]; -} - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wincomplete-implementation" -@implementation RLMManagedPropertyAccessor -@end -#pragma clang diagnostic pop diff --git a/Lesson14/Pods/Realm/Realm/RLMAnalytics.mm b/Lesson14/Pods/Realm/Realm/RLMAnalytics.mm deleted file mode 100644 index b1cd5ac..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMAnalytics.mm +++ /dev/null @@ -1,247 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -// Asynchronously submits build information to Realm if running in an iOS -// simulator or on OS X if a debugger is attached. Does nothing if running on an -// iOS / watchOS device or if a debugger is *not* attached. -// -// To be clear: this does *not* run when your app is in production or on -// your end-user’s devices; it will only run in the simulator or when a debugger -// is attached. -// -// Why are we doing this? In short, because it helps us build a better product -// for you. None of the data personally identifies you, your employer or your -// app, but it *will* help us understand what language you use, what iOS -// versions you target, etc. Having this info will help prioritizing our time, -// adding new features and deprecating old features. Collecting an anonymized -// bundle & anonymized MAC is the only way for us to count actual usage of the -// other metrics accurately. If we don’t have a way to deduplicate the info -// reported, it will be useless, as a single developer building their Swift app -// 10 times would report 10 times more than a single Objective-C developer that -// only builds once, making the data all but useless. -// No one likes sharing data unless it’s necessary, we get it, and we’ve -// debated adding this for a long long time. Since Realm is a free product -// without an email signup, we feel this is a necessary step so we can collect -// relevant data to build a better product for you. If you truly, absolutely -// feel compelled to not send this data back to Realm, then you can set an env -// variable named REALM_DISABLE_ANALYTICS. Since Realm is free we believe -// letting these analytics run is a small price to pay for the product & support -// we give you. -// -// Currently the following information is reported: -// - What version of Realm is being used, and from which language (obj-c or Swift). -// - What version of OS X it's running on (in case Xcode aggressively drops -// support for older versions again, we need to know what we need to support). -// - The minimum iOS/OS X version that the application is targeting (again, to -// help us decide what versions we need to support). -// - An anonymous MAC address and bundle ID to aggregate the other information on. -// - What version of Swift is being used (if applicable). - -#import "RLMAnalytics.hpp" - -#import - -#if TARGET_IPHONE_SIMULATOR || TARGET_OS_MAC || (TARGET_OS_WATCH && TARGET_OS_SIMULATOR) || (TARGET_OS_TV && TARGET_OS_SIMULATOR) -#import "RLMRealm.h" -#import "RLMUtil.hpp" - -#import -#import -#import -#import -#import - -#import - -#ifndef REALM_COCOA_VERSION -#import "RLMVersion.h" -#endif - -#if REALM_ENABLE_SYNC -#import -#endif - -// Declared for RealmSwiftObjectUtil -@interface NSObject (SwiftVersion) -+ (NSString *)swiftVersion; -@end - -// Wrapper for sysctl() that handles the memory management stuff -static auto RLMSysCtl(int *mib, u_int mibSize, size_t *bufferSize) { - std::unique_ptr buffer(nullptr, &free); - - int ret = sysctl(mib, mibSize, nullptr, bufferSize, nullptr, 0); - if (ret != 0) { - return buffer; - } - - buffer.reset(malloc(*bufferSize)); - if (!buffer) { - return buffer; - } - - ret = sysctl(mib, mibSize, buffer.get(), bufferSize, nullptr, 0); - if (ret != 0) { - buffer.reset(); - } - - return buffer; -} - -// Get the version of OS X we're running on (even in the simulator this gives -// the OS X version and not the simulated iOS version) -static NSString *RLMOSVersion() { - std::array mib = {{CTL_KERN, KERN_OSRELEASE}}; - size_t bufferSize; - auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize); - if (!buffer) { - return nil; - } - - return [[NSString alloc] initWithBytesNoCopy:buffer.release() - length:bufferSize - 1 - encoding:NSUTF8StringEncoding - freeWhenDone:YES]; -} - -// Hash the data in the given buffer and convert it to a hex-format string -static NSString *RLMHashData(const void *bytes, size_t length) { - unsigned char buffer[CC_SHA256_DIGEST_LENGTH]; - CC_SHA256(bytes, static_cast(length), buffer); - - char formatted[CC_SHA256_DIGEST_LENGTH * 2 + 1]; - for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { - sprintf(formatted + i * 2, "%02x", buffer[i]); - } - - return [[NSString alloc] initWithBytes:formatted - length:CC_SHA256_DIGEST_LENGTH * 2 - encoding:NSUTF8StringEncoding]; -} - -// Returns the hash of the MAC address of the first network adaptor since the -// vendorIdentifier isn't constant between iOS simulators. -static NSString *RLMMACAddress() { - int en0 = static_cast(if_nametoindex("en0")); - if (!en0) { - return nil; - } - - std::array mib = {{CTL_NET, PF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, en0}}; - size_t bufferSize; - auto buffer = RLMSysCtl(&mib[0], mib.size(), &bufferSize); - if (!buffer) { - return nil; - } - - // sockaddr_dl struct is immediately after the if_msghdr struct in the buffer - auto sockaddr = reinterpret_cast(static_cast(buffer.get()) + 1); - auto mac = reinterpret_cast(sockaddr->sdl_data + sockaddr->sdl_nlen); - - return RLMHashData(mac, 6); -} - -static NSDictionary *RLMAnalyticsPayload() { - NSBundle *appBundle = NSBundle.mainBundle; - NSString *hashedBundleID = appBundle.bundleIdentifier; - - // Main bundle isn't always the one of interest (e.g. when running tests - // it's xctest rather than the app's bundle), so look for one with a bundle ID - if (!hashedBundleID) { - for (NSBundle *bundle in NSBundle.allBundles) { - if ((hashedBundleID = bundle.bundleIdentifier)) { - appBundle = bundle; - break; - } - } - } - - // If we found a bundle ID anywhere, hash it as it could contain sensitive - // information (e.g. the name of an unnanounced product) - if (hashedBundleID) { - NSData *data = [hashedBundleID dataUsingEncoding:NSUTF8StringEncoding]; - hashedBundleID = RLMHashData(data.bytes, data.length); - } - - NSString *osVersionString = [[NSProcessInfo processInfo] operatingSystemVersionString]; - Class swiftObjectUtilClass = NSClassFromString(@"RealmSwiftObjectUtil"); - BOOL isSwift = swiftObjectUtilClass != nil; - NSString *swiftVersion = isSwift ? [swiftObjectUtilClass swiftVersion] : @"N/A"; - - static NSString *kUnknownString = @"unknown"; - NSString *hashedMACAddress = RLMMACAddress() ?: kUnknownString; - - return @{ - @"event": @"Run", - @"properties": @{ - // MixPanel properties - @"token": @"ce0fac19508f6c8f20066d345d360fd0", - - // Anonymous identifiers to deduplicate events - @"distinct_id": hashedMACAddress, - @"Anonymized MAC Address": hashedMACAddress, - @"Anonymized Bundle ID": hashedBundleID ?: kUnknownString, - - // Which version of Realm is being used - @"Binding": @"cocoa", - @"Language": isSwift ? @"swift" : @"objc", - @"Realm Version": REALM_COCOA_VERSION, -#if REALM_ENABLE_SYNC - @"Sync Version": @(REALM_SYNC_VER_STRING), -#endif -#if TARGET_OS_WATCH - @"Target OS Type": @"watchos", -#elif TARGET_OS_TV - @"Target OS Type": @"tvos", -#elif TARGET_OS_IPHONE - @"Target OS Type": @"ios", -#else - @"Target OS Type": @"osx", -#endif - @"Swift Version": swiftVersion, - // Current OS version the app is targetting - @"Target OS Version": osVersionString, - // Minimum OS version the app is targetting - @"Target OS Minimum Version": appBundle.infoDictionary[@"MinimumOSVersion"] ?: kUnknownString, - - // Host OS version being built on - @"Host OS Type": @"osx", - @"Host OS Version": RLMOSVersion() ?: kUnknownString, - } - }; -} - -void RLMSendAnalytics() { - if (getenv("REALM_DISABLE_ANALYTICS") || !RLMIsDebuggerAttached() || RLMIsRunningInPlayground()) { - return; - } - - - NSData *payload = [NSJSONSerialization dataWithJSONObject:RLMAnalyticsPayload() options:0 error:nil]; - NSString *url = [NSString stringWithFormat:@"https://api.mixpanel.com/track/?data=%@&ip=1", [payload base64EncodedStringWithOptions:0]]; - - // No error handling or anything because logging errors annoyed people for no - // real benefit, and it's not clear what else we could do - [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:url]] resume]; -} - -#else - -void RLMSendAnalytics() {} - -#endif diff --git a/Lesson14/Pods/Realm/Realm/RLMArray.mm b/Lesson14/Pods/Realm/Realm/RLMArray.mm deleted file mode 100644 index 2262e78..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMArray.mm +++ /dev/null @@ -1,587 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMArray_Private.hpp" - -#import "RLMObjectSchema.h" -#import "RLMObjectStore.h" -#import "RLMObject_Private.h" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" -#import "RLMThreadSafeReference_Private.hpp" -#import "RLMUtil.hpp" - -// See -countByEnumeratingWithState:objects:count -@interface RLMArrayHolder : NSObject { -@public - std::unique_ptr items; -} -@end -@implementation RLMArrayHolder -@end - -@interface RLMArray () -@end - -@implementation RLMArray { -@public - // Backing array when this instance is unmanaged - NSMutableArray *_backingArray; -} - -#pragma mark - Initializers - -- (instancetype)initWithObjectClassName:(__unsafe_unretained NSString *const)objectClassName { - REALM_ASSERT([objectClassName length] > 0); - self = [super init]; - if (self) { - _objectClassName = objectClassName; - _type = RLMPropertyTypeObject; - } - return self; -} - -- (instancetype)initWithObjectType:(RLMPropertyType)type optional:(BOOL)optional { - self = [super init]; - if (self) { - _type = type; - _optional = optional; - } - return self; -} - -#pragma mark - Convenience wrappers used for all RLMArray types - -- (void)addObjects:(id)objects { - for (id obj in objects) { - [self addObject:obj]; - } -} - -- (void)addObject:(id)object { - [self insertObject:object atIndex:self.count]; -} - -- (void)removeLastObject { - NSUInteger count = self.count; - if (count) { - [self removeObjectAtIndex:count-1]; - } -} - -- (id)objectAtIndexedSubscript:(NSUInteger)index { - return [self objectAtIndex:index]; -} - -- (void)setObject:(id)newValue atIndexedSubscript:(NSUInteger)index { - [self replaceObjectAtIndex:index withObject:newValue]; -} - -- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { - return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]]; -} - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args]; - va_end(args); - return index; -} - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args { - return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat - arguments:args]]; -} - -#pragma mark - Unmanaged RLMArray implementation - -- (RLMRealm *)realm { - return nil; -} - -- (id)firstObject { - if (self.count) { - return [self objectAtIndex:0]; - } - return nil; -} - -- (id)lastObject { - NSUInteger count = self.count; - if (count) { - return [self objectAtIndex:count-1]; - } - return nil; -} - -- (id)objectAtIndex:(NSUInteger)index { - validateArrayBounds(self, index); - return [_backingArray objectAtIndex:index]; -} - -- (NSUInteger)count { - return _backingArray.count; -} - -- (BOOL)isInvalidated { - return NO; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - objects:(__unused __unsafe_unretained id [])buffer - count:(__unused NSUInteger)len { - if (state->state != 0) { - return 0; - } - - // We need to enumerate a copy of the backing array so that it doesn't - // reflect changes made during enumeration. This copy has to be autoreleased - // (since there's nowhere for us to store a strong reference), and uses - // RLMArrayHolder rather than an NSArray because NSArray doesn't guarantee - // that it'll use a single contiguous block of memory, and if it doesn't - // we'd need to forward multiple calls to this method to the same NSArray, - // which would require holding a reference to it somewhere. - __autoreleasing RLMArrayHolder *copy = [[RLMArrayHolder alloc] init]; - copy->items = std::make_unique(self.count); - - NSUInteger i = 0; - for (id object in _backingArray) { - copy->items[i++] = object; - } - - state->itemsPtr = (__unsafe_unretained id *)(void *)copy->items.get(); - // needs to point to something valid, but the whole point of this is so - // that it can't be changed - state->mutationsPtr = state->extra; - state->state = i; - - return i; -} - - -template -static void changeArray(__unsafe_unretained RLMArray *const ar, - NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) { - if (!ar->_backingArray) { - ar->_backingArray = [NSMutableArray new]; - } - - if (RLMObjectBase *parent = ar->_parentObject) { - NSIndexSet *indexes = is(); - [parent willChange:kind valuesAtIndexes:indexes forKey:ar->_key]; - f(); - [parent didChange:kind valuesAtIndexes:indexes forKey:ar->_key]; - } - else { - f(); - } -} - -static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, - NSUInteger index, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; }); -} - -static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, - NSRange range, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; }); -} - -static void changeArray(__unsafe_unretained RLMArray *const ar, NSKeyValueChange kind, - NSIndexSet *is, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return is; }); -} - -void RLMArrayValidateMatchingObjectType(__unsafe_unretained RLMArray *const array, - __unsafe_unretained id const value) { - if (!value && !array->_optional) { - @throw RLMException(@"Invalid nil value for array of '%@'.", - array->_objectClassName ?: RLMTypeToString(array->_type)); - } - if (array->_type != RLMPropertyTypeObject) { - if (!RLMValidateValue(value, array->_type, array->_optional, false, nil)) { - @throw RLMException(@"Invalid value '%@' of type '%@' for expected type '%@%s'.", - value, [value class], RLMTypeToString(array->_type), - array->_optional ? "?" : ""); - } - return; - } - - auto object = RLMDynamicCast(value); - if (!object) { - return; - } - if (!object->_objectSchema) { - @throw RLMException(@"Object cannot be inserted unless the schema is initialized. " - "This can happen if you try to insert objects into a RLMArray / List from a default value or from an overriden unmanaged initializer (`init()`)."); - } - if (![array->_objectClassName isEqualToString:object->_objectSchema.className]) { - @throw RLMException(@"Object of type '%@' does not match RLMArray type '%@'.", - object->_objectSchema.className, array->_objectClassName); - } -} - -static void validateArrayBounds(__unsafe_unretained RLMArray *const ar, - NSUInteger index, bool allowOnePastEnd=false) { - NSUInteger max = ar->_backingArray.count + allowOnePastEnd; - if (index >= max) { - @throw RLMException(@"Index %llu is out of bounds (must be less than %llu).", - (unsigned long long)index, (unsigned long long)max); - } -} - -- (void)addObjectsFromArray:(NSArray *)array { - for (id obj in array) { - RLMArrayValidateMatchingObjectType(self, obj); - } - changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(_backingArray.count, array.count), ^{ - [_backingArray addObjectsFromArray:array]; - }); -} - -- (void)insertObject:(id)anObject atIndex:(NSUInteger)index { - RLMArrayValidateMatchingObjectType(self, anObject); - validateArrayBounds(self, index, true); - changeArray(self, NSKeyValueChangeInsertion, index, ^{ - [_backingArray insertObject:anObject atIndex:index]; - }); -} - -- (void)insertObjects:(id)objects atIndexes:(NSIndexSet *)indexes { - changeArray(self, NSKeyValueChangeInsertion, indexes, ^{ - NSUInteger currentIndex = [indexes firstIndex]; - for (RLMObject *obj in objects) { - RLMArrayValidateMatchingObjectType(self, obj); - [_backingArray insertObject:obj atIndex:currentIndex]; - currentIndex = [indexes indexGreaterThanIndex:currentIndex]; - } - }); -} - -- (void)removeObjectAtIndex:(NSUInteger)index { - validateArrayBounds(self, index); - changeArray(self, NSKeyValueChangeRemoval, index, ^{ - [_backingArray removeObjectAtIndex:index]; - }); -} - -- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes { - changeArray(self, NSKeyValueChangeRemoval, indexes, ^{ - [_backingArray removeObjectsAtIndexes:indexes]; - }); -} - -- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject { - RLMArrayValidateMatchingObjectType(self, anObject); - validateArrayBounds(self, index); - changeArray(self, NSKeyValueChangeReplacement, index, ^{ - [_backingArray replaceObjectAtIndex:index withObject:anObject]; - }); -} - -- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex { - validateArrayBounds(self, sourceIndex); - validateArrayBounds(self, destinationIndex); - id original = _backingArray[sourceIndex]; - - auto start = std::min(sourceIndex, destinationIndex); - auto len = std::max(sourceIndex, destinationIndex) - start + 1; - changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{ - [_backingArray removeObjectAtIndex:sourceIndex]; - [_backingArray insertObject:original atIndex:destinationIndex]; - }); -} - -- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 { - validateArrayBounds(self, index1); - validateArrayBounds(self, index2); - - changeArray(self, NSKeyValueChangeReplacement, ^{ - [_backingArray exchangeObjectAtIndex:index1 withObjectAtIndex:index2]; - }, [=] { - NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1]; - [set addIndex:index2]; - return set; - }); -} - -- (NSUInteger)indexOfObject:(id)object { - RLMArrayValidateMatchingObjectType(self, object); - if (!_backingArray) { - return NSNotFound; - } - if (_type != RLMPropertyTypeObject) { - return [_backingArray indexOfObject:object]; - } - - NSUInteger index = 0; - for (RLMObjectBase *cmp in _backingArray) { - if (RLMObjectBaseAreEqual(object, cmp)) { - return index; - } - index++; - } - return NSNotFound; -} - -- (void)removeAllObjects { - changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, _backingArray.count), ^{ - [_backingArray removeAllObjects]; - }); -} - -- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - RLMResults *results = [self objectsWhere:predicateFormat args:args]; - va_end(args); - return results; -} - -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { - return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; -} - -static bool canAggregate(RLMPropertyType type, bool allowDate) { - switch (type) { - case RLMPropertyTypeInt: - case RLMPropertyTypeFloat: - case RLMPropertyTypeDouble: - return true; - case RLMPropertyTypeDate: - return allowDate; - default: - return false; - } -} - -- (RLMPropertyType)typeForProperty:(NSString *)propertyName { - if ([propertyName isEqualToString:@"self"]) { - return _type; - } - - RLMObjectSchema *objectSchema; - if (_backingArray.count) { - objectSchema = [_backingArray[0] objectSchema]; - } - else { - objectSchema = [RLMSchema.partialPrivateSharedSchema schemaForClassName:_objectClassName]; - } - - return RLMValidatedProperty(objectSchema, propertyName).type; -} - -- (id)aggregateProperty:(NSString *)key operation:(NSString *)op method:(SEL)sel { - // Although delegating to valueForKeyPath: here would allow to support - // nested key paths as well, limiting functionality gives consistency - // between unmanaged and managed arrays. - if ([key rangeOfString:@"."].location != NSNotFound) { - @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators."); - } - - bool allowDate = false; - bool sum = false; - if ([op isEqualToString:@"@min"] || [op isEqualToString:@"@max"]) { - allowDate = true; - } - else if ([op isEqualToString:@"@sum"]) { - sum = true; - } - else if (![op isEqualToString:@"@avg"]) { - // Just delegate to NSArray for all other operators - return [_backingArray valueForKeyPath:[op stringByAppendingPathExtension:key]]; - } - - RLMPropertyType type = [self typeForProperty:key]; - if (!canAggregate(type, allowDate)) { - NSString *method = sel ? NSStringFromSelector(sel) : op; - if (_type == RLMPropertyTypeObject) { - @throw RLMException(@"%@: is not supported for %@ property '%@.%@'", - method, RLMTypeToString(type), _objectClassName, key); - } - else { - @throw RLMException(@"%@ is not supported for %@%s array", - method, RLMTypeToString(_type), _optional ? "?" : ""); - } - } - - NSArray *values = [key isEqualToString:@"self"] ? _backingArray : [_backingArray valueForKey:key]; - if (_optional) { - // Filter out NSNull values to match our behavior on managed arrays - NSIndexSet *nonnull = [values indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger, BOOL *) { - return obj != NSNull.null; - }]; - if (nonnull.count < values.count) { - values = [values objectsAtIndexes:nonnull]; - } - } - id result = [values valueForKeyPath:[op stringByAppendingString:@".self"]]; - return sum && !result ? @0 : result; -} - -- (id)valueForKeyPath:(NSString *)keyPath { - if ([keyPath characterAtIndex:0] != '@') { - return _backingArray ? [_backingArray valueForKeyPath:keyPath] : [super valueForKeyPath:keyPath]; - } - - if (!_backingArray) { - _backingArray = [NSMutableArray new]; - } - - NSUInteger dot = [keyPath rangeOfString:@"."].location; - if (dot == NSNotFound) { - return [_backingArray valueForKeyPath:keyPath]; - } - - NSString *op = [keyPath substringToIndex:dot]; - NSString *key = [keyPath substringFromIndex:dot + 1]; - return [self aggregateProperty:key operation:op method:nil]; -} - -- (id)valueForKey:(NSString *)key { - if ([key isEqualToString:RLMInvalidatedKey]) { - return @NO; // Unmanaged arrays are never invalidated - } - if (!_backingArray) { - _backingArray = [NSMutableArray new]; - } - return [_backingArray valueForKey:key]; -} - -- (void)setValue:(id)value forKey:(NSString *)key { - if ([key isEqualToString:@"self"]) { - RLMArrayValidateMatchingObjectType(self, value); - for (NSUInteger i = 0, count = _backingArray.count; i < count; ++i) { - _backingArray[i] = value; - } - return; - } - else if (_type == RLMPropertyTypeObject) { - [_backingArray setValue:value forKey:key]; - } - else { - [self setValue:value forUndefinedKey:key]; - } -} - -- (id)minOfProperty:(NSString *)property { - return [self aggregateProperty:property operation:@"@min" method:_cmd]; -} - -- (id)maxOfProperty:(NSString *)property { - return [self aggregateProperty:property operation:@"@max" method:_cmd]; -} - -- (id)sumOfProperty:(NSString *)property { - return [self aggregateProperty:property operation:@"@sum" method:_cmd]; -} - -- (id)averageOfProperty:(NSString *)property { - return [self aggregateProperty:property operation:@"@avg" method:_cmd]; -} - -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { - if (!_backingArray) { - return NSNotFound; - } - return [_backingArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger, BOOL *) { - return [predicate evaluateWithObject:obj]; - }]; -} - -- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes { - if (!_backingArray) { - _backingArray = [NSMutableArray new]; - } - return [_backingArray objectsAtIndexes:indexes]; -} - -- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath - options:(NSKeyValueObservingOptions)options context:(void *)context { - RLMValidateArrayObservationKey(keyPath, self); - [super addObserver:observer forKeyPath:keyPath options:options context:context]; -} - -#pragma mark - Methods unsupported on unmanaged RLMArray instances - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" - -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { - @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); -} - -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { - @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); -} - -// The compiler complains about the method's argument type not matching due to -// it not having the generic type attached, but it doesn't seem to be possible -// to actually include the generic type -// http://www.openradar.me/radar?id=6135653276319744 -#pragma clang diagnostic ignored "-Wmismatched-parameter-types" -- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block { - @throw RLMException(@"This method may only be called on RLMArray instances retrieved from an RLMRealm"); -} - -#pragma mark - Thread Confined Protocol Conformance - -- (std::unique_ptr)makeThreadSafeReference { - REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); -} - -- (id)objectiveCMetadata { - REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); -} - -+ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference - metadata:(id)metadata - realm:(RLMRealm *)realm { - REALM_TERMINATE("Unexpected handover of unmanaged `RLMArray`"); -} - -#pragma clang diagnostic pop // unused parameter warning - -#pragma mark - Superclass Overrides - -- (NSString *)description { - return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth]; -} - -- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth { - return RLMDescriptionWithMaxDepth(@"RLMArray", self, depth); -} -@end - -@implementation RLMSortDescriptor - -+ (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { - RLMSortDescriptor *desc = [[RLMSortDescriptor alloc] init]; - desc->_keyPath = keyPath; - desc->_ascending = ascending; - return desc; -} - -- (instancetype)reversedSortDescriptor { - return [self.class sortDescriptorWithKeyPath:_keyPath ascending:!_ascending]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMClassInfo.mm b/Lesson14/Pods/Realm/Realm/RLMClassInfo.mm deleted file mode 100644 index 52b44f8..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMClassInfo.mm +++ /dev/null @@ -1,131 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMClassInfo.hpp" - -#import "RLMRealm_Private.hpp" -#import "RLMObjectSchema_Private.h" -#import "RLMSchema.h" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMUtil.hpp" - -#import "object_schema.hpp" -#import "object_store.hpp" -#import "schema.hpp" -#import "shared_realm.hpp" - -#import - -using namespace realm; - -RLMClassInfo::RLMClassInfo(RLMRealm *realm, RLMObjectSchema *rlmObjectSchema, - const realm::ObjectSchema *objectSchema) -: realm(realm), rlmObjectSchema(rlmObjectSchema), objectSchema(objectSchema) { } - -realm::Table *RLMClassInfo::table() const { - if (!m_table) { - m_table = ObjectStore::table_for_object_type(realm.group, objectSchema->name).get(); - } - return m_table; -} - -RLMProperty *RLMClassInfo::propertyForTableColumn(NSUInteger col) const noexcept { - auto const& props = objectSchema->persisted_properties; - for (size_t i = 0; i < props.size(); ++i) { - if (props[i].table_column == col) { - return rlmObjectSchema.properties[i]; - } - } - return nil; -} - -RLMProperty *RLMClassInfo::propertyForPrimaryKey() const noexcept { - return rlmObjectSchema.primaryKeyProperty; -} - -NSUInteger RLMClassInfo::tableColumn(NSString *propertyName) const { - return tableColumn(RLMValidatedProperty(rlmObjectSchema, propertyName)); -} - -NSUInteger RLMClassInfo::tableColumn(RLMProperty *property) const { - return objectSchema->persisted_properties[property.index].table_column; -} - -RLMClassInfo &RLMClassInfo::linkTargetType(size_t propertyIndex) { - if (propertyIndex < m_linkTargets.size() && m_linkTargets[propertyIndex]) { - return *m_linkTargets[propertyIndex]; - } - if (m_linkTargets.size() <= propertyIndex) { - m_linkTargets.resize(propertyIndex + 1); - } - m_linkTargets[propertyIndex] = &realm->_info[rlmObjectSchema.properties[propertyIndex].objectClassName]; - return *m_linkTargets[propertyIndex]; -} - -RLMClassInfo &RLMClassInfo::linkTargetType(realm::Property const& property) { - REALM_ASSERT(property.type == PropertyType::Object); - return linkTargetType(&property - &objectSchema->persisted_properties[0]); -} - -RLMSchemaInfo::impl::iterator RLMSchemaInfo::begin() noexcept { return m_objects.begin(); } -RLMSchemaInfo::impl::iterator RLMSchemaInfo::end() noexcept { return m_objects.end(); } -RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::begin() const noexcept { return m_objects.begin(); } -RLMSchemaInfo::impl::const_iterator RLMSchemaInfo::end() const noexcept { return m_objects.end(); } - -RLMClassInfo& RLMSchemaInfo::operator[](NSString *name) { - auto it = m_objects.find(name); - if (it == m_objects.end()) { - @throw RLMException(@"Object type '%@' is not managed by the Realm. " - @"If using a custom `objectClasses` / `objectTypes` array in your configuration, " - @"add `%@` to the list of `objectClasses` / `objectTypes`.", - name, name); - } - return *&it->second; -} - -RLMSchemaInfo::RLMSchemaInfo(RLMRealm *realm) { - RLMSchema *rlmSchema = realm.schema; - realm::Schema const& schema = realm->_realm->schema(); - // rlmSchema can be larger due to multiple classes backed by one table - REALM_ASSERT(rlmSchema.objectSchema.count >= schema.size()); - - m_objects.reserve(schema.size()); - for (RLMObjectSchema *rlmObjectSchema in rlmSchema.objectSchema) { - m_objects.emplace(std::piecewise_construct, - std::forward_as_tuple(rlmObjectSchema.className), - std::forward_as_tuple(realm, rlmObjectSchema, - &*schema.find(rlmObjectSchema.objectName.UTF8String))); - } -} - -RLMSchemaInfo RLMSchemaInfo::clone(realm::Schema const& source_schema, - __unsafe_unretained RLMRealm *const target_realm) { - RLMSchemaInfo info; - info.m_objects.reserve(m_objects.size()); - - auto& schema = target_realm->_realm->schema(); - for (auto& pair : m_objects) { - size_t idx = pair.second.objectSchema - &*source_schema.begin(); - info.m_objects.emplace(std::piecewise_construct, - std::forward_as_tuple(pair.first), - std::forward_as_tuple(target_realm, pair.second.rlmObjectSchema, - &*schema.begin() + idx)); - } - return info; -} diff --git a/Lesson14/Pods/Realm/Realm/RLMCollection.mm b/Lesson14/Pods/Realm/Realm/RLMCollection.mm deleted file mode 100644 index b7e68ae..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMCollection.mm +++ /dev/null @@ -1,419 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMCollection_Private.hpp" - -#import "RLMAccessor.hpp" -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObject_Private.hpp" -#import "RLMProperty_Private.h" - -#import "collection_notifications.hpp" -#import "list.hpp" -#import "results.hpp" - -static const int RLMEnumerationBufferSize = 16; - -@implementation RLMFastEnumerator { - // The buffer supplied by fast enumeration does not retain the objects given - // to it, but because we create objects on-demand and don't want them - // autoreleased (a table can have more rows than the device has memory for - // accessor objects) we need a thing to retain them. - id _strongBuffer[RLMEnumerationBufferSize]; - - RLMRealm *_realm; - RLMClassInfo *_info; - - // A pointer to either _snapshot or a Results from the source collection, - // to avoid having to copy the Results when not in a write transaction - realm::Results *_results; - realm::Results _snapshot; - - // A strong reference to the collection being enumerated to ensure it stays - // alive when we're holding a pointer to a member in it - id _collection; -} - -- (instancetype)initWithList:(realm::List&)list - collection:(id)collection - classInfo:(RLMClassInfo&)info -{ - self = [super init]; - if (self) { - _info = &info; - _realm = _info->realm; - if (_realm.inWriteTransaction) { - _snapshot = list.snapshot(); - } - else { - _snapshot = list.as_results(); - _collection = collection; - [_realm registerEnumerator:self]; - } - _results = &_snapshot; - } - return self; -} - -- (instancetype)initWithResults:(realm::Results&)results - collection:(id)collection - classInfo:(RLMClassInfo&)info -{ - self = [super init]; - if (self) { - _info = &info; - _realm = _info->realm; - if (_realm.inWriteTransaction) { - _snapshot = results.snapshot(); - _results = &_snapshot; - } - else { - _results = &results; - _collection = collection; - [_realm registerEnumerator:self]; - } - } - return self; -} - -- (void)dealloc { - if (_collection) { - [_realm unregisterEnumerator:self]; - } -} - -- (void)detach { - _snapshot = _results->snapshot(); - _results = &_snapshot; - _collection = nil; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - count:(NSUInteger)len { - [_realm verifyThread]; - if (!_results->is_valid()) { - @throw RLMException(@"Collection is no longer valid"); - } - // The fast enumeration buffer size is currently a hardcoded number in the - // compiler so this can't actually happen, but just in case it changes in - // the future... - if (len > RLMEnumerationBufferSize) { - len = RLMEnumerationBufferSize; - } - - NSUInteger batchCount = 0, count = state->extra[1]; - - @autoreleasepool { - RLMAccessorContext ctx(*_info); - for (NSUInteger index = state->state; index < count && batchCount < len; ++index) { - _strongBuffer[batchCount] = _results->get(ctx, index); - batchCount++; - } - } - - for (NSUInteger i = batchCount; i < len; ++i) { - _strongBuffer[i] = nil; - } - - if (batchCount == 0) { - // Release our data if we're done, as we're autoreleased and so may - // stick around for a while - if (_collection) { - _collection = nil; - [_realm unregisterEnumerator:self]; - } - _snapshot = {}; - } - - state->itemsPtr = (__unsafe_unretained id *)(void *)_strongBuffer; - state->state += batchCount; - state->mutationsPtr = state->extra+1; - - return batchCount; -} -@end - -NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id collection) { - __autoreleasing RLMFastEnumerator *enumerator; - if (state->state == 0) { - enumerator = collection.fastEnumerator; - state->extra[0] = (long)enumerator; - state->extra[1] = collection.count; - } - else { - enumerator = (__bridge id)(void *)state->extra[0]; - } - - return [enumerator countByEnumeratingWithState:state count:len]; -} - -template -NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, RLMClassInfo& info) { - size_t count = collection.size(); - if (count == 0) { - return @[]; - } - - NSMutableArray *array = [NSMutableArray arrayWithCapacity:count]; - if ([key isEqualToString:@"self"]) { - RLMAccessorContext context(info); - for (size_t i = 0; i < count; ++i) { - [array addObject:collection.get(context, i) ?: NSNull.null]; - } - return array; - } - - if (collection.get_type() != realm::PropertyType::Object) { - RLMAccessorContext context(info); - for (size_t i = 0; i < count; ++i) { - [array addObject:[collection.get(context, i) valueForKey:key] ?: NSNull.null]; - } - return array; - } - - RLMObject *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info); - - // List properties need to be handled specially since we need to create a - // new List each time - if (info.rlmObjectSchema.isSwiftClass) { - auto prop = info.rlmObjectSchema[key]; - if (prop && prop.array && prop.swiftIvar) { - // Grab the actual class for the generic List from an instance of it - // so that we can make instances of the List without creating a new - // object accessor each time - Class cls = [object_getIvar(accessor, prop.swiftIvar) class]; - RLMAccessorContext context(info); - for (size_t i = 0; i < count; ++i) { - RLMListBase *list = [[cls alloc] init]; - list._rlmArray = [[RLMManagedArray alloc] initWithList:realm::List(info.realm->_realm, *info.table(), - info.tableColumn(prop), - collection.get(i).get_index()) - parentInfo:&info - property:prop]; - [array addObject:list]; - } - return array; - } - } - - for (size_t i = 0; i < count; i++) { - accessor->_row = collection.get(i); - RLMInitializeSwiftAccessorGenerics(accessor); - [array addObject:[accessor valueForKey:key] ?: NSNull.null]; - } - return array; -} - -template NSArray *RLMCollectionValueForKey(realm::Results&, NSString *, RLMClassInfo&); -template NSArray *RLMCollectionValueForKey(realm::List&, NSString *, RLMClassInfo&); - -void RLMCollectionSetValueForKey(id collection, NSString *key, id value) { - realm::TableView tv = [collection tableView]; - if (tv.size() == 0) { - return; - } - - RLMClassInfo *info = collection.objectInfo; - RLMObject *accessor = RLMCreateManagedAccessor(info->rlmObjectSchema.accessorClass, info); - for (size_t i = 0; i < tv.size(); i++) { - accessor->_row = tv[i]; - RLMInitializeSwiftAccessorGenerics(accessor); - [accessor setValue:value forKey:key]; - } -} - -NSString *RLMDescriptionWithMaxDepth(NSString *name, - id collection, - NSUInteger depth) { - if (depth == 0) { - return @""; - } - - const NSUInteger maxObjects = 100; - auto str = [NSMutableString stringWithFormat:@"%@<%@> <%p> (\n", name, - [collection objectClassName] ?: RLMTypeToString([collection type]), - (void *)collection]; - size_t index = 0, skipped = 0; - for (id obj in collection) { - NSString *sub; - if ([obj respondsToSelector:@selector(descriptionWithMaxDepth:)]) { - sub = [obj descriptionWithMaxDepth:depth - 1]; - } - else { - sub = [obj description]; - } - - // Indent child objects - NSString *objDescription = [sub stringByReplacingOccurrencesOfString:@"\n" - withString:@"\n\t"]; - [str appendFormat:@"\t[%zu] %@,\n", index++, objDescription]; - if (index >= maxObjects) { - skipped = collection.count - maxObjects; - break; - } - } - - // Remove last comma and newline characters - if (collection.count > 0) { - [str deleteCharactersInRange:NSMakeRange(str.length-2, 2)]; - } - if (skipped) { - [str appendFormat:@"\n\t... %zu objects skipped.", skipped]; - } - [str appendFormat:@"\n)"]; - return str; -} - -std::vector> RLMSortDescriptorsToKeypathArray(NSArray *properties) { - std::vector> keypaths; - keypaths.reserve(properties.count); - for (RLMSortDescriptor *desc in properties) { - if ([desc.keyPath rangeOfString:@"@"].location != NSNotFound) { - @throw RLMException(@"Cannot sort on key path '%@': KVC collection operators are not supported.", desc.keyPath); - } - keypaths.push_back({desc.keyPath.UTF8String, desc.ascending}); - } - return keypaths; -} - -@implementation RLMCancellationToken { - realm::NotificationToken _token; - __unsafe_unretained RLMRealm *_realm; -} -- (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm { - self = [super init]; - if (self) { - _token = std::move(token); - _realm = realm; - } - return self; -} - -- (RLMRealm *)realm { - return _realm; -} - -- (void)suppressNextNotification { - _token.suppress_next(); -} - -- (void)invalidate { - _token = {}; -} - -@end - -@implementation RLMCollectionChange { - realm::CollectionChangeSet _indices; -} - -- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices { - self = [super init]; - if (self) { - _indices = std::move(indices); - } - return self; -} - -static NSArray *toArray(realm::IndexSet const& set) { - NSMutableArray *ret = [NSMutableArray new]; - for (auto index : set.as_indexes()) { - [ret addObject:@(index)]; - } - return ret; -} - -- (NSArray *)insertions { - return toArray(_indices.insertions); -} - -- (NSArray *)deletions { - return toArray(_indices.deletions); -} - -- (NSArray *)modifications { - return toArray(_indices.modifications); -} - -static NSArray *toIndexPathArray(realm::IndexSet const& set, NSUInteger section) { - NSMutableArray *ret = [NSMutableArray new]; - NSUInteger path[2] = {section, 0}; - for (auto index : set.as_indexes()) { - path[1] = index; - [ret addObject:[NSIndexPath indexPathWithIndexes:path length:2]]; - } - return ret; -} - -- (NSArray *)deletionsInSection:(NSUInteger)section { - return toIndexPathArray(_indices.deletions, section); -} - -- (NSArray *)insertionsInSection:(NSUInteger)section { - return toIndexPathArray(_indices.insertions, section); - -} - -- (NSArray *)modificationsInSection:(NSUInteger)section { - return toIndexPathArray(_indices.modifications, section); - -} -@end - -template -RLMNotificationToken *RLMAddNotificationBlock(id objcCollection, - Collection& collection, - void (^block)(id, RLMCollectionChange *, NSError *), - bool suppressInitialChange) { - auto skip = suppressInitialChange ? std::make_shared(true) : nullptr; - auto cb = [=, &collection](realm::CollectionChangeSet const& changes, - std::exception_ptr err) { - if (err) { - try { - rethrow_exception(err); - } - catch (...) { - NSError *error = nil; - RLMRealmTranslateException(&error); - block(nil, nil, error); - return; - } - } - - if (skip && *skip) { - *skip = false; - block(objcCollection, nil, nil); - } - else if (changes.empty()) { - block(objcCollection, nil, nil); - } - else { - block(objcCollection, [[RLMCollectionChange alloc] initWithChanges:changes], nil); - } - }; - - return [[RLMCancellationToken alloc] initWithToken:collection.add_notification_callback(cb) - realm:(RLMRealm *)[objcCollection realm]]; -} - -// Explicitly instantiate the templated function for the two types we'll use it on -template RLMNotificationToken *RLMAddNotificationBlock(id, realm::List&, void (^)(id, RLMCollectionChange *, NSError *), bool); -template RLMNotificationToken *RLMAddNotificationBlock(id, realm::Results&, void (^)(id, RLMCollectionChange *, NSError *), bool); diff --git a/Lesson14/Pods/Realm/Realm/RLMConstants.m b/Lesson14/Pods/Realm/Realm/RLMConstants.m deleted file mode 100644 index b45638f..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMConstants.m +++ /dev/null @@ -1,36 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -RLMNotification const RLMRealmRefreshRequiredNotification = @"RLMRealmRefreshRequiredNotification"; -RLMNotification const RLMRealmDidChangeNotification = @"RLMRealmDidChangeNotification"; - -NSString * const RLMErrorDomain = @"io.realm"; - -NSString * const RLMUnknownSystemErrorDomain = @"io.realm.unknown"; - -NSString * const RLMExceptionName = @"RLMException"; - -NSString * const RLMRealmVersionKey = @"RLMRealmVersion"; - -NSString * const RLMRealmCoreVersionKey = @"RLMRealmCoreVersion"; - -NSString * const RLMInvalidatedKey = @"invalidated"; - -NSString * const RLMBackupRealmConfigurationErrorKey = @"RLMBackupRealmConfiguration"; diff --git a/Lesson14/Pods/Realm/Realm/RLMJSONModels.m b/Lesson14/Pods/Realm/Realm/RLMJSONModels.m deleted file mode 100644 index 8934d38..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMJSONModels.m +++ /dev/null @@ -1,233 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "RLMJSONModels.h" -#import "RLMSyncUtil_Private.h" -#import "RLMSyncUser.h" - -#pragma mark - Constants - -static const NSString *const kRLMSyncAccessTokenKey = @"access_token"; -static const NSString *const kRLMSyncAccountsKey = @"accounts"; -static const NSString *const kRLMSyncErrorCodeKey = @"code"; -static const NSString *const kRLMSyncExpiresKey = @"expires"; -static const NSString *const kRLMSyncErrorHintKey = @"hint"; -static const NSString *const kRLMSyncIdKey = @"id"; -static const NSString *const kRLMSyncKeyKey = @"key"; -static const NSString *const kRLMSyncMetadataKey = @"metadata"; -static const NSString *const kRLMSyncRefreshTokenKey = @"refresh_token"; -static const NSString *const kRLMSyncErrorStatusKey = @"status"; -static const NSString *const kRLMSyncErrorTitleKey = @"title"; -static const NSString *const kRLMSyncTokenDataKey = @"token_data"; -static const NSString *const kRLMSyncUserKey = @"user"; -static const NSString *const kRLMSyncValueKey = @"value"; - -#pragma mark - RLMTokenDataModel - -@interface RLMTokenDataModel () - -@property (nonatomic, readwrite) NSString *identity; -@property (nonatomic, readwrite) NSString *appID; -@property (nonatomic, readwrite) NSString *path; -@property (nonatomic, readwrite) NSTimeInterval expires; -@property (nonatomic, readwrite) BOOL isAdmin; - -@end - -@implementation RLMTokenDataModel - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { - if (self = [super init]) { - self.isAdmin = NO; - RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncIdentityKey, identity); - RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncAppIDKey, appID); - RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncPathKey, path); - RLM_SYNC_PARSE_OPTIONAL_BOOL(jsonDictionary, kRLMSyncIsAdminKey, isAdmin); - RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncExpiresKey, expires); - return self; - } - return nil; -} - -@end - -#pragma mark - RLMTokenModel - -@interface RLMTokenModel () - -@property (nonatomic, readwrite) NSString *token; -@property (nonatomic, nullable, readwrite) NSString *path; -@property (nonatomic, readwrite) RLMTokenDataModel *tokenData; - -@end - -@implementation RLMTokenModel - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { - if (self = [super init]) { - RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncTokenKey, token); - RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncPathKey, path); - RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncTokenDataKey, RLMTokenDataModel, tokenData); - return self; - } - return nil; -} - -@end - -#pragma mark - RLMAuthResponseModel - -@interface RLMAuthResponseModel () - -@property (nonatomic, readwrite) RLMTokenModel *accessToken; -@property (nonatomic, readwrite) RLMTokenModel *refreshToken; -@property (nonatomic, readwrite) NSString *urlPrefix; - -@end - -@implementation RLMAuthResponseModel - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary - requireAccessToken:(BOOL)requireAccessToken - requireRefreshToken:(BOOL)requireRefreshToken { - if (self = [super init]) { - // Get the access token. - if (requireAccessToken) { - RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncAccessTokenKey, RLMTokenModel, accessToken); - } else { - RLM_SYNC_PARSE_OPTIONAL_MODEL(jsonDictionary, kRLMSyncAccessTokenKey, RLMTokenModel, accessToken); - } - // Get the refresh token. - if (requireRefreshToken) { - RLM_SYNC_PARSE_MODEL_OR_ABORT(jsonDictionary, kRLMSyncRefreshTokenKey, RLMTokenModel, refreshToken); - } else { - RLM_SYNC_PARSE_OPTIONAL_MODEL(jsonDictionary, kRLMSyncRefreshTokenKey, RLMTokenModel, refreshToken); - } - self.urlPrefix = jsonDictionary[@"sync_worker"][@"path"]; - return self; - } - return nil; -} - -@end - -#pragma mark - RLMUserInfoResponseModel - -@interface RLMSyncUserAccountInfo () -@property (nonatomic, readwrite) NSString *provider; -@property (nonatomic, readwrite) NSString *providerUserIdentity; -@end - -@implementation RLMSyncUserAccountInfo - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { - if (self = [super init]) { - RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncProviderKey, provider); - RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncProviderIDKey, providerUserIdentity); - return self; - } - return nil; -} - -@end - -@interface RLMUserResponseModel () - -@property (nonatomic, readwrite) NSString *identity; -@property (nonatomic, readwrite) NSArray *accounts; -@property (nonatomic, readwrite) NSDictionary *metadata; -@property (nonatomic, readwrite) BOOL isAdmin; - -@end - -@implementation RLMUserResponseModel - -- (void)parseMetadataFromJSON:(NSDictionary *)jsonDictionary { - NSMutableDictionary *buffer = [NSMutableDictionary dictionary]; - NSArray *metadataArray = jsonDictionary[kRLMSyncMetadataKey]; - if (![metadataArray isKindOfClass:[NSArray class]]) { - self.metadata = @{}; - return; - } - for (NSDictionary *object in metadataArray) { - if (![object isKindOfClass:[NSDictionary class]]) { - continue; - } - NSString *key = object[kRLMSyncKeyKey]; - NSString *value = object[kRLMSyncValueKey]; - if (!key || !value) { - continue; - } - buffer[key] = value; - } - self.metadata = [buffer copy]; -} - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { - if (self = [super init]) { - self.isAdmin = NO; - RLM_SYNC_PARSE_STRING_OR_ABORT(jsonDictionary, kRLMSyncUserIDKey, identity); - RLM_SYNC_PARSE_OPTIONAL_BOOL(jsonDictionary, kRLMSyncIsAdminKey, isAdmin); - RLM_SYNC_PARSE_MODEL_ARRAY_OR_ABORT(jsonDictionary, kRLMSyncAccountsKey, RLMSyncUserAccountInfo, accounts); - [self parseMetadataFromJSON:jsonDictionary]; - return self; - } - return nil; -} - -@end - -#pragma mark - RLMSyncErrorResponseModel - -@interface RLMSyncErrorResponseModel () - -@property (nonatomic, readwrite) NSInteger status; -@property (nonatomic, readwrite) NSInteger code; -@property (nonatomic, readwrite) NSString *title; -@property (nonatomic, readwrite) NSString *hint; - -@end - -@implementation RLMSyncErrorResponseModel - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary { - if (self = [super init]) { - RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncErrorStatusKey, status); - RLM_SYNC_PARSE_DOUBLE_OR_ABORT(jsonDictionary, kRLMSyncErrorCodeKey, code); - RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncErrorTitleKey, title); - RLM_SYNC_PARSE_OPTIONAL_STRING(jsonDictionary, kRLMSyncErrorHintKey, hint); - - NSString *detail = jsonDictionary[@"detail"]; - if ([detail isKindOfClass:[NSString class]]) { - _title = detail; - } - - for (NSDictionary *problem in jsonDictionary[@"invalid_params"]) { - NSString *name = problem[@"name"]; - NSString *reason = problem[@"reason"]; - if (name && reason) { - _title = [NSString stringWithFormat:@"%@ %@: %@;", _title, name, reason]; - } - } - - return self; - } - return nil; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMListBase.mm b/Lesson14/Pods/Realm/Realm/RLMListBase.mm deleted file mode 100644 index bcc8169..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMListBase.mm +++ /dev/null @@ -1,135 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMListBase.h" - -#import "RLMArray_Private.hpp" -#import "RLMObjectSchema_Private.h" -#import "RLMObject_Private.hpp" -#import "RLMObservation.hpp" -#import "RLMProperty_Private.h" -#import "RLMRealm_Private.hpp" - -@interface RLMArray (KVO) -- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes; -@end - -@implementation RLMListBase { - std::unique_ptr _observationInfo; -} - -+ (RLMArray *)_unmanagedArray { - return nil; -} - -- (instancetype)init { - return self = [super init]; -} - -- (instancetype)initWithArray:(RLMArray *)array { - self = [super init]; - if (self) { - __rlmArray = array; - } - return self; -} - -- (RLMArray *)_rlmArray { - if (!__rlmArray) { - __rlmArray = self.class._unmanagedArray; - } - return __rlmArray; -} - -- (id)valueForKey:(NSString *)key { - return [self._rlmArray valueForKey:key]; -} - -- (id)valueForKeyPath:(NSString *)keyPath { - return [self._rlmArray valueForKeyPath:keyPath]; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - objects:(id __unsafe_unretained [])buffer - count:(NSUInteger)len { - return [self._rlmArray countByEnumeratingWithState:state objects:buffer count:len]; -} - -- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes { - return [self._rlmArray objectsAtIndexes:indexes]; -} - -- (void)addObserver:(id)observer - forKeyPath:(NSString *)keyPath - options:(NSKeyValueObservingOptions)options - context:(void *)context { - RLMEnsureArrayObservationInfo(_observationInfo, keyPath, self._rlmArray, self); - [super addObserver:observer forKeyPath:keyPath options:options context:context]; -} - -@end - -@implementation RLMLinkingObjectsHandle { - realm::Row _row; - RLMClassInfo *_info; - RLMRealm *_realm; - RLMProperty *_property; - - RLMResults *_results; -} - -- (instancetype)initWithObject:(RLMObjectBase *)object property:(RLMProperty *)prop { - if (!(self = [super init])) { - return nil; - } - - _row = object->_row; - _info = object->_info; - _realm = object->_realm; - _property = prop; - - return self; -} - -- (RLMResults *)results { - if (_results) { - return _results; - } - if (!_row.is_attached()) { - @throw RLMException(@"Object has been deleted or invalidated."); - } - [_realm verifyThread]; - - auto& objectInfo = _realm->_info[_property.objectClassName]; - auto& linkOrigin = _info->objectSchema->computed_properties[_property.index].link_origin_property_name; - auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin); - auto backlinkView = _row.get_table()->get_backlink_view(_row.get_index(), - objectInfo.table(), - linkingProperty->table_column); - realm::Results results(_realm->_realm, std::move(backlinkView)); - _results = [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)]; - _realm = nil; - return _results; -} - -- (RLMObjectBase *)parent { - RLMObjectBase *obj = RLMCreateManagedAccessor(_info->rlmObjectSchema.accessorClass, _info); - obj->_row = _row; - return obj; -} -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMManagedArray.mm b/Lesson14/Pods/Realm/Realm/RLMManagedArray.mm deleted file mode 100644 index 0b9e393..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMManagedArray.mm +++ /dev/null @@ -1,542 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMArray_Private.hpp" - -#import "RLMAccessor.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObject_Private.hpp" -#import "RLMObservation.hpp" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMSchema.h" -#import "RLMThreadSafeReference_Private.hpp" -#import "RLMUtil.hpp" - -#import "list.hpp" -#import "results.hpp" -#import "shared_realm.hpp" - -#import -#import - -@interface RLMManagedArrayHandoverMetadata : NSObject -@property (nonatomic) NSString *parentClassName; -@property (nonatomic) NSString *key; -@end - -@implementation RLMManagedArrayHandoverMetadata -@end - -@interface RLMManagedArray () -@end - -// -// RLMArray implementation -// -@implementation RLMManagedArray { -@public - realm::List _backingList; - RLMRealm *_realm; - RLMClassInfo *_objectInfo; - RLMClassInfo *_ownerInfo; - std::unique_ptr _observationInfo; -} - -- (RLMManagedArray *)initWithList:(realm::List)list - parentInfo:(RLMClassInfo *)parentInfo - property:(__unsafe_unretained RLMProperty *const)property { - if (property.type == RLMPropertyTypeObject) - self = [self initWithObjectClassName:property.objectClassName]; - else - self = [self initWithObjectType:property.type optional:property.optional]; - if (self) { - _realm = parentInfo->realm; - REALM_ASSERT(list.get_realm() == _realm->_realm); - _backingList = std::move(list); - _ownerInfo = parentInfo; - if (property.type == RLMPropertyTypeObject) - _objectInfo = &parentInfo->linkTargetType(property.index); - else - _objectInfo = _ownerInfo; - _key = property.name; - } - return self; -} - -- (RLMManagedArray *)initWithParent:(__unsafe_unretained RLMObjectBase *const)parentObject - property:(__unsafe_unretained RLMProperty *const)property { - __unsafe_unretained RLMRealm *const realm = parentObject->_realm; - auto col = parentObject->_info->tableColumn(property); - auto& row = parentObject->_row; - return [self initWithList:realm::List(realm->_realm, *row.get_table(), col, row.get_index()) - parentInfo:parentObject->_info - property:property]; -} - -void RLMValidateArrayObservationKey(__unsafe_unretained NSString *const keyPath, - __unsafe_unretained RLMArray *const array) { - if (![keyPath isEqualToString:RLMInvalidatedKey]) { - @throw RLMException(@"[<%@ %p> addObserver:forKeyPath:options:context:] is not supported. Key path: %@", - [array class], array, keyPath); - } -} - -void RLMEnsureArrayObservationInfo(std::unique_ptr& info, - __unsafe_unretained NSString *const keyPath, - __unsafe_unretained RLMArray *const array, - __unsafe_unretained id const observed) { - RLMValidateArrayObservationKey(keyPath, array); - if (!info && array.class == [RLMManagedArray class]) { - auto lv = static_cast(array); - info = std::make_unique(*lv->_ownerInfo, - lv->_backingList.get_origin_row_index(), - observed); - } -} - -// -// validation helpers -// -[[gnu::noinline]] -[[noreturn]] -static void throwError(__unsafe_unretained RLMManagedArray *const ar, NSString *aggregateMethod) { - try { - throw; - } - catch (realm::InvalidTransactionException const&) { - @throw RLMException(@"Cannot modify managed RLMArray outside of a write transaction."); - } - catch (realm::IncorrectThreadException const&) { - @throw RLMException(@"Realm accessed from incorrect thread."); - } - catch (realm::List::InvalidatedException const&) { - @throw RLMException(@"RLMArray has been invalidated or the containing object has been deleted."); - } - catch (realm::List::OutOfBoundsIndexException const& e) { - @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).", - e.requested, e.valid_count); - } - catch (realm::Results::UnsupportedColumnTypeException const& e) { - if (ar->_backingList.get_type() == realm::PropertyType::Object) { - @throw RLMException(@"%@: is not supported for %s%s property '%s'.", - aggregateMethod, - string_for_property_type(e.property_type), - is_nullable(e.property_type) ? "?" : "", - e.column_name.data()); - } - @throw RLMException(@"%@: is not supported for %s%s array '%@.%@'.", - aggregateMethod, - string_for_property_type(e.property_type), - is_nullable(e.property_type) ? "?" : "", - ar->_ownerInfo->rlmObjectSchema.className, ar->_key); - } - catch (std::logic_error const& e) { - @throw RLMException(e); - } -} - -template -static auto translateErrors(__unsafe_unretained RLMManagedArray *const ar, - Function&& f, NSString *aggregateMethod=nil) { - try { - return f(); - } - catch (...) { - throwError(ar, aggregateMethod); - } -} - -template -static auto translateErrors(Function&& f) { - try { - return f(); - } - catch (...) { - throwError(nil, nil); - } -} - -template -static void changeArray(__unsafe_unretained RLMManagedArray *const ar, - NSKeyValueChange kind, dispatch_block_t f, IndexSetFactory&& is) { - translateErrors([&] { ar->_backingList.verify_in_transaction(); }); - RLMObservationInfo *info = RLMGetObservationInfo(ar->_observationInfo.get(), - ar->_backingList.get_origin_row_index(), - *ar->_ownerInfo); - if (info) { - NSIndexSet *indexes = is(); - info->willChange(ar->_key, kind, indexes); - try { - f(); - } - catch (...) { - info->didChange(ar->_key, kind, indexes); - throwError(ar, nil); - } - info->didChange(ar->_key, kind, indexes); - } - else { - translateErrors([&] { f(); }); - } -} - -static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSUInteger index, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndex:index]; }); -} - -static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSRange range, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return [NSIndexSet indexSetWithIndexesInRange:range]; }); -} - -static void changeArray(__unsafe_unretained RLMManagedArray *const ar, NSKeyValueChange kind, NSIndexSet *is, dispatch_block_t f) { - changeArray(ar, kind, f, [=] { return is; }); -} - -// -// public method implementations -// -- (RLMRealm *)realm { - return _realm; -} - -- (NSUInteger)count { - return translateErrors([&] { return _backingList.size(); }); -} - -- (BOOL)isInvalidated { - return translateErrors([&] { return !_backingList.is_valid(); }); -} - -- (RLMClassInfo *)objectInfo { - return _objectInfo; -} - - -- (bool)isBackedByList:(realm::List const&)list { - return _backingList == list; -} - -- (BOOL)isEqual:(id)object { - return [object respondsToSelector:@selector(isBackedByList:)] && [object isBackedByList:_backingList]; -} - -- (NSUInteger)hash { - return std::hash()(_backingList); -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - objects:(__unused __unsafe_unretained id [])buffer - count:(NSUInteger)len { - return RLMFastEnumerate(state, len, self); -} - -- (id)objectAtIndex:(NSUInteger)index { - return translateErrors([&] { - RLMAccessorContext context(*_objectInfo); - return _backingList.get(context, index); - }); -} - -static void RLMInsertObject(RLMManagedArray *ar, id object, NSUInteger index) { - RLMArrayValidateMatchingObjectType(ar, object); - if (index == NSUIntegerMax) { - index = translateErrors([&] { return ar->_backingList.size(); }); - } - - changeArray(ar, NSKeyValueChangeInsertion, index, ^{ - RLMAccessorContext context(*ar->_objectInfo); - ar->_backingList.insert(context, index, object); - }); -} - -- (void)addObject:(id)object { - RLMInsertObject(self, object, NSUIntegerMax); -} - -- (void)insertObject:(id)object atIndex:(NSUInteger)index { - RLMInsertObject(self, object, index); -} - -- (void)insertObjects:(id)objects atIndexes:(NSIndexSet *)indexes { - changeArray(self, NSKeyValueChangeInsertion, indexes, ^{ - NSUInteger index = [indexes firstIndex]; - RLMAccessorContext context(*_objectInfo); - for (id obj in objects) { - RLMArrayValidateMatchingObjectType(self, obj); - _backingList.insert(context, index, obj); - index = [indexes indexGreaterThanIndex:index]; - } - }); -} - - -- (void)removeObjectAtIndex:(NSUInteger)index { - changeArray(self, NSKeyValueChangeRemoval, index, ^{ - _backingList.remove(index); - }); -} - -- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes { - changeArray(self, NSKeyValueChangeRemoval, indexes, ^{ - [indexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL *) { - _backingList.remove(idx); - }]; - }); -} - -- (void)addObjectsFromArray:(NSArray *)array { - changeArray(self, NSKeyValueChangeInsertion, NSMakeRange(self.count, array.count), ^{ - RLMAccessorContext context(*_objectInfo); - for (id obj in array) { - RLMArrayValidateMatchingObjectType(self, obj); - _backingList.add(context, obj); - } - }); -} - -- (void)removeAllObjects { - changeArray(self, NSKeyValueChangeRemoval, NSMakeRange(0, self.count), ^{ - _backingList.remove_all(); - }); -} - -- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { - RLMArrayValidateMatchingObjectType(self, object); - changeArray(self, NSKeyValueChangeReplacement, index, ^{ - RLMAccessorContext context(*_objectInfo); - _backingList.set(context, index, object); - }); -} - -- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex { - auto start = std::min(sourceIndex, destinationIndex); - auto len = std::max(sourceIndex, destinationIndex) - start + 1; - changeArray(self, NSKeyValueChangeReplacement, {start, len}, ^{ - _backingList.move(sourceIndex, destinationIndex); - }); -} - -- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 { - changeArray(self, NSKeyValueChangeReplacement, ^{ - _backingList.swap(index1, index2); - }, [=] { - NSMutableIndexSet *set = [[NSMutableIndexSet alloc] initWithIndex:index1]; - [set addIndex:index2]; - return set; - }); -} - -- (NSUInteger)indexOfObject:(id)object { - RLMArrayValidateMatchingObjectType(self, object); - return translateErrors([&] { - RLMAccessorContext context(*_objectInfo); - return RLMConvertNotFound(_backingList.find(context, object)); - }); -} - -- (id)valueForKeyPath:(NSString *)keyPath { - if ([keyPath hasPrefix:@"@"]) { - // Delegate KVC collection operators to RLMResults - return translateErrors([&] { - auto results = [RLMResults resultsWithObjectInfo:*_objectInfo results:_backingList.as_results()]; - return [results valueForKeyPath:keyPath]; - }); - } - return [super valueForKeyPath:keyPath]; -} - -- (id)valueForKey:(NSString *)key { - // Ideally we'd use "@invalidated" for this so that "invalidated" would use - // normal array KVC semantics, but observing @things works very oddly (when - // it's part of a key path, it's triggered automatically when array index - // changes occur, and can't be sent explicitly, but works normally when it's - // the entire key path), and an RLMManagedArray *can't* have objects where - // invalidated is true, so we're not losing much. - return translateErrors([&]() -> id { - if ([key isEqualToString:RLMInvalidatedKey]) { - return @(!_backingList.is_valid()); - } - - _backingList.verify_attached(); - return RLMCollectionValueForKey(_backingList, key, *_objectInfo); - }); -} - -- (void)setValue:(id)value forKey:(NSString *)key { - if ([key isEqualToString:@"self"]) { - RLMArrayValidateMatchingObjectType(self, value); - RLMAccessorContext context(*_objectInfo); - translateErrors([&] { - for (size_t i = 0, count = _backingList.size(); i < count; ++i) { - _backingList.set(context, i, value); - } - }); - return; - } - else if (_type == RLMPropertyTypeObject) { - RLMArrayValidateMatchingObjectType(self, value); - translateErrors([&] { _backingList.verify_in_transaction(); }); - RLMCollectionSetValueForKey(self, key, value); - } - else { - [self setValue:value forUndefinedKey:key]; - } -} - -- (size_t)columnForProperty:(NSString *)propertyName { - if (_backingList.get_type() == realm::PropertyType::Object) { - return _objectInfo->tableColumn(propertyName); - } - if (![propertyName isEqualToString:@"self"]) { - @throw RLMException(@"Arrays of '%@' can only be aggregated on \"self\"", RLMTypeToString(_type)); - } - return 0; -} - -- (id)minOfProperty:(NSString *)property { - size_t column = [self columnForProperty:property]; - auto value = translateErrors(self, [&] { return _backingList.min(column); }, @"minOfProperty"); - return value ? RLMMixedToObjc(*value) : nil; -} - -- (id)maxOfProperty:(NSString *)property { - size_t column = [self columnForProperty:property]; - auto value = translateErrors(self, [&] { return _backingList.max(column); }, @"maxOfProperty"); - return value ? RLMMixedToObjc(*value) : nil; -} - -- (id)sumOfProperty:(NSString *)property { - size_t column = [self columnForProperty:property]; - return RLMMixedToObjc(translateErrors(self, [&] { return _backingList.sum(column); }, @"sumOfProperty")); -} - -- (id)averageOfProperty:(NSString *)property { - size_t column = [self columnForProperty:property]; - auto value = translateErrors(self, [&] { return _backingList.average(column); }, @"averageOfProperty"); - return value ? @(*value) : nil; -} - -- (void)deleteObjectsFromRealm { - if (_type != RLMPropertyTypeObject) { - @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.", RLMTypeToString(_type)); - } - // delete all target rows from the realm - RLMTrackDeletions(_realm, ^{ - translateErrors([&] { _backingList.delete_all(); }); - }); -} - -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { - return translateErrors([&] { - return [RLMResults resultsWithObjectInfo:*_objectInfo - results:_backingList.sort(RLMSortDescriptorsToKeypathArray(properties))]; - }); -} - -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { - if (_type != RLMPropertyTypeObject) { - @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); - } - auto query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema, _realm.schema, _realm.group); - auto results = translateErrors([&] { return _backingList.filter(std::move(query)); }); - return [RLMResults resultsWithObjectInfo:*_objectInfo results:std::move(results)]; -} - -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { - if (_type != RLMPropertyTypeObject) { - @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); - } - realm::Query query = RLMPredicateToQuery(predicate, _objectInfo->rlmObjectSchema, - _realm.schema, _realm.group); - - return translateErrors([&] { - return RLMConvertNotFound(_backingList.find(std::move(query))); - }); -} - -- (NSArray *)objectsAtIndexes:(__unused NSIndexSet *)indexes { - // FIXME: this is called by KVO when array changes are made. It's not clear - // why, and returning nil seems to work fine. - return nil; -} - -- (void)addObserver:(id)observer - forKeyPath:(NSString *)keyPath - options:(NSKeyValueObservingOptions)options - context:(void *)context { - RLMEnsureArrayObservationInfo(_observationInfo, keyPath, self, self); - [super addObserver:observer forKeyPath:keyPath options:options context:context]; -} - -- (realm::TableView)tableView { - return translateErrors([&] { return _backingList.get_query(); }).find_all(); -} - -- (RLMFastEnumerator *)fastEnumerator { - return translateErrors([&] { - return [[RLMFastEnumerator alloc] initWithList:_backingList collection:self - classInfo:*_objectInfo]; - }); -} - -// The compiler complains about the method's argument type not matching due to -// it not having the generic type attached, but it doesn't seem to be possible -// to actually include the generic type -// http://www.openradar.me/radar?id=6135653276319744 -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wmismatched-parameter-types" -- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *, RLMCollectionChange *, NSError *))block { - [_realm verifyNotificationsAreSupported:true]; - return RLMAddNotificationBlock(self, _backingList, block); -} -#pragma clang diagnostic pop - -#pragma mark - Thread Confined Protocol Conformance - -- (std::unique_ptr)makeThreadSafeReference { - auto list_reference = _realm->_realm->obtain_thread_safe_reference(_backingList); - return std::make_unique>(std::move(list_reference)); -} - -- (RLMManagedArrayHandoverMetadata *)objectiveCMetadata { - RLMManagedArrayHandoverMetadata *metadata = [[RLMManagedArrayHandoverMetadata alloc] init]; - metadata.parentClassName = _ownerInfo->rlmObjectSchema.className; - metadata.key = _key; - return metadata; -} - -+ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference - metadata:(RLMManagedArrayHandoverMetadata *)metadata - realm:(RLMRealm *)realm { - REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); - auto list_reference = static_cast *>(reference.get()); - - auto list = realm->_realm->resolve_thread_safe_reference(std::move(*list_reference)); - if (!list.is_valid()) { - return nil; - } - RLMClassInfo *parentInfo = &realm->_info[metadata.parentClassName]; - return [[RLMManagedArray alloc] initWithList:std::move(list) - parentInfo:parentInfo - property:parentInfo->rlmObjectSchema[metadata.key]]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMMigration.mm b/Lesson14/Pods/Realm/Realm/RLMMigration.mm deleted file mode 100644 index 6c0c571..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMMigration.mm +++ /dev/null @@ -1,192 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMMigration_Private.h" - -#import "RLMAccessor.h" -#import "RLMObject_Private.h" -#import "RLMObject_Private.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMProperty_Private.h" -#import "RLMRealm_Dynamic.h" -#import "RLMRealm_Private.hpp" -#import "RLMResults_Private.hpp" -#import "RLMSchema_Private.hpp" -#import "RLMUtil.hpp" - -#import "object_store.hpp" -#import "shared_realm.hpp" -#import "schema.hpp" - -#import - -using namespace realm; - -// The source realm for a migration has to use a SharedGroup to be able to share -// the file with the destination realm, but we don't want to let the user call -// beginWriteTransaction on it as that would make no sense. -@interface RLMMigrationRealm : RLMRealm -@end - -@implementation RLMMigrationRealm -- (BOOL)readonly { - return YES; -} - -- (void)beginWriteTransaction { - @throw RLMException(@"Cannot modify the source Realm in a migration"); -} -@end - -@implementation RLMMigration { - realm::Schema *_schema; - std::unordered_map _deletedObjectIndices; -} - -- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm schema:(realm::Schema &)schema { - self = [super init]; - if (self) { - _realm = realm; - _oldRealm = oldRealm; - _schema = &schema; - object_setClass(_oldRealm, RLMMigrationRealm.class); - } - return self; -} - -- (RLMSchema *)oldSchema { - return self.oldRealm.schema; -} - -- (RLMSchema *)newSchema { - return self.realm.schema; -} - -- (void)enumerateObjects:(NSString *)className block:(__attribute__((noescape)) RLMObjectMigrationBlock)block { - RLMResults *objects = [_realm.schema schemaForClassName:className] ? [_realm allObjects:className] : nil; - RLMResults *oldObjects = [_oldRealm.schema schemaForClassName:className] ? [_oldRealm allObjects:className] : nil; - - // For whatever reason if this is a newly added table we enumerate the - // objects in it, while in all other cases we enumerate only the existing - // objects. It's unclear how this could be useful, but changing it would - // also be a pointless breaking change and it's unlikely to be hurting anyone. - if (objects && !oldObjects) { - for (auto i = objects.count; i > 0; --i) { - @autoreleasepool { - block(nil, objects[i - 1]); - } - } - return; - } - - auto count = oldObjects.count; - if (count == 0) { - return; - } - auto deletedObjects = _deletedObjectIndices.find(className); - for (auto i = count; i > 0; --i) { - auto index = i - 1; - if (deletedObjects != _deletedObjectIndices.end() && deletedObjects->second.contains(index)) { - continue; - } - @autoreleasepool { - block(oldObjects[index], objects[index]); - } - } -} - -- (void)execute:(RLMMigrationBlock)block { - @autoreleasepool { - // disable all primary keys for migration and use DynamicObject for all types - for (RLMObjectSchema *objectSchema in _realm.schema.objectSchema) { - objectSchema.accessorClass = RLMDynamicObject.class; - objectSchema.primaryKeyProperty.isPrimary = NO; - } - for (RLMObjectSchema *objectSchema in _oldRealm.schema.objectSchema) { - objectSchema.accessorClass = RLMDynamicObject.class; - } - - block(self, _oldRealm->_realm->schema_version()); - - [self deleteObjectsMarkedForDeletion]; - - _oldRealm = nil; - _realm = nil; - } -} - -- (RLMObject *)createObject:(NSString *)className withValue:(id)value { - return [_realm createObject:className withValue:value]; -} - -- (RLMObject *)createObject:(NSString *)className withObject:(id)object { - return [self createObject:className withValue:object]; -} - -- (void)deleteObject:(RLMObject *)object { - _deletedObjectIndices[object.objectSchema.className].add(object->_row.get_index()); -} - -- (void)deleteObjectsMarkedForDeletion { - for (auto& objectType : _deletedObjectIndices) { - TableRef table = ObjectStore::table_for_object_type(_realm.group, objectType.first.UTF8String); - if (!table) { - continue; - } - - auto& indices = objectType.second; - // Just clear the table if we're removing all of the rows - if (table->size() == indices.count()) { - table->clear(); - } - // Otherwise delete in reverse order to avoid invaliding any of the - // not-yet-deleted indices - else { - for (auto it = std::make_reverse_iterator(indices.end()), end = std::make_reverse_iterator(indices.begin()); it != end; ++it) { - for (size_t i = it->second; i > it->first; --i) { - table->move_last_over(i - 1); - } - } - } - } -} - -- (BOOL)deleteDataForClassName:(NSString *)name { - if (!name) { - return false; - } - - TableRef table = ObjectStore::table_for_object_type(_realm.group, name.UTF8String); - if (!table) { - return false; - } - _deletedObjectIndices[name].set(table->size()); - if (![_realm.schema schemaForClassName:name]) { - realm::ObjectStore::delete_data_for_object(_realm.group, name.UTF8String); - } - - return true; -} - -- (void)renamePropertyForClass:(NSString *)className oldName:(NSString *)oldName newName:(NSString *)newName { - realm::ObjectStore::rename_property(_realm.group, *_schema, className.UTF8String, - oldName.UTF8String, newName.UTF8String); -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMNetworkClient.mm b/Lesson14/Pods/Realm/Realm/RLMNetworkClient.mm deleted file mode 100644 index 009795e..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMNetworkClient.mm +++ /dev/null @@ -1,449 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMNetworkClient.h" - -#import "RLMRealmConfiguration.h" -#import "RLMJSONModels.h" -#import "RLMSyncUtil_Private.hpp" -#import "RLMSyncManager_Private.h" -#import "RLMUtil.hpp" - -#import - -typedef void(^RLMServerURLSessionCompletionBlock)(NSData *, NSURLResponse *, NSError *); - -static NSUInteger const kHTTPCodeRange = 100; - -typedef enum : NSUInteger { - Informational = 1, // 1XX - Success = 2, // 2XX - Redirection = 3, // 3XX - ClientError = 4, // 4XX - ServerError = 5, // 5XX -} RLMServerHTTPErrorCodeType; - -static NSRange rangeForErrorType(RLMServerHTTPErrorCodeType type) { - return NSMakeRange(type*100, kHTTPCodeRange); -} - -#pragma mark Network client - -@interface RLMSessionDelegate : NSObject -+ (instancetype)delegateWithCertificatePaths:(NSDictionary *)paths - completion:(void (^)(NSError *, NSDictionary *))completion; -@end - -@interface RLMSyncServerEndpoint () -/// The HTTP method the endpoint expects. Defaults to POST. -+ (NSString *)httpMethod; - -/// The URL to which the request should be made. Must be implemented. -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json; - -/// The body for the request, if any. -+ (NSData *)httpBodyForPayload:(NSDictionary *)json error:(NSError **)error; - -/// The HTTP headers to be added to the request, if any. -+ (NSDictionary *)httpHeadersForPayload:(NSDictionary *)json - options:(nullable RLMNetworkRequestOptions *)options; -@end - -@implementation RLMSyncServerEndpoint - -+ (void)sendRequestToServer:(NSURL *)serverURL - JSON:(NSDictionary *)jsonDictionary - completion:(void (^)(NSError *))completionBlock { - [self sendRequestToServer:serverURL JSON:jsonDictionary timeout:0 - completion:^(NSError *error, NSDictionary *) { - completionBlock(error); - }]; -} -+ (void)sendRequestToServer:(NSURL *)serverURL - JSON:(NSDictionary *)jsonDictionary - timeout:(NSTimeInterval)timeout - completion:(void (^)(NSError *, NSDictionary *))completionBlock { - // If the timeout isn't set then use the timeout set on the sync manager, - // or 60 seconds if it isn't set there either. - RLMSyncManager *syncManager = RLMSyncManager.sharedManager; - if (timeout < 1) - timeout = syncManager.timeoutOptions.connectTimeout / 1000.0; - if (timeout < 1) - timeout = 60.0; - - // Create the request - NSError *localError = nil; - NSURL *requestURL = [self urlForAuthServer:serverURL payload:jsonDictionary]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL]; - request.HTTPMethod = [self httpMethod]; - if (![request.HTTPMethod isEqualToString:@"GET"]) { - request.HTTPBody = [self httpBodyForPayload:jsonDictionary error:&localError]; - if (localError) { - completionBlock(localError, nil); - return; - } - } - request.timeoutInterval = timeout; - RLMNetworkRequestOptions *options = syncManager.networkRequestOptions; - NSDictionary *headers = [self httpHeadersForPayload:jsonDictionary options:options]; - for (NSString *key in headers) { - [request addValue:headers[key] forHTTPHeaderField:key]; - } - id delegate = [RLMSessionDelegate delegateWithCertificatePaths:options.pinnedCertificatePaths - completion:completionBlock]; - auto session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration - delegate:delegate delegateQueue:nil]; - - // Add the request to a task and start it - [[session dataTaskWithRequest:request] resume]; - // Tell the session to destroy itself once it's done with the request - [session finishTasksAndInvalidate]; -} - -+ (NSString *)httpMethod { - return @"POST"; -} - -+ (NSURL *)urlForAuthServer:(__unused NSURL *)authServerURL payload:(__unused NSDictionary *)json { - NSAssert(NO, @"This method must be overriden by concrete subclasses."); - return nil; -} - -+ (NSData *)httpBodyForPayload:(NSDictionary *)json error:(NSError **)error { - NSError *localError = nil; - NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json - options:(NSJSONWritingOptions)0 - error:&localError]; - if (jsonData && !localError) { - return jsonData; - } - NSAssert(localError, @"If there isn't a converted data object there must be an error."); - if (error) { - *error = localError; - } - return nil; -} - -+ (NSDictionary *)httpHeadersForPayload:(NSDictionary *)json - options:(nullable RLMNetworkRequestOptions *)options { - NSMutableDictionary *headers = [[NSMutableDictionary alloc] init]; - headers[@"Content-Type"] = @"application/json;charset=utf-8"; - headers[@"Accept"] = @"application/json"; - - if (NSDictionary *customHeaders = options.customHeaders) { - [headers addEntriesFromDictionary:customHeaders]; - } - if (NSString *authToken = [json objectForKey:kRLMSyncTokenKey]) { - headers[options.authorizationHeaderName ?: @"Authorization"] = authToken; - } - - return headers; -} -@end - -@implementation RLMSessionDelegate { - NSDictionary *_certificatePaths; - NSData *_data; - void (^_completionBlock)(NSError *, NSDictionary *); -} - -+ (instancetype)delegateWithCertificatePaths:(NSDictionary *)paths - completion:(void (^)(NSError *, NSDictionary *))completion { - RLMSessionDelegate *delegate = [RLMSessionDelegate new]; - delegate->_certificatePaths = paths; - delegate->_completionBlock = completion; - return delegate; -} - -- (void)URLSession:(__unused NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { - auto protectionSpace = challenge.protectionSpace; - - // Just fall back to the default logic for HTTP basic auth - if (protectionSpace.authenticationMethod != NSURLAuthenticationMethodServerTrust || !protectionSpace.serverTrust) { - completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); - return; - } - - // If we have a pinned certificate for this hostname, we want to validate - // against that, and otherwise just do the default thing - auto certPath = _certificatePaths[protectionSpace.host]; - if (!certPath) { - completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); - return; - } - if ([certPath isKindOfClass:[NSString class]]) { - certPath = [NSURL fileURLWithPath:(id)certPath]; - } - - - // Reject the server auth and report an error if any errors occur along the way - CFArrayRef items = nil; - NSError *error; - auto reportStatus = realm::util::make_scope_exit([&]() noexcept { - if (items) { - CFRelease(items); - } - if (error) { - _completionBlock(error, nil); - // Don't also report errors about the connection itself failing later - _completionBlock = ^(NSError *, id) { }; - completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); - } - }); - - NSData *data = [NSData dataWithContentsOfURL:certPath options:0 error:&error]; - if (!data) { - return; - } - - // Load our pinned certificate and add it to the anchor set -#if TARGET_OS_IPHONE - id certificate = (__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data); - if (!certificate) { - error = [NSError errorWithDomain:NSOSStatusErrorDomain code:errSecUnknownFormat userInfo:nil]; - return; - } - items = (CFArrayRef)CFBridgingRetain(@[certificate]); -#else - SecItemImportExportKeyParameters params{ - .version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION - }; - if (OSStatus status = SecItemImport((__bridge CFDataRef)data, (__bridge CFStringRef)certPath.absoluteString, - nullptr, nullptr, 0, ¶ms, nullptr, &items)) { - error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; - return; - } -#endif - SecTrustRef serverTrust = protectionSpace.serverTrust; - if (OSStatus status = SecTrustSetAnchorCertificates(serverTrust, items)) { - error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; - return; - } - - // Only use our certificate and not the ones from the default CA roots - if (OSStatus status = SecTrustSetAnchorCertificatesOnly(serverTrust, true)) { - error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; - return; - } - - // Verify that our pinned certificate is valid for this connection - SecTrustResultType trustResult; - if (OSStatus status = SecTrustEvaluate(serverTrust, &trustResult)) { - error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; - return; - } - if (trustResult != kSecTrustResultProceed && trustResult != kSecTrustResultUnspecified) { - completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); - return; - } - - completionHandler(NSURLSessionAuthChallengeUseCredential, - [NSURLCredential credentialForTrust:protectionSpace.serverTrust]); -} - -- (void)URLSession:(__unused NSURLSession *)session - dataTask:(__unused NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data { - if (!_data) { - _data = data; - return; - } - if (![_data respondsToSelector:@selector(appendData:)]) { - _data = [_data mutableCopy]; - } - [(id)_data appendData:data]; -} - -- (void)URLSession:(__unused NSURLSession *)session - task:(NSURLSessionTask *)task -didCompleteWithError:(NSError *)error -{ - if (error) { - _completionBlock(error, nil); - return; - } - - if (NSError *error = [self validateResponse:task.response data:_data]) { - _completionBlock(error, nil); - return; - } - - id json = [NSJSONSerialization JSONObjectWithData:_data - options:(NSJSONReadingOptions)0 - error:&error]; - if (!json) { - _completionBlock(error, nil); - return; - } - if (![json isKindOfClass:[NSDictionary class]]) { - _completionBlock(make_auth_error_bad_response(json), nil); - return; - } - - _completionBlock(nil, (NSDictionary *)json); -} - -- (NSError *)validateResponse:(NSURLResponse *)response data:(NSData *)data { - if (![response isKindOfClass:[NSHTTPURLResponse class]]) { - // FIXME: Provide error message - return make_auth_error_bad_response(); - } - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - BOOL badResponse = (NSLocationInRange(httpResponse.statusCode, rangeForErrorType(ClientError)) - || NSLocationInRange(httpResponse.statusCode, rangeForErrorType(ServerError))); - if (badResponse) { - if (RLMSyncErrorResponseModel *responseModel = [self responseModelFromData:data]) { - switch (responseModel.code) { - case RLMSyncAuthErrorInvalidParameters: - case RLMSyncAuthErrorMissingPath: - case RLMSyncAuthErrorInvalidCredential: - case RLMSyncAuthErrorUserDoesNotExist: - case RLMSyncAuthErrorUserAlreadyExists: - case RLMSyncAuthErrorAccessDeniedOrInvalidPath: - case RLMSyncAuthErrorInvalidAccessToken: - case RLMSyncAuthErrorExpiredPermissionOffer: - case RLMSyncAuthErrorAmbiguousPermissionOffer: - case RLMSyncAuthErrorFileCannotBeShared: - return make_auth_error(responseModel); - default: - // Right now we assume that any codes not described - // above are generic HTTP error codes. - return make_auth_error_http_status(responseModel.status); - } - } - return make_auth_error_http_status(httpResponse.statusCode); - } - - if (!data) { - // FIXME: provide error message - return make_auth_error_bad_response(); - } - - return nil; -} - -- (RLMSyncErrorResponseModel *)responseModelFromData:(NSData *)data { - if (data.length == 0) { - return nil; - } - id json = [NSJSONSerialization JSONObjectWithData:data - options:(NSJSONReadingOptions)0 - error:nil]; - if (!json || ![json isKindOfClass:[NSDictionary class]]) { - return nil; - } - return [[RLMSyncErrorResponseModel alloc] initWithDictionary:json]; -} - -@end - -@implementation RLMNetworkRequestOptions -@end - -#pragma mark - Endpoint Implementations - -@implementation RLMSyncAuthEndpoint -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"auth"]; -} -@end - -@implementation RLMSyncChangePasswordEndpoint -+ (NSString *)httpMethod { - return @"PUT"; -} - -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"auth/password"]; -} -@end - -@implementation RLMSyncUpdateAccountEndpoint -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"auth/password/updateAccount"]; -} -@end - -@implementation RLMSyncGetUserInfoEndpoint -+ (NSString *)httpMethod { - return @"GET"; -} - -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json { - NSString *provider = json[kRLMSyncProviderKey]; - NSString *providerID = json[kRLMSyncProviderIDKey]; - NSAssert([provider isKindOfClass:[NSString class]] && [providerID isKindOfClass:[NSString class]], - @"malformed request; this indicates a logic error in the binding."); - NSCharacterSet *allowed = [NSCharacterSet URLQueryAllowedCharacterSet]; - NSString *pathComponent = [NSString stringWithFormat:@"auth/users/%@/%@", - [provider stringByAddingPercentEncodingWithAllowedCharacters:allowed], - [providerID stringByAddingPercentEncodingWithAllowedCharacters:allowed]]; - return [authServerURL URLByAppendingPathComponent:pathComponent]; -} - -+ (NSData *)httpBodyForPayload:(__unused NSDictionary *)json error:(__unused NSError **)error { - return nil; -} -@end - -@implementation RLMSyncGetPermissionsEndpoint -+ (NSString *)httpMethod { - return @"GET"; -} -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"permissions"]; -} -@end - -@implementation RLMSyncGetPermissionOffersEndpoint -+ (NSString *)httpMethod { - return @"GET"; -} -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"permissions/offers"]; -} -@end - -@implementation RLMSyncApplyPermissionsEndpoint -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"permissions/apply"]; -} -@end - -@implementation RLMSyncOfferPermissionsEndpoint -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(__unused NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:@"permissions/offers"]; -} -@end - -@implementation RLMSyncAcceptPermissionOfferEndpoint -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:[NSString stringWithFormat:@"permissions/offers/%@/accept", json[@"offerToken"]]]; -} -@end - -@implementation RLMSyncInvalidatePermissionOfferEndpoint -+ (NSString *)httpMethod { - return @"DELETE"; -} -+ (NSURL *)urlForAuthServer:(NSURL *)authServerURL payload:(NSDictionary *)json { - return [authServerURL URLByAppendingPathComponent:[NSString stringWithFormat:@"permissions/offers/%@", json[@"offerToken"]]]; -} -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMObject.mm b/Lesson14/Pods/Realm/Realm/RLMObject.mm deleted file mode 100644 index 663ec64..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMObject.mm +++ /dev/null @@ -1,364 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObject_Private.hpp" - -#import "RLMAccessor.h" -#import "RLMArray.h" -#import "RLMCollection_Private.hpp" -#import "RLMObjectBase_Private.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMSchema_Private.h" - -#import "collection_notifications.hpp" -#import "object.hpp" - -@interface RLMPropertyChange () -@property (nonatomic, readwrite, strong) NSString *name; -@property (nonatomic, readwrite, strong, nullable) id previousValue; -@property (nonatomic, readwrite, strong, nullable) id value; -@end - -// We declare things in RLMObject which are actually implemented in RLMObjectBase -// for documentation's sake, which leads to -Wunimplemented-method warnings. -// Other alternatives to this would be to disable -Wunimplemented-method for this -// file (but then we could miss legitimately missing things), or declaring the -// inherited things in a category (but they currently aren't nicely grouped for -// that). -@implementation RLMObject - -// synthesized in RLMObjectBase -@dynamic invalidated, realm, objectSchema; - -#pragma mark - Designated Initializers - -- (instancetype)init { - return [super init]; -} - -#pragma mark - Convenience Initializers - -- (instancetype)initWithValue:(id)value { - if (!(self = [self init])) { - return nil; - } - RLMInitializeWithValue(self, value, RLMSchema.partialPrivateSharedSchema); - return self; -} - -#pragma mark - Class-based Object Creation - -+ (instancetype)createInDefaultRealmWithValue:(id)value { - return (RLMObject *)RLMCreateObjectInRealmWithValue([RLMRealm defaultRealm], [self className], value, RLMUpdatePolicyError); -} - -+ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value { - return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyError); -} - -+ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value { - return [self createOrUpdateInRealm:[RLMRealm defaultRealm] withValue:value]; -} - -+ (instancetype)createOrUpdateModifiedInDefaultRealmWithValue:(id)value { - return [self createOrUpdateModifiedInRealm:[RLMRealm defaultRealm] withValue:value]; -} - -+ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value { - RLMVerifyHasPrimaryKey(self); - return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyUpdateAll); -} - -+ (instancetype)createOrUpdateModifiedInRealm:(RLMRealm *)realm withValue:(id)value { - RLMVerifyHasPrimaryKey(self); - return (RLMObject *)RLMCreateObjectInRealmWithValue(realm, [self className], value, RLMUpdatePolicyUpdateChanged); -} - -#pragma mark - Subscripting - -- (id)objectForKeyedSubscript:(NSString *)key { - return RLMObjectBaseObjectForKeyedSubscript(self, key); -} - -- (void)setObject:(id)obj forKeyedSubscript:(NSString *)key { - RLMObjectBaseSetObjectForKeyedSubscript(self, key, obj); -} - -#pragma mark - Getting & Querying - -+ (RLMResults *)allObjects { - return RLMGetObjects(RLMRealm.defaultRealm, self.className, nil); -} - -+ (RLMResults *)allObjectsInRealm:(__unsafe_unretained RLMRealm *const)realm { - return RLMGetObjects(realm, self.className, nil); -} - -+ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - RLMResults *results = [self objectsWhere:predicateFormat args:args]; - va_end(args); - return results; -} - -+ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { - return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; -} - -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - RLMResults *results = [self objectsInRealm:realm where:predicateFormat args:args]; - va_end(args); - return results; -} - -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args { - return [self objectsInRealm:realm withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; -} - -+ (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { - return RLMGetObjects(RLMRealm.defaultRealm, self.className, predicate); -} - -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(NSPredicate *)predicate { - return RLMGetObjects(realm, self.className, predicate); -} - -+ (instancetype)objectForPrimaryKey:(id)primaryKey { - return RLMGetObject(RLMRealm.defaultRealm, self.className, primaryKey); -} - -+ (instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(id)primaryKey { - return RLMGetObject(realm, self.className, primaryKey); -} - -#pragma mark - Other Instance Methods - -- (BOOL)isEqualToObject:(RLMObject *)object { - return [object isKindOfClass:RLMObject.class] && RLMObjectBaseAreEqual(self, object); -} - -- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block { - return RLMObjectAddNotificationBlock(self, ^(NSArray *propertyNames, - NSArray *oldValues, NSArray *newValues, NSError *error) { - if (error) { - block(false, nil, error); - } - else if (!propertyNames) { - block(true, nil, nil); - } - else { - auto properties = [NSMutableArray arrayWithCapacity:propertyNames.count]; - for (NSUInteger i = 0, count = propertyNames.count; i < count; ++i) { - auto prop = [RLMPropertyChange new]; - prop.name = propertyNames[i]; - prop.previousValue = RLMCoerceToNil(oldValues[i]); - prop.value = RLMCoerceToNil(newValues[i]); - [properties addObject:prop]; - } - block(false, properties, nil); - } - }); -} - -+ (NSString *)className { - return [super className]; -} - -#pragma mark - Default values for schema definition - -+ (NSArray *)indexedProperties { - return @[]; -} - -+ (NSDictionary *)linkingObjectsProperties { - return @{}; -} - -+ (NSDictionary *)defaultPropertyValues { - return nil; -} - -+ (NSString *)primaryKey { - return nil; -} - -+ (NSArray *)ignoredProperties { - return nil; -} - -+ (NSArray *)requiredProperties { - return @[]; -} - -+ (bool)_realmIgnoreClass { - return false; -} - -@end - -@implementation RLMDynamicObject - -+ (bool)_realmIgnoreClass { - return true; -} - -+ (BOOL)shouldIncludeInDefaultSchema { - return NO; -} - -- (id)valueForUndefinedKey:(NSString *)key { - return RLMDynamicGetByName(self, key); -} - -- (void)setValue:(id)value forUndefinedKey:(NSString *)key { - RLMDynamicValidatedSet(self, key, value); -} - -+ (RLMObjectSchema *)sharedSchema { - return nil; -} - -@end - -BOOL RLMIsObjectOrSubclass(Class klass) { - return RLMIsKindOfClass(klass, RLMObjectBase.class); -} - -BOOL RLMIsObjectSubclass(Class klass) { - return RLMIsKindOfClass(class_getSuperclass(class_getSuperclass(klass)), RLMObjectBase.class); -} - -@interface RLMObjectNotificationToken : RLMCancellationToken -@end -@implementation RLMObjectNotificationToken { -@public - realm::Object _object; -} -@end - -RLMNotificationToken *RLMObjectAddNotificationBlock(RLMObjectBase *obj, RLMObjectNotificationCallback block) { - if (!obj->_realm) { - @throw RLMException(@"Only objects which are managed by a Realm support change notifications"); - } - [obj->_realm verifyNotificationsAreSupported:true]; - - struct { - void (^block)(NSArray *, NSArray *, NSArray *, NSError *); - RLMObjectBase *object; - - NSArray *propertyNames = nil; - NSArray *oldValues = nil; - bool deleted = false; - - void populateProperties(realm::CollectionChangeSet const& c) { - if (propertyNames) { - return; - } - if (!c.deletions.empty()) { - deleted = true; - return; - } - if (c.columns.empty()) { - return; - } - - auto properties = [NSMutableArray new]; - for (size_t i = 0; i < c.columns.size(); ++i) { - if (c.columns[i].empty()) { - continue; - } - if (auto prop = object->_info->propertyForTableColumn(i)) { - [properties addObject:prop.name]; - } - } - if (properties.count) { - propertyNames = properties; - } - } - - NSArray *readValues(realm::CollectionChangeSet const& c) { - if (c.empty()) { - return nil; - } - populateProperties(c); - if (!propertyNames) { - return nil; - } - - auto values = [NSMutableArray arrayWithCapacity:propertyNames.count]; - for (NSString *name in propertyNames) { - id value = [object valueForKey:name]; - if (!value || [value isKindOfClass:[RLMArray class]]) { - [values addObject:NSNull.null]; - } - else { - [values addObject:value]; - } - } - return values; - } - - void before(realm::CollectionChangeSet const& c) { - @autoreleasepool { - oldValues = readValues(c); - } - } - - void after(realm::CollectionChangeSet const& c) { - @autoreleasepool { - auto newValues = readValues(c); - if (deleted) { - block(nil, nil, nil, nil); - } - else if (newValues) { - block(propertyNames, oldValues, newValues, nil); - } - propertyNames = nil; - oldValues = nil; - } - } - - void error(std::exception_ptr err) { - @autoreleasepool { - try { - rethrow_exception(err); - } - catch (...) { - NSError *error = nil; - RLMRealmTranslateException(&error); - block(nil, nil, nil, error); - } - } - } - } callback{block, obj}; - - realm::Object object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row); - auto token = [[RLMObjectNotificationToken alloc] initWithToken:object.add_notification_callback(callback) realm:obj->_realm]; - token->_object = std::move(object); - return token; -} - -@implementation RLMPropertyChange -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMObjectBase.mm b/Lesson14/Pods/Realm/Realm/RLMObjectBase.mm deleted file mode 100644 index 3b264c8..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMObjectBase.mm +++ /dev/null @@ -1,468 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObject_Private.hpp" - -#import "RLMAccessor.h" -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObservation.hpp" -#import "RLMOptionalBase.h" -#import "RLMProperty_Private.h" -#import "RLMRealm_Private.hpp" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" -#import "RLMThreadSafeReference_Private.hpp" -#import "RLMUtil.hpp" - -#import "object.hpp" -#import "object_schema.hpp" -#import "shared_realm.hpp" - -using namespace realm; - -const NSUInteger RLMDescriptionMaxDepth = 5; - - -static bool isManagedAccessorClass(Class cls) { - const char *className = class_getName(cls); - const char accessorClassPrefix[] = "RLM:Managed"; - return strncmp(className, accessorClassPrefix, sizeof(accessorClassPrefix) - 1) == 0; -} - -static bool maybeInitObjectSchemaForUnmanaged(RLMObjectBase *obj) { - Class cls = obj.class; - if (isManagedAccessorClass(cls)) { - return false; - } - - obj->_objectSchema = [cls sharedSchema]; - if (!obj->_objectSchema) { - return false; - } - - // set default values - if (!obj->_objectSchema.isSwiftClass) { - NSDictionary *dict = RLMDefaultValuesForObjectSchema(obj->_objectSchema); - for (NSString *key in dict) { - [obj setValue:dict[key] forKey:key]; - } - } - - // set unmanaged accessor class - object_setClass(obj, obj->_objectSchema.unmanagedClass); - return true; -} - -@interface RLMObjectBase () -@end - -@implementation RLMObjectBase -// unmanaged init -- (instancetype)init { - if ((self = [super init])) { - maybeInitObjectSchemaForUnmanaged(self); - } - return self; -} - -- (void)dealloc { - // This can't be a unique_ptr because associated objects are removed - // *after* c++ members are destroyed and dealloc is called, and we need it - // to be in a validish state when that happens - delete _observationInfo; - _observationInfo = nullptr; -} - -static id coerceToObjectType(id obj, Class cls, RLMSchema *schema) { - if ([obj isKindOfClass:cls]) { - return obj; - } - id value = [[cls alloc] init]; - RLMInitializeWithValue(value, obj, schema); - return value; -} - -static id validatedObjectForProperty(__unsafe_unretained id const obj, - __unsafe_unretained RLMObjectSchema *const objectSchema, - __unsafe_unretained RLMProperty *const prop, - __unsafe_unretained RLMSchema *const schema) { - RLMValidateValueForProperty(obj, objectSchema, prop); - if (!obj || obj == NSNull.null) { - return nil; - } - if (prop.type == RLMPropertyTypeObject) { - Class objectClass = schema[prop.objectClassName].objectClass; - if (prop.array) { - NSMutableArray *ret = [[NSMutableArray alloc] init]; - for (id el in obj) { - [ret addObject:coerceToObjectType(el, objectClass, schema)]; - } - return ret; - } - return coerceToObjectType(obj, objectClass, schema); - } - return obj; -} - -void RLMInitializeWithValue(RLMObjectBase *self, id value, RLMSchema *schema) { - if (!value || value == NSNull.null) { - @throw RLMException(@"Must provide a non-nil value."); - } - - RLMObjectSchema *objectSchema = self->_objectSchema; - if (!objectSchema) { - // Will be nil if we're called during schema init, when we don't want - // to actually populate the object anyway - return; - } - - NSArray *properties = objectSchema.properties; - if (NSArray *array = RLMDynamicCast(value)) { - if (array.count > properties.count) { - @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).", - (unsigned long long)array.count, (unsigned long long)properties.count); - } - NSUInteger i = 0; - for (id val in array) { - RLMProperty *prop = properties[i++]; - [self setValue:validatedObjectForProperty(RLMCoerceToNil(val), objectSchema, prop, schema) - forKey:prop.name]; - } - } - else { - // assume our object is an NSDictionary or an object with kvc properties - for (RLMProperty *prop in properties) { - id obj = RLMValidatedValueForProperty(value, prop.name, objectSchema.className); - - // don't set unspecified properties - if (!obj) { - continue; - } - - [self setValue:validatedObjectForProperty(RLMCoerceToNil(obj), objectSchema, prop, schema) - forKey:prop.name]; - } - } -} - -id RLMCreateManagedAccessor(Class cls, RLMClassInfo *info) { - RLMObjectBase *obj = [[cls alloc] init]; - obj->_info = info; - obj->_realm = info->realm; - obj->_objectSchema = info->rlmObjectSchema; - return obj; -} - -- (id)valueForKey:(NSString *)key { - if (_observationInfo) { - return _observationInfo->valueForKey(key); - } - return [super valueForKey:key]; -} - -// Generic Swift properties can't be dynamic, so KVO doesn't work for them by default -- (id)valueForUndefinedKey:(NSString *)key { - RLMProperty *prop = _objectSchema[key]; - if (Class accessor = prop.swiftAccessor) { - return [accessor get:(char *)(__bridge void *)self + ivar_getOffset(prop.swiftIvar)]; - } - if (Ivar ivar = prop.swiftIvar) { - return RLMCoerceToNil(object_getIvar(self, ivar)); - } - return [super valueForUndefinedKey:key]; -} - -- (void)setValue:(id)value forUndefinedKey:(NSString *)key { - value = RLMCoerceToNil(value); - RLMProperty *property = _objectSchema[key]; - if (Ivar ivar = property.swiftIvar) { - if (property.array) { - value = RLMAsFastEnumeration(value); - RLMArray *array = [object_getIvar(self, ivar) _rlmArray]; - [array removeAllObjects]; - - if (value) { - [array addObjects:validatedObjectForProperty(value, _objectSchema, property, - RLMSchema.partialPrivateSharedSchema)]; - } - } - else if (property.optional) { - RLMSetOptional(object_getIvar(self, ivar), value); - } - return; - } - [super setValue:value forUndefinedKey:key]; -} - -// overridden at runtime per-class for performance -+ (NSString *)className { - NSString *className = NSStringFromClass(self); - if ([RLMSwiftSupport isSwiftClassName:className]) { - className = [RLMSwiftSupport demangleClassName:className]; - } - return className; -} - -// overridden at runtime per-class for performance -+ (RLMObjectSchema *)sharedSchema { - return [RLMSchema sharedSchemaForClass:self.class]; -} - -+ (void)initializeLinkedObjectSchemas { - for (RLMProperty *prop in self.sharedSchema.properties) { - if (prop.type == RLMPropertyTypeObject && !RLMSchema.partialPrivateSharedSchema[prop.objectClassName]) { - [[RLMSchema classForString:prop.objectClassName] initializeLinkedObjectSchemas]; - } - } -} - -+ (nullable NSArray *)_getPropertiesWithInstance:(__unused id)obj { - return nil; -} - -- (NSString *)description { - if (self.isInvalidated) { - return @"[invalid object]"; - } - - return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth]; -} - -- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth { - if (depth == 0) { - return @""; - } - - NSString *baseClassName = _objectSchema.className; - NSMutableString *mString = [NSMutableString stringWithFormat:@"%@ {\n", baseClassName]; - - for (RLMProperty *property in _objectSchema.properties) { - id object = [(id)self objectForKeyedSubscript:property.name]; - NSString *sub; - if ([object respondsToSelector:@selector(descriptionWithMaxDepth:)]) { - sub = [object descriptionWithMaxDepth:depth - 1]; - } - else if (property.type == RLMPropertyTypeData) { - static NSUInteger maxPrintedDataLength = 24; - NSData *data = object; - NSUInteger length = data.length; - if (length > maxPrintedDataLength) { - data = [NSData dataWithBytes:data.bytes length:maxPrintedDataLength]; - } - NSString *dataDescription = [data description]; - sub = [NSString stringWithFormat:@"<%@ — %lu total bytes>", [dataDescription substringWithRange:NSMakeRange(1, dataDescription.length - 2)], (unsigned long)length]; - } - else { - sub = [object description]; - } - [mString appendFormat:@"\t%@ = %@;\n", property.name, [sub stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; - } - [mString appendString:@"}"]; - - return [NSString stringWithString:mString]; -} - -- (RLMRealm *)realm { - return _realm; -} - -- (RLMObjectSchema *)objectSchema { - return _objectSchema; -} - -- (BOOL)isInvalidated { - // if not unmanaged and our accessor has been detached, we have been deleted - return self.class == _objectSchema.accessorClass && !_row.is_attached(); -} - -- (BOOL)isEqual:(id)object { - if (RLMObjectBase *other = RLMDynamicCast(object)) { - if (_objectSchema.primaryKeyProperty) { - return RLMObjectBaseAreEqual(self, other); - } - } - return [super isEqual:object]; -} - -- (NSUInteger)hash { - if (_objectSchema.primaryKeyProperty) { - id primaryProperty = [self valueForKey:_objectSchema.primaryKeyProperty.name]; - - // modify the hash of our primary key value to avoid potential (although unlikely) collisions - return [primaryProperty hash] ^ 1; - } - else { - return [super hash]; - } -} - -+ (BOOL)shouldIncludeInDefaultSchema { - return RLMIsObjectSubclass(self); -} - -+ (NSString *)_realmObjectName { - return nil; -} - -+ (NSDictionary *)_realmColumnNames { - return nil; -} - -+ (bool)_realmIgnoreClass { - return false; -} - -- (id)mutableArrayValueForKey:(NSString *)key { - id obj = [self valueForKey:key]; - if ([obj isKindOfClass:[RLMArray class]]) { - return obj; - } - return [super mutableArrayValueForKey:key]; -} - -- (void)addObserver:(id)observer - forKeyPath:(NSString *)keyPath - options:(NSKeyValueObservingOptions)options - context:(void *)context { - if (!_observationInfo) { - _observationInfo = new RLMObservationInfo(self); - } - _observationInfo->recordObserver(_row, _info, _objectSchema, keyPath); - - [super addObserver:observer forKeyPath:keyPath options:options context:context]; -} - -- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath { - [super removeObserver:observer forKeyPath:keyPath]; - if (_observationInfo) - _observationInfo->removeObserver(); -} - -+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { - if (isManagedAccessorClass(self) && [class_getSuperclass(self.class) sharedSchema][key]) { - return NO; - } - - return [super automaticallyNotifiesObserversForKey:key]; -} - -#pragma mark - Thread Confined Protocol Conformance - -- (std::unique_ptr)makeThreadSafeReference { - Object object(_realm->_realm, *_info->objectSchema, _row); - realm::ThreadSafeReference reference = _realm->_realm->obtain_thread_safe_reference(std::move(object)); - return std::make_unique>(std::move(reference)); -} - -- (id)objectiveCMetadata { - return nil; -} - -+ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference - metadata:(__unused id)metadata - realm:(RLMRealm *)realm { - REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); - auto object_reference = static_cast *>(reference.get()); - - Object object = realm->_realm->resolve_thread_safe_reference(std::move(*object_reference)); - if (!object.is_valid()) { - return nil; - } - NSString *objectClassName = @(object.get_object_schema().name.c_str()); - - return RLMCreateObjectAccessor(realm->_info[objectClassName], object.row().get_index()); -} - -@end - -RLMRealm *RLMObjectBaseRealm(__unsafe_unretained RLMObjectBase *object) { - return object ? object->_realm : nil; -} - -RLMObjectSchema *RLMObjectBaseObjectSchema(__unsafe_unretained RLMObjectBase *object) { - return object ? object->_objectSchema : nil; -} - -id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key) { - if (!object) { - return nil; - } - - if (object->_realm) { - return RLMDynamicGetByName(object, key); - } - else { - return [object valueForKey:key]; - } -} - -void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj) { - if (!object) { - return; - } - - if (object->_realm || object.class == object->_objectSchema.accessorClass) { - RLMDynamicValidatedSet(object, key, obj); - } - else { - [object setValue:obj forKey:key]; - } -} - - -BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1, RLMObjectBase *o2) { - // if not the correct types throw - if ((o1 && ![o1 isKindOfClass:RLMObjectBase.class]) || (o2 && ![o2 isKindOfClass:RLMObjectBase.class])) { - @throw RLMException(@"Can only compare objects of class RLMObjectBase"); - } - // if identical object (or both are nil) - if (o1 == o2) { - return YES; - } - // if one is nil - if (o1 == nil || o2 == nil) { - return NO; - } - // if not in realm or differing realms - if (o1->_realm == nil || o1->_realm != o2->_realm) { - return NO; - } - // if either are detached - if (!o1->_row.is_attached() || !o2->_row.is_attached()) { - return NO; - } - // if table and index are the same - return o1->_row.get_table() == o2->_row.get_table() - && o1->_row.get_index() == o2->_row.get_index(); -} - -id RLMValidatedValueForProperty(id object, NSString *key, NSString *className) { - @try { - return [object valueForKey:key]; - } - @catch (NSException *e) { - if ([e.name isEqualToString:NSUndefinedKeyException]) { - @throw RLMException(@"Invalid value '%@' to initialize object of type '%@': missing key '%@'", - object, className, key); - } - @throw; - } -} diff --git a/Lesson14/Pods/Realm/Realm/RLMObjectSchema.mm b/Lesson14/Pods/Realm/Realm/RLMObjectSchema.mm deleted file mode 100644 index 4bbd1c1..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMObjectSchema.mm +++ /dev/null @@ -1,370 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObjectSchema_Private.hpp" - -#import "RLMArray.h" -#import "RLMListBase.h" -#import "RLMObject_Private.h" -#import "RLMProperty_Private.hpp" -#import "RLMRealm_Dynamic.h" -#import "RLMRealm_Private.hpp" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" -#import "RLMUtil.hpp" - -#import "object_schema.hpp" -#import "object_store.hpp" - -using namespace realm; - -// private properties -@interface RLMObjectSchema () -@property (nonatomic, readwrite) NSDictionary *allPropertiesByName; -@property (nonatomic, readwrite) NSString *className; -@end - -@implementation RLMObjectSchema { - NSArray *_swiftGenericProperties; -} - -- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties { - self = [super init]; - self.className = objectClassName; - self.properties = properties; - self.objectClass = objectClass; - self.accessorClass = objectClass; - self.unmanagedClass = objectClass; - return self; -} - -// return properties by name -- (RLMProperty *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)key { - return _allPropertiesByName[key]; -} - -// create property map when setting property array -- (void)setProperties:(NSArray *)properties { - _properties = properties; - [self _propertiesDidChange]; -} - -- (void)setComputedProperties:(NSArray *)computedProperties { - _computedProperties = computedProperties; - [self _propertiesDidChange]; -} - -- (void)_propertiesDidChange { - NSMutableDictionary *map = [NSMutableDictionary dictionaryWithCapacity:_properties.count + _computedProperties.count]; - NSUInteger index = 0; - for (RLMProperty *prop in _properties) { - prop.index = index++; - map[prop.name] = prop; - if (prop.isPrimary) { - self.primaryKeyProperty = prop; - } - } - index = 0; - for (RLMProperty *prop in _computedProperties) { - prop.index = index++; - map[prop.name] = prop; - } - _allPropertiesByName = map; -} - - -- (void)setPrimaryKeyProperty:(RLMProperty *)primaryKeyProperty { - _primaryKeyProperty.isPrimary = NO; - primaryKeyProperty.isPrimary = YES; - _primaryKeyProperty = primaryKeyProperty; -} - -+ (instancetype)schemaForObjectClass:(Class)objectClass { - RLMObjectSchema *schema = [RLMObjectSchema new]; - - // determine classname from objectclass as className method has not yet been updated - NSString *className = NSStringFromClass(objectClass); - bool hasSwiftName = [RLMSwiftSupport isSwiftClassName:className]; - if (hasSwiftName) { - className = [RLMSwiftSupport demangleClassName:className]; - } - - static Class s_swiftObjectClass = NSClassFromString(@"RealmSwiftObject"); - bool isSwift = hasSwiftName || [objectClass isSubclassOfClass:s_swiftObjectClass]; - - schema.className = className; - schema.objectClass = objectClass; - schema.accessorClass = objectClass; - schema.isSwiftClass = isSwift; - - // create array of RLMProperties, inserting properties of superclasses first - Class cls = objectClass; - Class superClass = class_getSuperclass(cls); - NSArray *allProperties = @[]; - while (superClass && superClass != RLMObjectBase.class) { - allProperties = [[RLMObjectSchema propertiesForClass:cls isSwift:isSwift] - arrayByAddingObjectsFromArray:allProperties]; - cls = superClass; - superClass = class_getSuperclass(superClass); - } - NSArray *persistedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) { - return !RLMPropertyTypeIsComputed(property.type); - }]]; - schema.properties = persistedProperties; - - NSArray *computedProperties = [allProperties filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(RLMProperty *property, NSDictionary *) { - return RLMPropertyTypeIsComputed(property.type); - }]]; - schema.computedProperties = computedProperties; - - // verify that we didn't add any properties twice due to inheritance - if (allProperties.count != [NSSet setWithArray:[allProperties valueForKey:@"name"]].count) { - NSCountedSet *countedPropertyNames = [NSCountedSet setWithArray:[allProperties valueForKey:@"name"]]; - NSArray *duplicatePropertyNames = [countedPropertyNames filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *) { - return [countedPropertyNames countForObject:object] > 1; - }]].allObjects; - - if (duplicatePropertyNames.count == 1) { - @throw RLMException(@"Property '%@' is declared multiple times in the class hierarchy of '%@'", duplicatePropertyNames.firstObject, className); - } else { - @throw RLMException(@"Object '%@' has properties that are declared multiple times in its class hierarchy: '%@'", className, [duplicatePropertyNames componentsJoinedByString:@"', '"]); - } - } - - if (NSString *primaryKey = [objectClass primaryKey]) { - for (RLMProperty *prop in schema.properties) { - if ([primaryKey isEqualToString:prop.name]) { - prop.indexed = YES; - schema.primaryKeyProperty = prop; - break; - } - } - - if (!schema.primaryKeyProperty) { - @throw RLMException(@"Primary key property '%@' does not exist on object '%@'", primaryKey, className); - } - if (schema.primaryKeyProperty.type != RLMPropertyTypeInt && schema.primaryKeyProperty.type != RLMPropertyTypeString) { - @throw RLMException(@"Property '%@' cannot be made the primary key of '%@' because it is not a 'string' or 'int' property.", - primaryKey, className); - } - } - - for (RLMProperty *prop in schema.properties) { - if (prop.optional && prop.array && (prop.type == RLMPropertyTypeObject || prop.type == RLMPropertyTypeLinkingObjects)) { - // FIXME: message is awkward - @throw RLMException(@"Property '%@.%@' cannot be made optional because optional '%@' properties are not supported.", - className, prop.name, RLMTypeToString(prop.type)); - } - } - - return schema; -} - -+ (NSArray *)propertiesForClass:(Class)objectClass isSwift:(bool)isSwiftClass { - // For Swift classes we need an instance of the object when parsing properties - id swiftObjectInstance = isSwiftClass ? [[objectClass alloc] init] : nil; - - if (NSArray *props = [objectClass _getPropertiesWithInstance:swiftObjectInstance]) { - return props; - } - - NSArray *ignoredProperties = [objectClass ignoredProperties]; - NSDictionary *linkingObjectsProperties = [objectClass linkingObjectsProperties]; - NSDictionary *columnNameMap = [objectClass _realmColumnNames]; - - unsigned int count; - std::unique_ptr props(class_copyPropertyList(objectClass, &count), &free); - NSMutableArray *propArray = [NSMutableArray arrayWithCapacity:count]; - NSSet *indexed = [[NSSet alloc] initWithArray:[objectClass indexedProperties]]; - for (unsigned int i = 0; i < count; i++) { - NSString *propertyName = @(property_getName(props[i])); - if ([ignoredProperties containsObject:propertyName]) { - continue; - } - - RLMProperty *prop = nil; - if (isSwiftClass) { - prop = [[RLMProperty alloc] initSwiftPropertyWithName:propertyName - indexed:[indexed containsObject:propertyName] - linkPropertyDescriptor:linkingObjectsProperties[propertyName] - property:props[i] - instance:swiftObjectInstance]; - } - else { - prop = [[RLMProperty alloc] initWithName:propertyName - indexed:[indexed containsObject:propertyName] - linkPropertyDescriptor:linkingObjectsProperties[propertyName] - property:props[i]]; - } - - if (prop) { - if (columnNameMap) { - prop.columnName = columnNameMap[prop.name]; - } - [propArray addObject:prop]; - } - } - - if (auto requiredProperties = [objectClass requiredProperties]) { - for (RLMProperty *property in propArray) { - bool required = [requiredProperties containsObject:property.name]; - if (required && property.type == RLMPropertyTypeObject && !property.array) { - @throw RLMException(@"Object properties cannot be made required, " - "but '+[%@ requiredProperties]' included '%@'", objectClass, property.name); - } - property.optional &= !required; - } - } - - for (RLMProperty *property in propArray) { - if (!property.optional && property.type == RLMPropertyTypeObject && !property.array) { - @throw RLMException(@"The `%@.%@` property must be marked as being optional.", - [objectClass className], property.name); - } - } - - return propArray; -} - -- (id)copyWithZone:(NSZone *)zone { - RLMObjectSchema *schema = [[RLMObjectSchema allocWithZone:zone] init]; - schema->_objectClass = _objectClass; - schema->_className = _className; - schema->_objectClass = _objectClass; - schema->_accessorClass = _objectClass; - schema->_unmanagedClass = _unmanagedClass; - schema->_isSwiftClass = _isSwiftClass; - - // call property setter to reset map and primary key - schema.properties = [[NSArray allocWithZone:zone] initWithArray:_properties copyItems:YES]; - schema.computedProperties = [[NSArray allocWithZone:zone] initWithArray:_computedProperties copyItems:YES]; - - return schema; -} - -- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema { - if (objectSchema.properties.count != _properties.count) { - return NO; - } - - if (![_properties isEqualToArray:objectSchema.properties]) { - return NO; - } - if (![_computedProperties isEqualToArray:objectSchema.computedProperties]) { - return NO; - } - - return YES; -} - -- (NSString *)description { - NSMutableString *propertiesString = [NSMutableString string]; - for (RLMProperty *property in self.properties) { - [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; - } - for (RLMProperty *property in self.computedProperties) { - [propertiesString appendFormat:@"\t%@\n", [property.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; - } - return [NSString stringWithFormat:@"%@ {\n%@}", self.className, propertiesString]; -} - -- (NSString *)objectName { - return [self.objectClass _realmObjectName] ?: _className; -} - -- (realm::ObjectSchema)objectStoreCopy:(RLMSchema *)schema { - ObjectSchema objectSchema; - objectSchema.name = self.objectName.UTF8String; - objectSchema.primary_key = _primaryKeyProperty ? _primaryKeyProperty.columnName.UTF8String : ""; - for (RLMProperty *prop in _properties) { - Property p = [prop objectStoreCopy:schema]; - p.is_primary = (prop == _primaryKeyProperty); - objectSchema.persisted_properties.push_back(std::move(p)); - } - for (RLMProperty *prop in _computedProperties) { - objectSchema.computed_properties.push_back([prop objectStoreCopy:schema]); - } - return objectSchema; -} - -+ (instancetype)objectSchemaForObjectStoreSchema:(realm::ObjectSchema const&)objectSchema { - RLMObjectSchema *schema = [RLMObjectSchema new]; - schema.className = @(objectSchema.name.c_str()); - - // create array of RLMProperties - NSMutableArray *properties = [NSMutableArray arrayWithCapacity:objectSchema.persisted_properties.size()]; - for (const Property &prop : objectSchema.persisted_properties) { - RLMProperty *property = [RLMProperty propertyForObjectStoreProperty:prop]; - property.isPrimary = (prop.name == objectSchema.primary_key); - [properties addObject:property]; - } - schema.properties = properties; - - NSMutableArray *computedProperties = [NSMutableArray arrayWithCapacity:objectSchema.computed_properties.size()]; - for (const Property &prop : objectSchema.computed_properties) { - [computedProperties addObject:[RLMProperty propertyForObjectStoreProperty:prop]]; - } - schema.computedProperties = computedProperties; - - // get primary key from realm metadata - if (objectSchema.primary_key.length()) { - NSString *primaryKeyString = [NSString stringWithUTF8String:objectSchema.primary_key.c_str()]; - schema.primaryKeyProperty = schema[primaryKeyString]; - if (!schema.primaryKeyProperty) { - @throw RLMException(@"No property matching primary key '%@'", primaryKeyString); - } - } - - // for dynamic schema use vanilla RLMDynamicObject accessor classes - schema.objectClass = RLMObject.class; - schema.accessorClass = RLMDynamicObject.class; - schema.unmanagedClass = RLMObject.class; - - return schema; -} - -- (NSArray *)swiftGenericProperties { - if (_swiftGenericProperties) { - return _swiftGenericProperties; - } - - // This check isn't semantically required, but avoiding accessing the local - // static helps perf in the obj-c case - if (!_isSwiftClass) { - return _swiftGenericProperties = @[]; - } - - // Check if it's a swift class using the obj-c API - static Class s_swiftObjectClass = NSClassFromString(@"RealmSwiftObject"); - if (![_accessorClass isSubclassOfClass:s_swiftObjectClass]) { - return _swiftGenericProperties = @[]; - } - - NSMutableArray *genericProperties = [NSMutableArray new]; - for (RLMProperty *prop in _properties) { - if (prop->_swiftIvar) { - [genericProperties addObject:prop]; - } - } - // Currently all computed properties are Swift generics - [genericProperties addObjectsFromArray:_computedProperties]; - - return _swiftGenericProperties = genericProperties; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMObjectStore.mm b/Lesson14/Pods/Realm/Realm/RLMObjectStore.mm deleted file mode 100644 index 3625004..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMObjectStore.mm +++ /dev/null @@ -1,273 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObjectStore.h" - -#import "RLMAccessor.hpp" -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObservation.hpp" -#import "RLMObject_Private.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMOptionalBase.h" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" -#import "RLMUtil.hpp" - -#import "object_store.hpp" -#import "results.hpp" -#import "shared_realm.hpp" - -#import - -#import - -using namespace realm; - -static_assert(RLMUpdatePolicyError == static_cast(CreatePolicy::ForceCreate), ""); -static_assert(RLMUpdatePolicyUpdateAll == static_cast(CreatePolicy::UpdateAll), ""); -static_assert(RLMUpdatePolicyUpdateChanged == static_cast(CreatePolicy::UpdateModified), ""); - -void RLMRealmCreateAccessors(RLMSchema *schema) { - const size_t bufferSize = sizeof("RLM:Managed ") // includes null terminator - + std::numeric_limits::digits10 - + realm::Group::max_table_name_length; - - char className[bufferSize] = "RLM:Managed "; - char *const start = className + strlen(className); - - for (RLMObjectSchema *objectSchema in schema.objectSchema) { - if (objectSchema.accessorClass != objectSchema.objectClass) { - continue; - } - - static unsigned long long count = 0; - sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String); - objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className); - } -} - -static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) { - if (!realm) { - @throw RLMException(@"Realm must not be nil"); - } - [realm verifyThread]; -} - -static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) { - RLMVerifyRealmRead(realm); - // if realm is not writable throw - if (!realm.inWriteTransaction) { - @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first."); - } -} - -void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) { - if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) { - return; - } - if (![object isKindOfClass:object->_objectSchema.objectClass]) { - // It can be a different class if it's a dynamic object, and those don't - // require any init here (and would crash since they don't have the ivars) - return; - } - - for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) { - if (prop.type == RLMPropertyTypeLinkingObjects) { - [prop.swiftAccessor initializeObject:(char *)(__bridge void *)object + ivar_getOffset(prop.swiftIvar) - parent:object property:prop]; - } - else if (prop.array) { - id ivar = object_getIvar(object, prop.swiftIvar); - RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop]; - [ivar set_rlmArray:array]; - } - else { - id ivar = object_getIvar(object, prop.swiftIvar); - RLMInitializeManagedOptional(ivar, object, prop); - } - } -} - -void RLMVerifyHasPrimaryKey(Class cls) { - RLMObjectSchema *schema = [cls sharedSchema]; - if (!schema.primaryKeyProperty) { - NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className]; - @throw [NSException exceptionWithName:@"RLMException" reason:reason userInfo:nil]; - } -} - -void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object, - __unsafe_unretained RLMRealm *const realm, - RLMUpdatePolicy updatePolicy) { - RLMVerifyInWriteTransaction(realm); - - // verify that object is unmanaged - if (object.invalidated) { - @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted"); - } - if (object->_realm) { - if (object->_realm == realm) { - // Adding an object to the Realm it's already manged by is a no-op - return; - } - // for differing realms users must explicitly create the object in the second realm - @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm."); - } - if (object->_observationInfo && object->_observationInfo->hasObservers()) { - @throw RLMException(@"Cannot add an object with observers to a Realm"); - } - - auto& info = realm->_info[object->_objectSchema.className]; - RLMAccessorContext c{info, true}; - object->_info = &info; - object->_realm = realm; - object->_objectSchema = info.rlmObjectSchema; - try { - realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object, - static_cast(updatePolicy), - -1, &object->_row); - } - catch (std::exception const& e) { - @throw RLMException(e); - } - object_setClass(object, info.rlmObjectSchema.accessorClass); - RLMInitializeSwiftAccessorGenerics(object); -} - -RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className, - id value, RLMUpdatePolicy updatePolicy) { - RLMVerifyInWriteTransaction(realm); - - if (updatePolicy != RLMUpdatePolicyError && RLMIsObjectSubclass([value class])) { - RLMObjectBase *obj = value; - if (obj->_realm == realm && [obj->_objectSchema.className isEqualToString:className]) { - // This is a no-op if value is an RLMObject of the same type already backed by the target realm. - return value; - } - } - - if (!value || value == NSNull.null) { - @throw RLMException(@"Must provide a non-nil value."); - } - - auto& info = realm->_info[className]; - if ([value isKindOfClass:[NSArray class]] && [value count] > info.objectSchema->persisted_properties.size()) { - @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).", - (unsigned long long)[value count], - (unsigned long long)info.objectSchema->persisted_properties.size()); - } - - RLMAccessorContext c{info, false}; - RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info); - try { - object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema, (id)value, - static_cast(updatePolicy)).row(); - } - catch (std::exception const& e) { - @throw RLMException(e); - } - RLMInitializeSwiftAccessorGenerics(object); - return object; -} - -void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object, - __unsafe_unretained RLMRealm *const realm) { - if (realm != object->_realm) { - @throw RLMException(@"Can only delete an object from the Realm it belongs to."); - } - - RLMVerifyInWriteTransaction(object->_realm); - - // move last row to row we are deleting - if (object->_row.is_attached()) { - RLMTrackDeletions(realm, ^{ - object->_row.move_last_over(); - }); - } - - // set realm to nil - object->_realm = nil; -} - -void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) { - RLMVerifyInWriteTransaction(realm); - - // clear table for each object schema - for (auto& info : realm->_info) { - RLMClearTable(info.second); - } -} - -RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm, - NSString *objectClassName, - NSPredicate *predicate) { - RLMVerifyRealmRead(realm); - - // create view from table and predicate - RLMClassInfo& info = realm->_info[objectClassName]; - if (!info.table()) { - // read-only realms may be missing tables since we can't add any - // missing ones on init - return [RLMResults resultsWithObjectInfo:info results:{}]; - } - - if (predicate) { - realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group); - return [RLMResults resultsWithObjectInfo:info - results:realm::Results(realm->_realm, std::move(query))]; - } - - return [RLMResults resultsWithObjectInfo:info - results:realm::Results(realm->_realm, *info.table())]; -} - -id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) { - RLMVerifyRealmRead(realm); - - auto& info = realm->_info[objectClassName]; - if (RLMProperty *prop = info.propertyForPrimaryKey()) { - RLMValidateValueForProperty(key, info.rlmObjectSchema, prop); - } - try { - RLMAccessorContext c{info}; - auto obj = realm::Object::get_for_primary_key(c, realm->_realm, *info.objectSchema, - key ?: NSNull.null); - if (!obj.is_valid()) - return nil; - return RLMCreateObjectAccessor(info, obj.row()); - } - catch (std::exception const& e) { - @throw RLMException(e); - } -} - -RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, NSUInteger index) { - return RLMCreateObjectAccessor(info, (*info.table())[index]); -} - -// Create accessor and register with realm -RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, realm::RowExpr row) { - RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info); - accessor->_row = row; - RLMInitializeSwiftAccessorGenerics(accessor); - return accessor; -} diff --git a/Lesson14/Pods/Realm/Realm/RLMObservation.mm b/Lesson14/Pods/Realm/Realm/RLMObservation.mm deleted file mode 100644 index f8102ed..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMObservation.mm +++ /dev/null @@ -1,499 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMObservation.hpp" - -#import "RLMAccessor.h" -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObject_Private.hpp" -#import "RLMProperty_Private.h" -#import "RLMRealm_Private.hpp" - -#import - -using namespace realm; - -namespace { - template - struct IteratorPair { - Iterator first; - Iterator second; - }; - template - Iterator begin(IteratorPair const& p) { - return p.first; - } - template - Iterator end(IteratorPair const& p) { - return p.second; - } - - template - auto reverse(Container const& c) { - return IteratorPair{c.rbegin(), c.rend()}; - } -} - -RLMObservationInfo::RLMObservationInfo(RLMClassInfo &objectSchema, std::size_t row, id object) -: object(object) -, objectSchema(&objectSchema) -{ - setRow(*objectSchema.table(), row); -} - -RLMObservationInfo::RLMObservationInfo(id object) -: object(object) -{ -} - -RLMObservationInfo::~RLMObservationInfo() { - if (prev) { - // Not the head of the linked list, so just detach from the list - REALM_ASSERT_DEBUG(prev->next == this); - prev->next = next; - if (next) { - REALM_ASSERT_DEBUG(next->prev == this); - next->prev = prev; - } - } - else if (objectSchema) { - // The head of the list, so remove self from the object schema's array - // of observation info, either replacing self with the next info or - // removing entirely if there is no next - auto end = objectSchema->observedObjects.end(); - auto it = find(objectSchema->observedObjects.begin(), end, this); - if (it != end) { - if (next) { - *it = next; - next->prev = nullptr; - } - else { - iter_swap(it, std::prev(end)); - objectSchema->observedObjects.pop_back(); - } - } - } - // Otherwise the observed object was unmanaged, so nothing to do - -#ifdef DEBUG - // ensure that incorrect cleanup fails noisily - object = (__bridge id)(void *)-1; - prev = (RLMObservationInfo *)-1; - next = (RLMObservationInfo *)-1; -#endif -} - -NSString *RLMObservationInfo::columnName(size_t col) const noexcept { - return objectSchema->propertyForTableColumn(col).name; -} - -void RLMObservationInfo::willChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const { - if (indexes) { - forEach([=](__unsafe_unretained auto o) { - [o willChange:kind valuesAtIndexes:indexes forKey:key]; - }); - } - else { - forEach([=](__unsafe_unretained auto o) { - [o willChangeValueForKey:key]; - }); - } -} - -void RLMObservationInfo::didChange(NSString *key, NSKeyValueChange kind, NSIndexSet *indexes) const { - if (indexes) { - forEach([=](__unsafe_unretained auto o) { - [o didChange:kind valuesAtIndexes:indexes forKey:key]; - }); - } - else { - forEach([=](__unsafe_unretained auto o) { - [o didChangeValueForKey:key]; - }); - } -} - -void RLMObservationInfo::prepareForInvalidation() { - REALM_ASSERT_DEBUG(objectSchema); - REALM_ASSERT_DEBUG(!prev); - for (auto info = this; info; info = info->next) - info->invalidated = true; -} - -void RLMObservationInfo::setRow(realm::Table &table, size_t newRow) { - REALM_ASSERT_DEBUG(!row); - REALM_ASSERT_DEBUG(objectSchema); - row = table[newRow]; - for (auto info : objectSchema->observedObjects) { - if (info->row && info->row.get_index() == row.get_index()) { - prev = info; - next = info->next; - if (next) - next->prev = this; - info->next = this; - return; - } - } - objectSchema->observedObjects.push_back(this); -} - -void RLMObservationInfo::recordObserver(realm::Row& objectRow, RLMClassInfo *objectInfo, - __unsafe_unretained RLMObjectSchema *const objectSchema, - __unsafe_unretained NSString *const keyPath) { - ++observerCount; - if (row) { - return; - } - - // add ourselves to the list of observed objects if this is the first time - // an observer is being added to a managed object - if (objectRow) { - this->objectSchema = objectInfo; - setRow(*objectRow.get_table(), objectRow.get_index()); - return; - } - - // Arrays need a reference to their containing object to avoid having to - // go through the awful proxy object from mutableArrayValueForKey. - // For managed objects we do this when the object is added or created - // (and have to to support notifications from modifying an object which - // was never observed), but for Swift classes (both RealmSwift and - // RLMObject) we can't do it then because we don't know what the parent - // object is. - - NSUInteger sep = [keyPath rangeOfString:@"."].location; - NSString *key = sep == NSNotFound ? keyPath : [keyPath substringToIndex:sep]; - RLMProperty *prop = objectSchema[key]; - if (prop && prop.array) { - id value = valueForKey(key); - RLMArray *array = [value isKindOfClass:[RLMListBase class]] ? [value _rlmArray] : value; - array->_key = key; - array->_parentObject = object; - } - else if (auto swiftIvar = prop.swiftIvar) { - if (auto optional = RLMDynamicCast(object_getIvar(object, swiftIvar))) { - RLMInitializeUnmanagedOptional(optional, object, prop); - } - } -} - -void RLMObservationInfo::removeObserver() { - --observerCount; -} - -id RLMObservationInfo::valueForKey(NSString *key) { - if (invalidated) { - if ([key isEqualToString:RLMInvalidatedKey]) { - return @YES; - } - return cachedObjects[key]; - } - - if (key != lastKey) { - lastKey = key; - lastProp = objectSchema ? objectSchema->rlmObjectSchema[key] : nil; - } - - static auto superValueForKey = reinterpret_cast([NSObject methodForSelector:@selector(valueForKey:)]); - if (!lastProp) { - // Not a managed property, so use NSObject's implementation of valueForKey: - return RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key)); - } - - auto getSuper = [&] { - return row ? RLMDynamicGet(object, lastProp) : RLMCoerceToNil(superValueForKey(object, @selector(valueForKey:), key)); - }; - - // We need to return the same object each time for observing over keypaths - // to work, so we store a cache of them here. We can't just cache them on - // the object as that leads to retain cycles. - if (lastProp.array) { - RLMArray *value = cachedObjects[key]; - if (!value) { - value = getSuper(); - if (!cachedObjects) { - cachedObjects = [NSMutableDictionary new]; - } - cachedObjects[key] = value; - } - return value; - } - - if (lastProp.type == RLMPropertyTypeObject) { - size_t col = row.get_column_index(lastProp.name.UTF8String); - if (row.is_null_link(col)) { - [cachedObjects removeObjectForKey:key]; - return nil; - } - - RLMObjectBase *value = cachedObjects[key]; - if (value && value->_row.get_index() == row.get_link(col)) { - return value; - } - value = getSuper(); - if (!cachedObjects) { - cachedObjects = [NSMutableDictionary new]; - } - cachedObjects[key] = value; - return value; - } - - return getSuper(); -} - -RLMObservationInfo *RLMGetObservationInfo(RLMObservationInfo *info, size_t row, - RLMClassInfo& objectSchema) { - if (info) { - return info; - } - - for (RLMObservationInfo *info : objectSchema.observedObjects) { - if (info->isForRow(row)) { - return info; - } - } - - return nullptr; -} - -void RLMClearTable(RLMClassInfo &objectSchema) { - for (auto info : objectSchema.observedObjects) { - info->willChange(RLMInvalidatedKey); - } - - RLMTrackDeletions(objectSchema.realm, ^{ - Results(objectSchema.realm->_realm, *objectSchema.table()).clear(); - - for (auto info : objectSchema.observedObjects) { - info->prepareForInvalidation(); - } - }); - - for (auto info : reverse(objectSchema.observedObjects)) { - info->didChange(RLMInvalidatedKey); - } - - objectSchema.observedObjects.clear(); -} - -void RLMTrackDeletions(__unsafe_unretained RLMRealm *const realm, dispatch_block_t block) { - std::vector *> observers; - - // Build up an array of observation info arrays which is indexed by table - // index (the object schemata may be in an entirely different order) - for (auto& info : realm->_info) { - if (info.second.observedObjects.empty()) { - continue; - } - size_t ndx = info.second.table()->get_index_in_group(); - if (ndx >= observers.size()) { - observers.resize(std::max(observers.size() * 2, ndx + 1)); - } - observers[ndx] = &info.second.observedObjects; - } - - // No need for change tracking if no objects are observed - if (observers.empty()) { - block(); - return; - } - - struct change { - RLMObservationInfo *info; - __unsafe_unretained NSString *property; - NSMutableIndexSet *indexes; - }; - - std::vector changes; - std::vector invalidated; - - // This callback is called by core with a list of row deletions and - // resulting link nullifications immediately before things are deleted and nullified - realm.group.set_cascade_notification_handler([&](realm::Group::CascadeNotification const& cs) { - for (auto const& link : cs.links) { - size_t table_ndx = link.origin_table->get_index_in_group(); - if (table_ndx >= observers.size() || !observers[table_ndx]) { - // The modified table has no observers - continue; - } - - for (auto observer : *observers[table_ndx]) { - if (!observer->isForRow(link.origin_row_ndx)) { - continue; - } - - NSString *name = observer->columnName(link.origin_col_ndx); - if (observer->getRow().get_table()->get_column_type(link.origin_col_ndx) != type_LinkList) { - changes.push_back({observer, name}); - continue; - } - - auto c = find_if(begin(changes), end(changes), [&](auto const& c) { - return c.info == observer && c.property == name; - }); - if (c == end(changes)) { - changes.push_back({observer, name, [NSMutableIndexSet new]}); - c = prev(end(changes)); - } - - // We know what row index is being removed from the LinkView, - // but what we actually want is the indexes in the LinkView that - // are going away - auto linkview = observer->getRow().get_linklist(link.origin_col_ndx); - size_t start = 0, index; - while ((index = linkview->find(link.old_target_row_ndx, start)) != realm::not_found) { - [c->indexes addIndex:index]; - start = index + 1; - } - } - } - - for (auto const& row : cs.rows) { - if (row.table_ndx >= observers.size() || !observers[row.table_ndx]) { - // The modified table has no observers - continue; - } - - for (auto observer : *observers[row.table_ndx]) { - if (observer->isForRow(row.row_ndx)) { - invalidated.push_back(observer); - break; - } - } - } - - // The relative order of these loops is very important - for (auto info : invalidated) { - info->willChange(RLMInvalidatedKey); - } - for (auto const& change : changes) { - change.info->willChange(change.property, NSKeyValueChangeRemoval, change.indexes); - } - for (auto info : invalidated) { - info->prepareForInvalidation(); - } - }); - - try { - block(); - } - catch (...) { - realm.group.set_cascade_notification_handler(nullptr); - throw; - } - - for (auto const& change : reverse(changes)) { - change.info->didChange(change.property, NSKeyValueChangeRemoval, change.indexes); - } - for (auto info : reverse(invalidated)) { - info->didChange(RLMInvalidatedKey); - } - - realm.group.set_cascade_notification_handler(nullptr); -} - -namespace { -template -void forEach(realm::BindingContext::ObserverState const& state, Func&& func) { - for (size_t i = 0, size = state.changes.size(); i < size; ++i) { - if (state.changes[i].kind != realm::BindingContext::ColumnInfo::Kind::None) { - func(i, state.changes[i], static_cast(state.info)); - } - } -} -} - -std::vector RLMGetObservedRows(RLMSchemaInfo const& schema) { - std::vector observers; - for (auto& table : schema) { - for (auto info : table.second.observedObjects) { - auto const& row = info->getRow(); - if (!row.is_attached()) - continue; - observers.push_back({ - row.get_table()->get_index_in_group(), - row.get_index(), - info}); - } - } - sort(begin(observers), end(observers)); - return observers; -} - -static NSKeyValueChange convert(realm::BindingContext::ColumnInfo::Kind kind) { - switch (kind) { - case realm::BindingContext::ColumnInfo::Kind::None: - case realm::BindingContext::ColumnInfo::Kind::SetAll: - return NSKeyValueChangeSetting; - case realm::BindingContext::ColumnInfo::Kind::Set: - return NSKeyValueChangeReplacement; - case realm::BindingContext::ColumnInfo::Kind::Insert: - return NSKeyValueChangeInsertion; - case realm::BindingContext::ColumnInfo::Kind::Remove: - return NSKeyValueChangeRemoval; - } -} - -static NSIndexSet *convert(realm::IndexSet const& in, NSMutableIndexSet *out) { - if (in.empty()) { - return nil; - } - - [out removeAllIndexes]; - for (auto range : in) { - [out addIndexesInRange:{range.first, range.second - range.first}]; - } - return out; -} - -void RLMWillChange(std::vector const& observed, - std::vector const& invalidated) { - for (auto info : invalidated) { - static_cast(info)->willChange(RLMInvalidatedKey); - } - if (!observed.empty()) { - NSMutableIndexSet *indexes = [NSMutableIndexSet new]; - for (auto const& o : observed) { - forEach(o, [&](size_t, auto const& change, RLMObservationInfo *info) { - info->willChange(info->columnName(change.initial_column_index), - convert(change.kind), convert(change.indices, indexes)); - }); - } - } - for (auto info : invalidated) { - static_cast(info)->prepareForInvalidation(); - } -} - -void RLMDidChange(std::vector const& observed, - std::vector const& invalidated) { - if (!observed.empty()) { - // Loop in reverse order to avoid O(N^2) behavior in Foundation - NSMutableIndexSet *indexes = [NSMutableIndexSet new]; - for (auto const& o : reverse(observed)) { - forEach(o, [&](size_t i, auto const& change, RLMObservationInfo *info) { - info->didChange(info->columnName(i), convert(change.kind), convert(change.indices, indexes)); - }); - } - } - for (auto const& info : reverse(invalidated)) { - static_cast(info)->didChange(RLMInvalidatedKey); - } -} diff --git a/Lesson14/Pods/Realm/Realm/RLMOptionalBase.mm b/Lesson14/Pods/Realm/Realm/RLMOptionalBase.mm deleted file mode 100644 index 2617f0b..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMOptionalBase.mm +++ /dev/null @@ -1,163 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMOptionalBase.h" - -#import "RLMAccessor.hpp" -#import "RLMObject_Private.hpp" -#import "RLMProperty.h" -#import "RLMUtil.hpp" -#import "object.hpp" - -namespace { -struct OptionalBase { - virtual id get() = 0; - virtual void set(id) = 0; - virtual ~OptionalBase() = default; -}; - -class UnmanagedOptional : public OptionalBase { -public: - id get() override { - return _value; - } - - void set(__unsafe_unretained const id newValue) override { - @autoreleasepool { - RLMObjectBase *object = _parent; - [object willChangeValueForKey:_property]; - _value = newValue; - [object didChangeValueForKey:_property]; - } - } - - void attach(__unsafe_unretained RLMObjectBase *const obj, NSString *property) { - if (!_property) { - _property = property; - _parent = obj; - } - } - -private: - id _value; - NSString *_property; - __weak RLMObjectBase *_parent; - -}; - -class ManagedOptional : public OptionalBase { -public: - ManagedOptional(RLMObjectBase *obj, RLMProperty *prop) - : _realm(obj->_realm) - , _object(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row) - , _propertyName(prop.name.UTF8String) - , _ctx(*obj->_info) - { - } - - id get() override { - return _object.get_property_value(_ctx, _propertyName); - } - - void set(__unsafe_unretained id const value) override { - _object.set_property_value(_ctx, _propertyName, value ?: NSNull.null); - } - -private: - // We have to hold onto a strong reference to the Realm as - // RLMAccessorContext holds a non-retaining one. - __unused RLMRealm *_realm; - realm::Object _object; - std::string _propertyName; - RLMAccessorContext _ctx; -}; -} // anonymous namespace - -@interface RLMOptionalBase () { - std::unique_ptr _impl; -} -@end - -@implementation RLMOptionalBase -- (instancetype)init { - return self; -} - -- (BOOL)isKindOfClass:(Class)aClass { - return [RLMGetOptional(self) isKindOfClass:aClass] || RLMIsKindOfClass(object_getClass(self), aClass); -} - -- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { - return [RLMGetOptional(self) methodSignatureForSelector:sel]; -} - -- (void)forwardInvocation:(NSInvocation *)invocation { - [invocation invokeWithTarget:RLMGetOptional(self)]; -} - -- (id)forwardingTargetForSelector:(__unused SEL)sel { - return RLMGetOptional(self); -} - -- (BOOL)respondsToSelector:(SEL)aSelector { - return [RLMGetOptional(self) respondsToSelector:aSelector]; -} - -- (void)doesNotRecognizeSelector:(SEL)aSelector { - [RLMGetOptional(self) doesNotRecognizeSelector:aSelector]; -} - -id RLMGetOptional(__unsafe_unretained RLMOptionalBase *const self) { - try { - return self->_impl ? RLMCoerceToNil(self->_impl->get()) : nil; - } - catch (std::exception const& err) { - @throw RLMException(err); - } -} - -void RLMSetOptional(__unsafe_unretained RLMOptionalBase *const self, __unsafe_unretained const id value) { - try { - if (!self->_impl && value) { - self->_impl.reset(new UnmanagedOptional); - } - if (self->_impl) { - self->_impl->set(value); - } - } - catch (std::exception const& err) { - @throw RLMException(err); - } -} - -void RLMInitializeManagedOptional(__unsafe_unretained RLMOptionalBase *const self, - __unsafe_unretained RLMObjectBase *const parent, - __unsafe_unretained RLMProperty *const prop) { - REALM_ASSERT(parent->_realm); - self->_impl.reset(new ManagedOptional(parent, prop)); -} - -void RLMInitializeUnmanagedOptional(__unsafe_unretained RLMOptionalBase *const self, - __unsafe_unretained RLMObjectBase *const parent, - __unsafe_unretained RLMProperty *const prop) { - if (!self->_impl) { - self->_impl.reset(new UnmanagedOptional); - } - static_cast(*self->_impl).attach(parent, prop.name); -} -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMPredicateUtil.mm b/Lesson14/Pods/Realm/Realm/RLMPredicateUtil.mm deleted file mode 100644 index 830a9b2..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMPredicateUtil.mm +++ /dev/null @@ -1,127 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMPredicateUtil.hpp" - -#include - -// NSConditionalExpressionType is new in OS X 10.11 and iOS 9.0 -#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#define CONDITIONAL_EXPRESSION_DECLARED (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) -#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#define CONDITIONAL_EXPRESSION_DECLARED (__IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) -#else -#define CONDITIONAL_EXPRESSION_DECLARED 0 -#endif - -#if !CONDITIONAL_EXPRESSION_DECLARED - -#define NSConditionalExpressionType 20 - -@interface NSExpression (NewIn1011And90) -+ (NSExpression *)expressionForConditional:(NSPredicate *)predicate trueExpression:(NSExpression *)trueExpression falseExpression:(NSExpression *)falseExpression; -- (NSExpression *)trueExpression; -- (NSExpression *)falseExpression; -@end - -#endif - -namespace { - -struct PredicateExpressionTransformer { - PredicateExpressionTransformer(ExpressionVisitor visitor) : m_visitor(visitor) { } - - NSExpression *visit(NSExpression *expression) const; - NSPredicate *visit(NSPredicate *predicate) const; - - ExpressionVisitor m_visitor; -}; - -NSExpression *PredicateExpressionTransformer::visit(NSExpression *expression) const { - expression = m_visitor(expression); - - switch (expression.expressionType) { - case NSFunctionExpressionType: { - NSMutableArray *arguments = [NSMutableArray array]; - for (NSExpression *argument in expression.arguments) { - [arguments addObject:visit(argument)]; - } - if (expression.operand) { - return [NSExpression expressionForFunction:visit(expression.operand) selectorName:expression.function arguments:arguments]; - } else { - return [NSExpression expressionForFunction:expression.function arguments:arguments]; - } - } - - case NSUnionSetExpressionType: - return [NSExpression expressionForUnionSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; - case NSIntersectSetExpressionType: - return [NSExpression expressionForIntersectSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; - case NSMinusSetExpressionType: - return [NSExpression expressionForMinusSet:visit(expression.leftExpression) with:visit(expression.rightExpression)]; - - case NSSubqueryExpressionType: { - NSExpression *collection = expression.collection; - // NSExpression.collection is declared as id, but appears to always hold an NSExpression for subqueries. - REALM_ASSERT([collection isKindOfClass:[NSExpression class]]); - return [NSExpression expressionForSubquery:visit(collection) usingIteratorVariable:expression.variable predicate:visit(expression.predicate)]; - } - - case NSAggregateExpressionType: { - NSMutableArray *subexpressions = [NSMutableArray array]; - for (NSExpression *subexpression in expression.collection) { - [subexpressions addObject:visit(subexpression)]; - } - return [NSExpression expressionForAggregate:subexpressions]; - } - - case NSConditionalExpressionType: -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpartial-availability" - return [NSExpression expressionForConditional:visit(expression.predicate) trueExpression:visit(expression.trueExpression) falseExpression:visit(expression.falseExpression)]; -#pragma clang diagnostic pop - - default: - // The remaining expression types do not contain nested expressions or predicates. - return expression; - } -} - -NSPredicate *PredicateExpressionTransformer::visit(NSPredicate *predicate) const { - if ([predicate isKindOfClass:[NSCompoundPredicate class]]) { - NSCompoundPredicate *compoundPredicate = (NSCompoundPredicate *)predicate; - NSMutableArray *subpredicates = [NSMutableArray array]; - for (NSPredicate *subpredicate in compoundPredicate.subpredicates) { - [subpredicates addObject:visit(subpredicate)]; - } - return [[NSCompoundPredicate alloc] initWithType:compoundPredicate.compoundPredicateType subpredicates:subpredicates]; - } - if ([predicate isKindOfClass:[NSComparisonPredicate class]]) { - NSComparisonPredicate *comparisonPredicate = (NSComparisonPredicate *)predicate; - NSExpression *leftExpression = visit(comparisonPredicate.leftExpression); - NSExpression *rightExpression = visit(comparisonPredicate.rightExpression); - return [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression:rightExpression modifier:comparisonPredicate.comparisonPredicateModifier type:comparisonPredicate.predicateOperatorType options:comparisonPredicate.options]; - } - return predicate; -} - -} // anonymous namespace - -NSPredicate *transformPredicate(NSPredicate *predicate, ExpressionVisitor visitor) { - PredicateExpressionTransformer transformer(visitor); - return transformer.visit(predicate); -} diff --git a/Lesson14/Pods/Realm/Realm/RLMProperty.mm b/Lesson14/Pods/Realm/Realm/RLMProperty.mm deleted file mode 100644 index 7b4e5ec..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMProperty.mm +++ /dev/null @@ -1,622 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMProperty_Private.hpp" - -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObject.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObject_Private.h" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" -#import "RLMUtil.hpp" - -#import "property.hpp" - -static_assert((int)RLMPropertyTypeInt == (int)realm::PropertyType::Int, ""); -static_assert((int)RLMPropertyTypeBool == (int)realm::PropertyType::Bool, ""); -static_assert((int)RLMPropertyTypeFloat == (int)realm::PropertyType::Float, ""); -static_assert((int)RLMPropertyTypeDouble == (int)realm::PropertyType::Double, ""); -static_assert((int)RLMPropertyTypeString == (int)realm::PropertyType::String, ""); -static_assert((int)RLMPropertyTypeData == (int)realm::PropertyType::Data, ""); -static_assert((int)RLMPropertyTypeDate == (int)realm::PropertyType::Date, ""); -static_assert((int)RLMPropertyTypeObject == (int)realm::PropertyType::Object, ""); - -BOOL RLMPropertyTypeIsComputed(RLMPropertyType propertyType) { - return propertyType == RLMPropertyTypeLinkingObjects; -} - -// Swift obeys the ARC naming conventions for method families (except for init) -// but the end result doesn't really work (using KVC on a method returning a -// retained value results in a leak, but not returning a retained value results -// in crashes). Objective-C makes properties with naming fitting the method -// families a compile error, so we just disallow them in Swift as well. -// http://clang.llvm.org/docs/AutomaticReferenceCounting.html#arc-method-families -void RLMValidateSwiftPropertyName(NSString *name) { - // To belong to a method family, the property name must begin with the family - // name followed by a non-lowercase letter (or nothing), with an optional - // leading underscore - const char *str = name.UTF8String; - if (str[0] == '_') - ++str; - auto nameSize = strlen(str); - - // Note that "init" is deliberately not in this list because Swift does not - // infer family membership for it. - for (auto family : {"alloc", "new", "copy", "mutableCopy"}) { - auto familySize = strlen(family); - if (nameSize < familySize || !std::equal(str, str + familySize, family)) { - continue; - } - if (familySize == nameSize || !islower(str[familySize])) { - @throw RLMException(@"Property names beginning with '%s' are not " - "supported. Swift follows ARC's ownership " - "rules for methods based on their name, which " - "results in memory leaks when accessing " - "properties which return retained values via KVC.", - family); - } - return; - } -} - -static bool rawTypeShouldBeTreatedAsComputedProperty(NSString *rawType) { - return [rawType isEqualToString:@"@\"RLMLinkingObjects\""] || [rawType hasPrefix:@"@\"RLMLinkingObjects<"]; -} - -@implementation RLMProperty - -+ (instancetype)propertyForObjectStoreProperty:(const realm::Property &)prop { - auto ret = [[RLMProperty alloc] initWithName:@(prop.name.c_str()) - type:static_cast(prop.type & ~realm::PropertyType::Flags) - objectClassName:prop.object_type.length() ? @(prop.object_type.c_str()) : nil - linkOriginPropertyName:prop.link_origin_property_name.length() ? @(prop.link_origin_property_name.c_str()) : nil - indexed:prop.is_indexed - optional:is_nullable(prop.type)]; - if (is_array(prop.type)) { - ret->_array = true; - } - if (!prop.public_name.empty()) { - ret->_columnName = ret->_name; - ret->_name = @(prop.public_name.c_str()); - } - return ret; -} - -- (instancetype)initWithName:(NSString *)name - type:(RLMPropertyType)type - objectClassName:(NSString *)objectClassName - linkOriginPropertyName:(NSString *)linkOriginPropertyName - indexed:(BOOL)indexed - optional:(BOOL)optional { - self = [super init]; - if (self) { - _name = name; - _type = type; - _objectClassName = objectClassName; - _linkOriginPropertyName = linkOriginPropertyName; - _indexed = indexed; - _optional = optional; - [self updateAccessors]; - } - - return self; -} - -- (void)setName:(NSString *)name { - _name = name; - [self updateAccessors]; -} - -- (void)updateAccessors { - // populate getter/setter names if generic - if (!_getterName) { - _getterName = _name; - } - if (!_setterName) { - // Objective-C setters only capitalize the first letter of the property name if it falls between 'a' and 'z' - int asciiCode = [_name characterAtIndex:0]; - BOOL shouldUppercase = asciiCode >= 'a' && asciiCode <= 'z'; - NSString *firstChar = [_name substringToIndex:1]; - firstChar = shouldUppercase ? firstChar.uppercaseString : firstChar; - _setterName = [NSString stringWithFormat:@"set%@%@:", firstChar, [_name substringFromIndex:1]]; - } - - _getterSel = NSSelectorFromString(_getterName); - _setterSel = NSSelectorFromString(_setterName); -} - -static realm::util::Optional typeFromProtocolString(const char *type) { - if (strncmp(type, "RLM", 3)) { - return realm::none; - } - type += 3; - if (strcmp(type, "Int>\"") == 0) { - return RLMPropertyTypeInt; - } - if (strcmp(type, "Float>\"") == 0) { - return RLMPropertyTypeFloat; - } - if (strcmp(type, "Double>\"") == 0) { - return RLMPropertyTypeDouble; - } - if (strcmp(type, "Bool>\"") == 0) { - return RLMPropertyTypeBool; - } - if (strcmp(type, "String>\"") == 0) { - return RLMPropertyTypeString; - } - if (strcmp(type, "Data>\"") == 0) { - return RLMPropertyTypeData; - } - if (strcmp(type, "Date>\"") == 0) { - return RLMPropertyTypeDate; - } - return realm::none; -} - -// determine RLMPropertyType from objc code - returns true if valid type was found/set -- (BOOL)setTypeFromRawType:(NSString *)rawType { - const char *code = rawType.UTF8String; - switch (*code) { - case 's': // short - case 'i': // int - case 'l': // long - case 'q': // long long - _type = RLMPropertyTypeInt; - return YES; - case 'f': - _type = RLMPropertyTypeFloat; - return YES; - case 'd': - _type = RLMPropertyTypeDouble; - return YES; - case 'c': // BOOL is stored as char - since rlm has no char type this is ok - case 'B': - _type = RLMPropertyTypeBool; - return YES; - case '@': - break; - default: - return NO; - } - - _optional = true; - static const char arrayPrefix[] = "@\"RLMArray<"; - static const int arrayPrefixLen = sizeof(arrayPrefix) - 1; - - static const char numberPrefix[] = "@\"NSNumber<"; - static const int numberPrefixLen = sizeof(numberPrefix) - 1; - - static const char linkingObjectsPrefix[] = "@\"RLMLinkingObjects"; - static const int linkingObjectsPrefixLen = sizeof(linkingObjectsPrefix) - 1; - - if (strcmp(code, "@\"NSString\"") == 0) { - _type = RLMPropertyTypeString; - } - else if (strcmp(code, "@\"NSDate\"") == 0) { - _type = RLMPropertyTypeDate; - } - else if (strcmp(code, "@\"NSData\"") == 0) { - _type = RLMPropertyTypeData; - } - else if (strncmp(code, arrayPrefix, arrayPrefixLen) == 0) { - _array = true; - if (auto type = typeFromProtocolString(code + arrayPrefixLen)) { - _type = *type; - return YES; - } - - // get object class from type string - @"RLMArray" - _objectClassName = [[NSString alloc] initWithBytes:code + arrayPrefixLen - length:strlen(code + arrayPrefixLen) - 2 // drop trailing >" - encoding:NSUTF8StringEncoding]; - - if ([RLMSchema classForString:_objectClassName]) { - _optional = false; - _type = RLMPropertyTypeObject; - return YES; - } - @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. " - @"RLMArrays can only contain instances of RLMObject subclasses. " - @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName); - } - else if (strncmp(code, numberPrefix, numberPrefixLen) == 0) { - auto type = typeFromProtocolString(code + numberPrefixLen); - if (type && (*type == RLMPropertyTypeInt || *type == RLMPropertyTypeFloat || *type == RLMPropertyTypeDouble || *type == RLMPropertyTypeBool)) { - _type = *type; - return YES; - } - @throw RLMException(@"Property '%@' is of type %s which is not a supported NSNumber object type. " - @"NSNumbers can only be RLMInt, RLMFloat, RLMDouble, and RLMBool at the moment. " - @"See https://realm.io/docs/objc/latest for more information.", _name, code + 1); - } - else if (strncmp(code, linkingObjectsPrefix, linkingObjectsPrefixLen) == 0 && - (code[linkingObjectsPrefixLen] == '"' || code[linkingObjectsPrefixLen] == '<')) { - _type = RLMPropertyTypeLinkingObjects; - _optional = false; - _array = true; - - if (!_objectClassName || !_linkOriginPropertyName) { - @throw RLMException(@"Property '%@' is of type RLMLinkingObjects but +linkingObjectsProperties did not specify the class " - "or property that is the origin of the link.", _name); - } - - // If the property was declared with a protocol indicating the contained type, validate that it matches - // the class from the dictionary returned by +linkingObjectsProperties. - if (code[linkingObjectsPrefixLen] == '<') { - NSString *classNameFromProtocol = [[NSString alloc] initWithBytes:code + linkingObjectsPrefixLen + 1 - length:strlen(code + linkingObjectsPrefixLen) - 3 // drop trailing >" - encoding:NSUTF8StringEncoding]; - if (![_objectClassName isEqualToString:classNameFromProtocol]) { - @throw RLMException(@"Property '%@' was declared with type RLMLinkingObjects<%@>, but a conflicting " - "class name of '%@' was returned by +linkingObjectsProperties.", _name, - classNameFromProtocol, _objectClassName); - } - } - } - else if (strcmp(code, "@\"NSNumber\"") == 0) { - @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: NSNumber.", _name); - } - else if (strcmp(code, "@\"RLMArray\"") == 0) { - @throw RLMException(@"Property '%@' requires a protocol defining the contained type - example: RLMArray.", _name); - } - else { - NSString *className; - Class cls = nil; - if (code[1] == '\0') { - className = @"id"; - } - else { - // for objects strip the quotes and @ - className = [rawType substringWithRange:NSMakeRange(2, rawType.length-3)]; - cls = [RLMSchema classForString:className]; - } - - if (!cls) { - @throw RLMException(@"Property '%@' is declared as '%@', which is not a supported RLMObject property type. " - @"All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, or subclasses of RLMObject. " - @"See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.", _name, className); - } - - _type = RLMPropertyTypeObject; - _optional = true; - _objectClassName = [cls className] ?: className; - } - return YES; -} - -- (void)parseObjcProperty:(objc_property_t)property - readOnly:(bool *)readOnly - computed:(bool *)computed - rawType:(NSString **)rawType { - unsigned int count; - objc_property_attribute_t *attrs = property_copyAttributeList(property, &count); - - *computed = true; - for (size_t i = 0; i < count; ++i) { - switch (*attrs[i].name) { - case 'T': - *rawType = @(attrs[i].value); - break; - case 'R': - *readOnly = true; - break; - case 'G': - _getterName = @(attrs[i].value); - break; - case 'S': - _setterName = @(attrs[i].value); - break; - case 'V': // backing ivar name - *computed = false; - break; - - case '&': - // retain/assign - break; - case 'C': - // copy - break; - case 'D': - // dynamic - break; - case 'N': - // nonatomic - break; - case 'P': - // GC'able - break; - case 'W': - // weak - break; - default: - break; - } - } - free(attrs); -} - -- (instancetype)initSwiftPropertyWithName:(NSString *)name - indexed:(BOOL)indexed - linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor - property:(objc_property_t)property - instance:(RLMObject *)obj { - self = [super init]; - if (!self) { - return nil; - } - - RLMValidateSwiftPropertyName(name); - - _name = name; - _indexed = indexed; - - if (linkPropertyDescriptor) { - _objectClassName = [linkPropertyDescriptor.objectClass className]; - _linkOriginPropertyName = linkPropertyDescriptor.propertyName; - } - - NSString *rawType; - bool readOnly = false; - bool isComputed = false; - [self parseObjcProperty:property readOnly:&readOnly computed:&isComputed rawType:&rawType]; - - // Swift sometimes doesn't explicitly set the ivar name in the metadata, so check if - // there's an ivar with the same name as the property. - if (!readOnly && isComputed && class_getInstanceVariable([obj class], name.UTF8String)) { - isComputed = false; - } - - // Check if there's a storage ivar for a lazy property in this name. We don't honor - // @lazy in managed objects, but allow it for unmanaged objects which are - // subclasses of RLMObject (but not RealmSwift.Object). It's unclear if there's a - // good reason for this difference. - if (!readOnly && isComputed) { - // Xcode 10 and earlier - NSString *backingPropertyName = [NSString stringWithFormat:@"%@.storage", name]; - isComputed = !class_getInstanceVariable([obj class], backingPropertyName.UTF8String); - } - if (!readOnly && isComputed) { - // Xcode 11 - NSString *backingPropertyName = [NSString stringWithFormat:@"$__lazy_storage_$_%@", name]; - isComputed = !class_getInstanceVariable([obj class], backingPropertyName.UTF8String); - } - - if (readOnly || isComputed) { - return nil; - } - - id propertyValue = [obj valueForKey:_name]; - - // FIXME: temporarily workaround added since Objective-C generics used in Swift show up as `@` - // * broken starting in Swift 3.0 Xcode 8 b1 - // * tested to still be broken in Swift 3.0 Xcode 8 b6 - // * if the Realm Objective-C Swift tests pass with this removed, it's been fixed - // * once it has been fixed, remove this entire conditional block (contents included) entirely - // * Bug Report: SR-2031 https://bugs.swift.org/browse/SR-2031 - if ([rawType isEqualToString:@"@"]) { - if (propertyValue) { - rawType = [NSString stringWithFormat:@"@\"%@\"", [propertyValue class]]; - } else if (linkPropertyDescriptor) { - // we're going to naively assume that the user used the correct type since we can't check it - rawType = @"@\"RLMLinkingObjects\""; - } - } - - // convert array types to objc variant - if ([rawType isEqualToString:@"@\"RLMArray\""]) { - RLMArray *value = propertyValue; - _type = value.type; - _optional = value.optional; - _array = true; - _objectClassName = value.objectClassName; - if (_type == RLMPropertyTypeObject && ![RLMSchema classForString:_objectClassName]) { - @throw RLMException(@"Property '%@' is of type 'RLMArray<%@>' which is not a supported RLMArray object type. " - @"RLMArrays can only contain instances of RLMObject subclasses. " - @"See https://realm.io/docs/objc/latest/#to-many for more information.", _name, _objectClassName); - } - } - else if ([rawType isEqualToString:@"@\"NSNumber\""]) { - const char *numberType = [propertyValue objCType]; - if (!numberType) { - @throw RLMException(@"Can't persist NSNumber without default value: use a Swift-native number type or provide a default value."); - } - _optional = true; - switch (*numberType) { - case 'i': case 'l': case 'q': - _type = RLMPropertyTypeInt; - break; - case 'f': - _type = RLMPropertyTypeFloat; - break; - case 'd': - _type = RLMPropertyTypeDouble; - break; - case 'B': case 'c': - _type = RLMPropertyTypeBool; - break; - default: - @throw RLMException(@"Can't persist NSNumber of type '%s': only integers, floats, doubles, and bools are currently supported.", numberType); - } - } - else if (![self setTypeFromRawType:rawType]) { - @throw RLMException(@"Can't persist property '%@' with incompatible type. " - "Add to Object.ignoredProperties() class method to ignore.", - self.name); - } - - if ([rawType isEqualToString:@"c"]) { - // Check if it's a BOOL or Int8 by trying to set it to 2 and seeing if - // it actually sets it to 1. - [obj setValue:@2 forKey:name]; - NSNumber *value = [obj valueForKey:name]; - _type = value.intValue == 2 ? RLMPropertyTypeInt : RLMPropertyTypeBool; - } - - // update getter/setter names - [self updateAccessors]; - - return self; -} - -- (instancetype)initWithName:(NSString *)name - indexed:(BOOL)indexed - linkPropertyDescriptor:(RLMPropertyDescriptor *)linkPropertyDescriptor - property:(objc_property_t)property -{ - self = [super init]; - if (!self) { - return nil; - } - - _name = name; - _indexed = indexed; - - if (linkPropertyDescriptor) { - _objectClassName = [linkPropertyDescriptor.objectClass className]; - _linkOriginPropertyName = linkPropertyDescriptor.propertyName; - } - - NSString *rawType; - bool isReadOnly = false; - bool isComputed = false; - [self parseObjcProperty:property readOnly:&isReadOnly computed:&isComputed rawType:&rawType]; - bool shouldBeTreatedAsComputedProperty = rawTypeShouldBeTreatedAsComputedProperty(rawType); - if ((isReadOnly || isComputed) && !shouldBeTreatedAsComputedProperty) { - return nil; - } - - if (![self setTypeFromRawType:rawType]) { - @throw RLMException(@"Can't persist property '%@' with incompatible type. " - "Add to ignoredPropertyNames: method to ignore.", self.name); - } - - if (!isReadOnly && shouldBeTreatedAsComputedProperty) { - @throw RLMException(@"Property '%@' must be declared as readonly as %@ properties cannot be written to.", - self.name, RLMTypeToString(_type)); - } - - // update getter/setter names - [self updateAccessors]; - - return self; -} - -- (id)copyWithZone:(NSZone *)zone { - RLMProperty *prop = [[RLMProperty allocWithZone:zone] init]; - prop->_name = _name; - prop->_columnName = _columnName; - prop->_type = _type; - prop->_objectClassName = _objectClassName; - prop->_array = _array; - prop->_indexed = _indexed; - prop->_getterName = _getterName; - prop->_setterName = _setterName; - prop->_getterSel = _getterSel; - prop->_setterSel = _setterSel; - prop->_isPrimary = _isPrimary; - prop->_swiftIvar = _swiftIvar; - prop->_optional = _optional; - prop->_linkOriginPropertyName = _linkOriginPropertyName; - return prop; -} - -- (RLMProperty *)copyWithNewName:(NSString *)name { - RLMProperty *prop = [self copy]; - prop.name = name; - return prop; -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[RLMProperty class]]) { - return NO; - } - - return [self isEqualToProperty:object]; -} - -- (BOOL)isEqualToProperty:(RLMProperty *)property { - return _type == property->_type - && _indexed == property->_indexed - && _isPrimary == property->_isPrimary - && _optional == property->_optional - && [_name isEqualToString:property->_name] - && (_objectClassName == property->_objectClassName || [_objectClassName isEqualToString:property->_objectClassName]) - && (_linkOriginPropertyName == property->_linkOriginPropertyName || - [_linkOriginPropertyName isEqualToString:property->_linkOriginPropertyName]); -} - -- (NSString *)description { - return [NSString stringWithFormat: - @"%@ {\n" - "\ttype = %@;\n" - "\tobjectClassName = %@;\n" - "\tlinkOriginPropertyName = %@;\n" - "\tindexed = %@;\n" - "\tisPrimary = %@;\n" - "\tarray = %@;\n" - "\toptional = %@;\n" - "}", - self.name, RLMTypeToString(self.type), self.objectClassName, - self.linkOriginPropertyName, - self.indexed ? @"YES" : @"NO", - self.isPrimary ? @"YES" : @"NO", - self.array ? @"YES" : @"NO", - self.optional ? @"YES" : @"NO"]; -} - -- (NSString *)columnName { - return _columnName ?: _name; -} - -- (realm::Property)objectStoreCopy:(RLMSchema *)schema { - realm::Property p; - p.name = self.columnName.UTF8String; - if (_objectClassName) { - RLMObjectSchema *targetSchema = schema[_objectClassName]; - p.object_type = (targetSchema.objectName ?: _objectClassName).UTF8String; - if (_linkOriginPropertyName) { - p.link_origin_property_name = (targetSchema[_linkOriginPropertyName].columnName ?: _linkOriginPropertyName).UTF8String; - } - } - p.is_indexed = static_cast(_indexed); - p.type = static_cast(_type); - if (_array) { - p.type |= realm::PropertyType::Array; - } - if (_optional) { - p.type |= realm::PropertyType::Nullable; - } - return p; -} - -@end - -@implementation RLMPropertyDescriptor - -+ (instancetype)descriptorWithClass:(Class)objectClass propertyName:(NSString *)propertyName -{ - RLMPropertyDescriptor *descriptor = [[RLMPropertyDescriptor alloc] init]; - descriptor->_objectClass = objectClass; - descriptor->_propertyName = propertyName; - return descriptor; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMQueryUtil.mm b/Lesson14/Pods/Realm/Realm/RLMQueryUtil.mm deleted file mode 100644 index 93fe03b..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMQueryUtil.mm +++ /dev/null @@ -1,1490 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMQueryUtil.hpp" - -#import "RLMArray.h" -#import "RLMObjectSchema_Private.h" -#import "RLMObject_Private.hpp" -#import "RLMPredicateUtil.hpp" -#import "RLMProperty_Private.h" -#import "RLMSchema.h" -#import "RLMUtil.hpp" - -#import "object_store.hpp" -#import "results.hpp" - -#include -#include -#include -#include - -using namespace realm; - -NSString * const RLMPropertiesComparisonTypeMismatchException = @"RLMPropertiesComparisonTypeMismatchException"; -NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException = @"RLMUnsupportedTypesFoundInPropertyComparisonException"; - -NSString * const RLMPropertiesComparisonTypeMismatchReason = @"Property type mismatch between %@ and %@"; -NSString * const RLMUnsupportedTypesFoundInPropertyComparisonReason = @"Comparison between %@ and %@"; - -// small helper to create the many exceptions thrown when parsing predicates -static NSException *RLMPredicateException(NSString *name, NSString *format, ...) { - va_list args; - va_start(args, format); - NSString *reason = [[NSString alloc] initWithFormat:format arguments:args]; - va_end(args); - - return [NSException exceptionWithName:name reason:reason userInfo:nil]; -} - -// check a precondition and throw an exception if it is not met -// this should be used iff the condition being false indicates a bug in the caller -// of the function checking its preconditions -static void RLMPrecondition(bool condition, NSString *name, NSString *format, ...) { - if (__builtin_expect(condition, 1)) { - return; - } - - va_list args; - va_start(args, format); - NSString *reason = [[NSString alloc] initWithFormat:format arguments:args]; - va_end(args); - - @throw [NSException exceptionWithName:name reason:reason userInfo:nil]; -} - -// return the property for a validated column name -RLMProperty *RLMValidatedProperty(RLMObjectSchema *desc, NSString *columnName) { - RLMProperty *prop = desc[columnName]; - RLMPrecondition(prop, @"Invalid property name", - @"Property '%@' not found in object of type '%@'", columnName, desc.className); - return prop; -} - -namespace { -BOOL RLMPropertyTypeIsNumeric(RLMPropertyType propertyType) { - switch (propertyType) { - case RLMPropertyTypeInt: - case RLMPropertyTypeFloat: - case RLMPropertyTypeDouble: - return YES; - default: - return NO; - } -} - -// Equal and ContainsSubstring are used by QueryBuilder::add_string_constraint as the comparator -// for performing diacritic-insensitive comparisons. - -bool equal(CFStringCompareFlags options, StringData v1, StringData v2) -{ - if (v1.is_null() || v2.is_null()) { - return v1.is_null() == v2.is_null(); - } - - auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(), - kCFStringEncodingUTF8, false, kCFAllocatorNull)); - auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(), - kCFStringEncodingUTF8, false, kCFAllocatorNull)); - - return CFStringCompare(s1.get(), s2.get(), options) == kCFCompareEqualTo; -} - -template -struct Equal { - using CaseSensitive = Equal; - using CaseInsensitive = Equal; - - bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const - { - REALM_ASSERT_DEBUG(v1_null == v1.is_null()); - REALM_ASSERT_DEBUG(v2_null == v2.is_null()); - - return equal(options, v1, v2); - } - - // FIXME: Consider the options. - static const char* description() { return "equal"; } -}; - -bool contains_substring(CFStringCompareFlags options, StringData v1, StringData v2) -{ - if (v2.is_null()) { - // Everything contains NULL - return true; - } - - if (v1.is_null()) { - // NULL contains nothing (except NULL, handled above) - return false; - } - - if (v2.size() == 0) { - // Everything (except NULL, handled above) contains the empty string - return true; - } - - auto s1 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v1.data(), v1.size(), - kCFStringEncodingUTF8, false, kCFAllocatorNull)); - auto s2 = util::adoptCF(CFStringCreateWithBytesNoCopy(kCFAllocatorSystemDefault, (const UInt8*)v2.data(), v2.size(), - kCFStringEncodingUTF8, false, kCFAllocatorNull)); - - return CFStringFind(s1.get(), s2.get(), options).location != kCFNotFound; -} - -template -struct ContainsSubstring { - using CaseSensitive = ContainsSubstring; - using CaseInsensitive = ContainsSubstring; - - bool operator()(StringData v1, StringData v2, bool v1_null, bool v2_null) const - { - REALM_ASSERT_DEBUG(v1_null == v1.is_null()); - REALM_ASSERT_DEBUG(v2_null == v2.is_null()); - - return contains_substring(options, v1, v2); - } - - // FIXME: Consider the options. - static const char* description() { return "contains"; } -}; - - -NSString *operatorName(NSPredicateOperatorType operatorType) -{ - switch (operatorType) { - case NSLessThanPredicateOperatorType: - return @"<"; - case NSLessThanOrEqualToPredicateOperatorType: - return @"<="; - case NSGreaterThanPredicateOperatorType: - return @">"; - case NSGreaterThanOrEqualToPredicateOperatorType: - return @">="; - case NSEqualToPredicateOperatorType: - return @"=="; - case NSNotEqualToPredicateOperatorType: - return @"!="; - case NSMatchesPredicateOperatorType: - return @"MATCHES"; - case NSLikePredicateOperatorType: - return @"LIKE"; - case NSBeginsWithPredicateOperatorType: - return @"BEGINSWITH"; - case NSEndsWithPredicateOperatorType: - return @"ENDSWITH"; - case NSInPredicateOperatorType: - return @"IN"; - case NSContainsPredicateOperatorType: - return @"CONTAINS"; - case NSBetweenPredicateOperatorType: - return @"BETWEEN"; - case NSCustomSelectorPredicateOperatorType: - return @"custom selector"; - } - - return [NSString stringWithFormat:@"unknown operator %lu", (unsigned long)operatorType]; -} - -Table& get_table(Group& group, RLMObjectSchema *objectSchema) -{ - return *ObjectStore::table_for_object_type(group, objectSchema.objectName.UTF8String); -} - -// A reference to a column within a query. Can be resolved to a Columns for use in query expressions. -class ColumnReference { -public: - ColumnReference(Query& query, Group& group, RLMSchema *schema, RLMProperty* property, const std::vector& links = {}) - : m_links(links), m_property(property), m_schema(schema), m_group(&group), m_query(&query), m_table(query.get_table().get()) - { - auto& table = walk_link_chain([](Table&, size_t, RLMPropertyType) { }); - m_index = table.get_column_index(m_property.columnName.UTF8String); - } - - template - auto resolve(SubQuery&&... subquery) const - { - static_assert(sizeof...(SubQuery) < 2, "resolve() takes at most one subquery"); - set_link_chain_on_table(); - if (type() != RLMPropertyTypeLinkingObjects) { - return m_table->template column(index(), std::forward(subquery)...); - } - else { - return resolve_backlink(std::forward(subquery)...); - } - } - - RLMProperty *property() const { return m_property; } - size_t index() const { return m_index; } - RLMPropertyType type() const { return property().type; } - Group& group() const { return *m_group; } - - RLMObjectSchema *link_target_object_schema() const - { - switch (type()) { - case RLMPropertyTypeObject: - case RLMPropertyTypeLinkingObjects: - return m_schema[property().objectClassName]; - default: - REALM_UNREACHABLE(); - } - } - - bool has_links() const { return m_links.size(); } - - bool has_any_to_many_links() const { - return std::any_of(begin(m_links), end(m_links), - [](RLMProperty *property) { return property.array; }); - } - - ColumnReference last_link_column() const { - REALM_ASSERT(!m_links.empty()); - return {*m_query, *m_group, m_schema, m_links.back(), {m_links.begin(), m_links.end() - 1}}; - } - - ColumnReference column_ignoring_links(Query& query) const { - return {query, *m_group, m_schema, m_property}; - } - -private: - template - auto resolve_backlink(SubQuery&&... subquery) const - { - // We actually just want `if constexpr (std::is_same::value) { ... }`, - // so fake it by tag-dispatching on the conditional - return do_resolve_backlink(std::is_same(), std::forward(subquery)...); - } - - template - auto do_resolve_backlink(std::true_type, SubQuery&&... subquery) const - { - return with_link_origin(m_property, [&](Table& table, size_t col) { - return m_table->template column(table, col, std::forward(subquery)...); - }); - } - - template - Columns do_resolve_backlink(std::false_type, SubQuery&&...) const - { - // This can't actually happen as we only call resolve_backlink() if - // it's RLMPropertyTypeLinkingObjects - __builtin_unreachable(); - } - - template - Table& walk_link_chain(Func&& func) const - { - auto table = m_query->get_table().get(); - for (const auto& link : m_links) { - if (link.type != RLMPropertyTypeLinkingObjects) { - auto index = table->get_column_index(link.columnName.UTF8String); - func(*table, index, link.type); - table = table->get_link_target(index).get(); - } - else { - with_link_origin(link, [&](Table& link_origin_table, size_t link_origin_column) { - func(link_origin_table, link_origin_column, link.type); - table = &link_origin_table; - }); - } - } - return *table; - } - - template - auto with_link_origin(RLMProperty *prop, Func&& func) const - { - RLMObjectSchema *link_origin_schema = m_schema[prop.objectClassName]; - Table& link_origin_table = get_table(*m_group, link_origin_schema); - NSString *column_name = link_origin_schema[prop.linkOriginPropertyName].columnName; - size_t link_origin_column = link_origin_table.get_column_index(column_name.UTF8String); - return func(link_origin_table, link_origin_column); - } - - void set_link_chain_on_table() const - { - walk_link_chain([&](Table& current_table, size_t column, RLMPropertyType type) { - if (type == RLMPropertyTypeLinkingObjects) { - m_table->backlink(current_table, column); - } - else { - m_table->link(column); - } - }); - } - - std::vector m_links; - RLMProperty *m_property; - RLMSchema *m_schema; - Group *m_group; - Query *m_query; - Table *m_table; - size_t m_index; -}; - -class CollectionOperation { -public: - enum Type { - Count, - Minimum, - Maximum, - Sum, - Average, - }; - - CollectionOperation(Type type, ColumnReference link_column, util::Optional column) - : m_type(type) - , m_link_column(std::move(link_column)) - , m_column(std::move(column)) - { - RLMPrecondition(m_link_column.property().array, - @"Invalid predicate", @"Collection operation can only be applied to a property of type RLMArray."); - - switch (m_type) { - case Count: - RLMPrecondition(!m_column, @"Invalid predicate", @"Result of @count does not have any properties."); - break; - case Minimum: - case Maximum: - case Sum: - case Average: - RLMPrecondition(m_column && RLMPropertyTypeIsNumeric(m_column->type()), @"Invalid predicate", - @"%@ can only be applied to a numeric property.", name_for_type(m_type)); - break; - } - } - - CollectionOperation(NSString *operationName, ColumnReference link_column, util::Optional column = util::none) - : CollectionOperation(type_for_name(operationName), std::move(link_column), std::move(column)) - { - } - - Type type() const { return m_type; } - const ColumnReference& link_column() const { return m_link_column; } - const ColumnReference& column() const { return *m_column; } - - void validate_comparison(id value) const { - switch (m_type) { - case Count: - case Average: - RLMPrecondition([value isKindOfClass:[NSNumber class]], @"Invalid operand", - @"%@ can only be compared with a numeric value.", name_for_type(m_type)); - break; - case Minimum: - case Maximum: - case Sum: - RLMPrecondition(RLMIsObjectValidForProperty(value, m_column->property()), @"Invalid operand", - @"%@ on a property of type %@ cannot be compared with '%@'", - name_for_type(m_type), RLMTypeToString(m_column->type()), value); - break; - } - } - - void validate_comparison(const ColumnReference& column) const { - switch (m_type) { - case Count: - RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand", - @"%@ can only be compared with a numeric value.", name_for_type(m_type)); - break; - case Average: - case Minimum: - case Maximum: - case Sum: - RLMPrecondition(RLMPropertyTypeIsNumeric(column.type()), @"Invalid operand", - @"%@ on a property of type %@ cannot be compared with property of type '%@'", - name_for_type(m_type), RLMTypeToString(m_column->type()), RLMTypeToString(column.type())); - break; - } - } - -private: - static Type type_for_name(NSString *name) { - if ([name isEqualToString:@"@count"]) { - return Count; - } - if ([name isEqualToString:@"@min"]) { - return Minimum; - } - if ([name isEqualToString:@"@max"]) { - return Maximum; - } - if ([name isEqualToString:@"@sum"]) { - return Sum; - } - if ([name isEqualToString:@"@avg"]) { - return Average; - } - @throw RLMPredicateException(@"Invalid predicate", @"Unsupported collection operation '%@'", name); - } - - static NSString *name_for_type(Type type) { - switch (type) { - case Count: return @"@count"; - case Minimum: return @"@min"; - case Maximum: return @"@max"; - case Sum: return @"@sum"; - case Average: return @"@avg"; - } - } - - Type m_type; - ColumnReference m_link_column; - util::Optional m_column; -}; - -class QueryBuilder { -public: - QueryBuilder(Query& query, Group& group, RLMSchema *schema) - : m_query(query), m_group(group), m_schema(schema) { } - - void apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema); - - - void apply_collection_operator_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred); - void apply_value_expression(RLMObjectSchema *desc, NSString *keyPath, id value, NSComparisonPredicate *pred); - void apply_column_expression(RLMObjectSchema *desc, NSString *leftKeyPath, NSString *rightKeyPath, NSComparisonPredicate *predicate); - void apply_subquery_count_expression(RLMObjectSchema *objectSchema, NSExpression *subqueryExpression, - NSPredicateOperatorType operatorType, NSExpression *right); - void apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, - NSPredicateOperatorType operatorType, NSExpression *right); - void apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, - NSPredicateOperatorType operatorType, NSExpression *right); - - - template - void add_numeric_constraint(RLMPropertyType datatype, - NSPredicateOperatorType operatorType, - A&& lhs, B&& rhs); - - template - void add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs); - - void add_substring_constraint(null, Query condition); - template - void add_substring_constraint(const T& value, Query condition); - template - void add_substring_constraint(const Columns& value, Query condition); - - template - void add_string_constraint(NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, - Columns &&column, - T value); - - void add_string_constraint(NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, - StringData value, - Columns&& column); - - template - void add_constraint(RLMPropertyType type, - NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, - L lhs, R rhs); - template - void do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, T... values); - void do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null); - - void add_between_constraint(const ColumnReference& column, id value); - - void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, BinaryData value); - void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value); - void add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null); - void add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column); - void add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&); - - void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, RLMObject *obj); - void add_link_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, realm::null); - template - void add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column); - void add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&); - - template - void add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values); - template - void add_collection_operation_constraint(NSPredicateOperatorType operatorType, - CollectionOperation collectionOperation, T... values); - - - CollectionOperation collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath); - ColumnReference column_reference_from_key_path(RLMObjectSchema *objectSchema, NSString *keyPath, bool isAggregate); - -private: - Query& m_query; - Group& m_group; - RLMSchema *m_schema; -}; - -// add a clause for numeric constraints based on operator type -template -void QueryBuilder::add_numeric_constraint(RLMPropertyType datatype, - NSPredicateOperatorType operatorType, - A&& lhs, B&& rhs) -{ - switch (operatorType) { - case NSLessThanPredicateOperatorType: - m_query.and_query(lhs < rhs); - break; - case NSLessThanOrEqualToPredicateOperatorType: - m_query.and_query(lhs <= rhs); - break; - case NSGreaterThanPredicateOperatorType: - m_query.and_query(lhs > rhs); - break; - case NSGreaterThanOrEqualToPredicateOperatorType: - m_query.and_query(lhs >= rhs); - break; - case NSEqualToPredicateOperatorType: - m_query.and_query(lhs == rhs); - break; - case NSNotEqualToPredicateOperatorType: - m_query.and_query(lhs != rhs); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' not supported for type %@", - operatorName(operatorType), RLMTypeToString(datatype)); - } -} - -template -void QueryBuilder::add_bool_constraint(NSPredicateOperatorType operatorType, A lhs, B rhs) { - switch (operatorType) { - case NSEqualToPredicateOperatorType: - m_query.and_query(lhs == rhs); - break; - case NSNotEqualToPredicateOperatorType: - m_query.and_query(lhs != rhs); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' not supported for bool type", operatorName(operatorType)); - } -} - -void QueryBuilder::add_substring_constraint(null, Query) { - // Foundation always returns false for substring operations with a RHS of null or "". - m_query.and_query(std::unique_ptr(new FalseExpression)); -} - -template -void QueryBuilder::add_substring_constraint(const T& value, Query condition) { - // Foundation always returns false for substring operations with a RHS of null or "". - m_query.and_query(value.size() - ? std::move(condition) - : std::unique_ptr(new FalseExpression)); -} - -template -void QueryBuilder::add_substring_constraint(const Columns& value, Query condition) { - // Foundation always returns false for substring operations with a RHS of null or "". - // We don't need to concern ourselves with the possibility of value traversing a link list - // and producing multiple values per row as such expressions will have been rejected. - m_query.and_query(const_cast&>(value).size() != 0 && std::move(condition)); -} - -template -void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, - Columns &&column, - T value) { - bool caseSensitive = !(predicateOptions & NSCaseInsensitivePredicateOption); - bool diacriticSensitive = !(predicateOptions & NSDiacriticInsensitivePredicateOption); - - if (diacriticSensitive) { - switch (operatorType) { - case NSBeginsWithPredicateOperatorType: - add_substring_constraint(value, column.begins_with(value, caseSensitive)); - break; - case NSEndsWithPredicateOperatorType: - add_substring_constraint(value, column.ends_with(value, caseSensitive)); - break; - case NSContainsPredicateOperatorType: - add_substring_constraint(value, column.contains(value, caseSensitive)); - break; - case NSEqualToPredicateOperatorType: - m_query.and_query(column.equal(value, caseSensitive)); - break; - case NSNotEqualToPredicateOperatorType: - m_query.and_query(column.not_equal(value, caseSensitive)); - break; - case NSLikePredicateOperatorType: - m_query.and_query(column.like(value, caseSensitive)); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' not supported for string type", - operatorName(operatorType)); - } - return; - } - - auto as_subexpr = util::overload([](StringData value) { return make_subexpr(value); }, - [](const Columns& c) { return c.clone(); }); - auto left = as_subexpr(column); - auto right = as_subexpr(value); - - auto make_constraint = [&](auto comparator) { - using Comparator = decltype(comparator); - using CompareCS = Compare; - using CompareCI = Compare; - if (caseSensitive) { - return make_expression(std::move(left), std::move(right)); - } - else { - return make_expression(std::move(left), std::move(right)); - } - }; - - switch (operatorType) { - case NSBeginsWithPredicateOperatorType: { - using C = ContainsSubstring; - add_substring_constraint(value, make_constraint(C{})); - break; - } - case NSEndsWithPredicateOperatorType: { - using C = ContainsSubstring; - add_substring_constraint(value, make_constraint(C{})); - break; - } - case NSContainsPredicateOperatorType: { - using C = ContainsSubstring; - add_substring_constraint(value, make_constraint(C{})); - break; - } - case NSNotEqualToPredicateOperatorType: - m_query.Not(); - REALM_FALLTHROUGH; - case NSEqualToPredicateOperatorType: - m_query.and_query(make_constraint(Equal{})); - break; - case NSLikePredicateOperatorType: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator 'LIKE' not supported with diacritic-insensitive modifier."); - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' not supported for string type", operatorName(operatorType)); - } -} - -void QueryBuilder::add_string_constraint(NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, - StringData value, - Columns&& column) { - switch (operatorType) { - case NSEqualToPredicateOperatorType: - case NSNotEqualToPredicateOperatorType: - add_string_constraint(operatorType, predicateOptions, std::move(column), value); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' is not supported for string type with key path on right side of operator", - operatorName(operatorType)); - } -} - -id value_from_constant_expression_or_value(id value) { - if (NSExpression *exp = RLMDynamicCast(value)) { - RLMPrecondition(exp.expressionType == NSConstantValueExpressionType, - @"Invalid value", - @"Expressions within predicate aggregates must be constant values"); - return exp.constantValue; - } - return value; -} - -void validate_and_extract_between_range(id value, RLMProperty *prop, id *from, id *to) { - NSArray *array = RLMDynamicCast(value); - RLMPrecondition(array, @"Invalid value", @"object must be of type NSArray for BETWEEN operations"); - RLMPrecondition(array.count == 2, @"Invalid value", @"NSArray object must contain exactly two objects for BETWEEN operations"); - - *from = value_from_constant_expression_or_value(array.firstObject); - *to = value_from_constant_expression_or_value(array.lastObject); - RLMPrecondition(RLMIsObjectValidForProperty(*from, prop) && RLMIsObjectValidForProperty(*to, prop), - @"Invalid value", - @"NSArray objects must be of type %@ for BETWEEN operations", RLMTypeToString(prop.type)); -} - -void QueryBuilder::add_between_constraint(const ColumnReference& column, id value) { - if (column.has_any_to_many_links()) { - auto link_column = column.last_link_column(); - Query subquery = get_table(m_group, link_column.link_target_object_schema()).where(); - QueryBuilder(subquery, m_group, m_schema).add_between_constraint(column.column_ignoring_links(subquery), value); - - m_query.and_query(link_column.resolve(std::move(subquery)).count() > 0); - return; - } - - id from, to; - validate_and_extract_between_range(value, column.property(), &from, &to); - - RLMPropertyType type = column.type(); - - m_query.group(); - add_constraint(type, NSGreaterThanOrEqualToPredicateOperatorType, 0, column, from); - add_constraint(type, NSLessThanOrEqualToPredicateOperatorType, 0, column, to); - m_query.end_group(); -} - -void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, - const ColumnReference& column, - BinaryData value) { - RLMPrecondition(!column.has_links(), @"Unsupported operator", @"NSData properties cannot be queried over an object link."); - - size_t index = column.index(); - Query query = m_query.get_table()->where(); - - switch (operatorType) { - case NSBeginsWithPredicateOperatorType: - add_substring_constraint(value, query.begins_with(index, value)); - break; - case NSEndsWithPredicateOperatorType: - add_substring_constraint(value, query.ends_with(index, value)); - break; - case NSContainsPredicateOperatorType: - add_substring_constraint(value, query.contains(index, value)); - break; - case NSEqualToPredicateOperatorType: - m_query.equal(index, value); - break; - case NSNotEqualToPredicateOperatorType: - m_query.not_equal(index, value); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' not supported for binary type", operatorName(operatorType)); - } -} - -void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, id value) { - add_binary_constraint(operatorType, column, RLMBinaryDataForNSData(value)); -} - -void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, const ColumnReference& column, null) { - add_binary_constraint(operatorType, column, BinaryData()); -} - -void QueryBuilder::add_binary_constraint(NSPredicateOperatorType operatorType, id value, const ColumnReference& column) { - switch (operatorType) { - case NSEqualToPredicateOperatorType: - case NSNotEqualToPredicateOperatorType: - add_binary_constraint(operatorType, column, value); - break; - default: - @throw RLMPredicateException(@"Invalid operator type", - @"Operator '%@' is not supported for binary type with key path on right side of operator", - operatorName(operatorType)); - } -} - -void QueryBuilder::add_binary_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) { - @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two NSData properties are not supported"); -} - -void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, - const ColumnReference& column, RLMObject *obj) { - RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType, - @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison"); - - if (operatorType == NSEqualToPredicateOperatorType) { - m_query.and_query(column.resolve() == obj->_row); - } - else { - m_query.and_query(column.resolve() != obj->_row); - } -} - -void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, - const ColumnReference& column, - realm::null) { - RLMPrecondition(operatorType == NSEqualToPredicateOperatorType || operatorType == NSNotEqualToPredicateOperatorType, - @"Invalid operator type", @"Only 'Equal' and 'Not Equal' operators supported for object comparison"); - - if (operatorType == NSEqualToPredicateOperatorType) { - m_query.and_query(column.resolve() == null()); - } - else { - m_query.and_query(column.resolve() != null()); - } -} - -template -void QueryBuilder::add_link_constraint(NSPredicateOperatorType operatorType, T obj, const ColumnReference& column) { - // Link constraints only support the equal-to and not-equal-to operators. The order of operands - // is not important for those comparisons so we can delegate to the other implementation. - add_link_constraint(operatorType, column, obj); -} - -void QueryBuilder::add_link_constraint(NSPredicateOperatorType, const ColumnReference&, const ColumnReference&) { - // This is not actually reachable as this case is caught earlier, but this - // overload is needed for the code to compile - @throw RLMPredicateException(@"Invalid predicate", @"Comparisons between two RLMArray properties are not supported"); -} - - -// iterate over an array of subpredicates, using @func to build a query from each -// one and ORing them together -template -void process_or_group(Query &query, id array, Func&& func) { - array = RLMAsFastEnumeration(array); - RLMPrecondition(array, @"Invalid value", @"IN clause requires an array of items"); - - query.group(); - - bool first = true; - for (id item in array) { - if (!first) { - query.Or(); - } - first = false; - - func(item); - } - - if (first) { - // Queries can't be empty, so if there's zero things in the OR group - // validation will fail. Work around this by adding an expression which - // will never find any rows in a table. - query.and_query(std::unique_ptr(new FalseExpression)); - } - - query.end_group(); -} - -template -RequestedType convert(id value); - -template <> -Timestamp convert(id value) { - return RLMTimestampForNSDate(value); -} - -template <> -bool convert(id value) { - return [value boolValue]; -} - -template <> -Double convert(id value) { - return [value doubleValue]; -} - -template <> -Float convert(id value) { - return [value floatValue]; -} - -template <> -Int convert(id value) { - return [value longLongValue]; -} - -template <> -String convert(id value) { - return RLMStringDataWithNSString(value); -} - -template -realm::null value_of_type(realm::null) { - return realm::null(); -} - -template -auto value_of_type(id value) { - return ::convert(value); -} - -template -auto value_of_type(const ColumnReference& column) { - return column.resolve(); -} - - -template -void QueryBuilder::do_add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, T... values) -{ - static_assert(sizeof...(T) == 2, "do_add_constraint accepts only two values as arguments"); - - switch (type) { - case RLMPropertyTypeBool: - add_bool_constraint(operatorType, value_of_type(values)...); - break; - case RLMPropertyTypeDate: - add_numeric_constraint(type, operatorType, value_of_type(values)...); - break; - case RLMPropertyTypeDouble: - add_numeric_constraint(type, operatorType, value_of_type(values)...); - break; - case RLMPropertyTypeFloat: - add_numeric_constraint(type, operatorType, value_of_type(values)...); - break; - case RLMPropertyTypeInt: - add_numeric_constraint(type, operatorType, value_of_type(values)...); - break; - case RLMPropertyTypeString: - add_string_constraint(operatorType, predicateOptions, value_of_type(values)...); - break; - case RLMPropertyTypeData: - add_binary_constraint(operatorType, values...); - break; - case RLMPropertyTypeObject: - case RLMPropertyTypeLinkingObjects: - add_link_constraint(operatorType, values...); - break; - default: - @throw RLMPredicateException(@"Unsupported predicate value type", - @"Object type %@ not supported", RLMTypeToString(type)); - } -} - -void QueryBuilder::do_add_constraint(RLMPropertyType, NSPredicateOperatorType, NSComparisonPredicateOptions, id, realm::null) -{ - // This is not actually reachable as this case is caught earlier, but this - // overload is needed for the code to compile - @throw RLMPredicateException(@"Invalid predicate expressions", - @"Predicate expressions must compare a keypath and another keypath or a constant value"); -} - -bool is_nsnull(id value) { - return !value || value == NSNull.null; -} - -template -bool is_nsnull(T) { - return false; -} - -template -void QueryBuilder::add_constraint(RLMPropertyType type, NSPredicateOperatorType operatorType, - NSComparisonPredicateOptions predicateOptions, L lhs, R rhs) -{ - // The expression operators are only overloaded for realm::null on the rhs - RLMPrecondition(!is_nsnull(lhs), @"Unsupported operator", - @"Nil is only supported on the right side of operators"); - - if (is_nsnull(rhs)) { - do_add_constraint(type, operatorType, predicateOptions, lhs, realm::null()); - } - else { - do_add_constraint(type, operatorType, predicateOptions, lhs, rhs); - } -} - -struct KeyPath { - std::vector links; - RLMProperty *property; - bool containsToManyRelationship; -}; - -KeyPath key_path_from_string(RLMSchema *schema, RLMObjectSchema *objectSchema, NSString *keyPath) -{ - RLMProperty *property; - std::vector links; - - bool keyPathContainsToManyRelationship = false; - - NSUInteger start = 0, length = keyPath.length, end = NSNotFound; - do { - end = [keyPath rangeOfString:@"." options:0 range:{start, length - start}].location; - NSString *propertyName = [keyPath substringWithRange:{start, end == NSNotFound ? length - start : end - start}]; - property = objectSchema[propertyName]; - RLMPrecondition(property, @"Invalid property name", - @"Property '%@' not found in object of type '%@'", - propertyName, objectSchema.className); - - if (property.array) - keyPathContainsToManyRelationship = true; - - if (end != NSNotFound) { - RLMPrecondition(property.type == RLMPropertyTypeObject || property.type == RLMPropertyTypeLinkingObjects, - @"Invalid value", @"Property '%@' is not a link in object of type '%@'", - propertyName, objectSchema.className); - - links.push_back(property); - REALM_ASSERT(property.objectClassName); - objectSchema = schema[property.objectClassName]; - } - - start = end + 1; - } while (end != NSNotFound); - - return {std::move(links), property, keyPathContainsToManyRelationship}; -} - -ColumnReference QueryBuilder::column_reference_from_key_path(RLMObjectSchema *objectSchema, - NSString *keyPathString, bool isAggregate) -{ - auto keyPath = key_path_from_string(m_schema, objectSchema, keyPathString); - - if (isAggregate && !keyPath.containsToManyRelationship) { - @throw RLMPredicateException(@"Invalid predicate", - @"Aggregate operations can only be used on key paths that include an array property"); - } else if (!isAggregate && keyPath.containsToManyRelationship) { - @throw RLMPredicateException(@"Invalid predicate", - @"Key paths that include an array property must use aggregate operations"); - } - - return ColumnReference(m_query, m_group, m_schema, keyPath.property, std::move(keyPath.links)); -} - -void validate_property_value(const ColumnReference& column, - __unsafe_unretained id const value, - __unsafe_unretained NSString *const err, - __unsafe_unretained RLMObjectSchema *const objectSchema, - __unsafe_unretained NSString *const keyPath) { - RLMProperty *prop = column.property(); - if (prop.array) { - RLMPrecondition([RLMObjectBaseObjectSchema(RLMDynamicCast(value)).className isEqualToString:prop.objectClassName], - @"Invalid value", err, prop.objectClassName, keyPath, objectSchema.className, value); - } - else { - RLMPrecondition(RLMIsObjectValidForProperty(value, prop), - @"Invalid value", err, RLMTypeToString(prop.type), keyPath, objectSchema.className, value); - } - if (RLMObjectBase *obj = RLMDynamicCast(value)) { - RLMPrecondition(!obj->_row.is_attached() || &column.group() == &obj->_realm.group, - @"Invalid value origin", @"Object must be from the Realm being queried"); - } -} - -template -struct ValueOfTypeWithCollectionOperationHelper; - -template <> -struct ValueOfTypeWithCollectionOperationHelper { - static auto convert(const CollectionOperation& operation) - { - assert(operation.type() == CollectionOperation::Count); - return operation.link_column().resolve().count(); - } -}; - -#define VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(OperationType, function) \ -template \ -struct ValueOfTypeWithCollectionOperationHelper { \ - static auto convert(const CollectionOperation& operation) \ - { \ - REALM_ASSERT(operation.type() == OperationType); \ - auto targetColumn = operation.link_column().resolve().template column(operation.column().index()); \ - return targetColumn.function(); \ - } \ -} \ - -VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Minimum, min); -VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Maximum, max); -VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Sum, sum); -VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER(CollectionOperation::Average, average); -#undef VALUE_OF_TYPE_WITH_COLLECTION_OPERATOR_HELPER - -template -auto value_of_type_with_collection_operation(T&& value) { - return value_of_type(std::forward(value)); -} - -template -auto value_of_type_with_collection_operation(CollectionOperation operation) { - using helper = ValueOfTypeWithCollectionOperationHelper; - return helper::convert(operation); -} - -template -void QueryBuilder::add_collection_operation_constraint(RLMPropertyType propertyType, NSPredicateOperatorType operatorType, T... values) -{ - switch (propertyType) { - case RLMPropertyTypeInt: - add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); - break; - case RLMPropertyTypeFloat: - add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); - break; - case RLMPropertyTypeDouble: - add_numeric_constraint(propertyType, operatorType, value_of_type_with_collection_operation(values)...); - break; - default: - REALM_ASSERT(false && "Only numeric property types should hit this path."); - } -} - -template -void QueryBuilder::add_collection_operation_constraint(NSPredicateOperatorType operatorType, - CollectionOperation collectionOperation, T... values) -{ - static_assert(sizeof...(T) == 2, "add_collection_operation_constraint accepts only two values as arguments"); - - switch (collectionOperation.type()) { - case CollectionOperation::Count: - add_numeric_constraint(RLMPropertyTypeInt, operatorType, - value_of_type_with_collection_operation(values)...); - break; - case CollectionOperation::Minimum: - add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); - break; - case CollectionOperation::Maximum: - add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); - break; - case CollectionOperation::Sum: - add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); - break; - case CollectionOperation::Average: - add_collection_operation_constraint(collectionOperation.column().type(), operatorType, values...); - break; - } -} - -bool key_path_contains_collection_operator(NSString *keyPath) { - return [keyPath rangeOfString:@"@"].location != NSNotFound; -} - -NSString *get_collection_operation_name_from_key_path(NSString *keyPath, NSString **leadingKeyPath, - NSString **trailingKey) { - NSRange at = [keyPath rangeOfString:@"@"]; - if (at.location == NSNotFound || at.location >= keyPath.length - 1) { - @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath); - } - - if (at.location == 0 || [keyPath characterAtIndex:at.location - 1] != '.') { - @throw RLMPredicateException(@"Invalid key path", @"'%@' is not a valid key path'", keyPath); - } - - NSRange trailingKeyRange = [keyPath rangeOfString:@"." options:0 range:{at.location, keyPath.length - at.location} locale:nil]; - - *leadingKeyPath = [keyPath substringToIndex:at.location - 1]; - if (trailingKeyRange.location == NSNotFound) { - *trailingKey = nil; - return [keyPath substringFromIndex:at.location]; - } else { - *trailingKey = [keyPath substringFromIndex:trailingKeyRange.location + 1]; - return [keyPath substringWithRange:{at.location, trailingKeyRange.location - at.location}]; - } -} - -CollectionOperation QueryBuilder::collection_operation_from_key_path(RLMObjectSchema *desc, NSString *keyPath) { - NSString *leadingKeyPath; - NSString *trailingKey; - NSString *collectionOperationName = get_collection_operation_name_from_key_path(keyPath, &leadingKeyPath, &trailingKey); - - ColumnReference linkColumn = column_reference_from_key_path(desc, leadingKeyPath, true); - util::Optional column; - if (trailingKey) { - RLMPrecondition([trailingKey rangeOfString:@"."].location == NSNotFound, @"Invalid key path", - @"Right side of collection operator may only have a single level key"); - NSString *fullKeyPath = [leadingKeyPath stringByAppendingFormat:@".%@", trailingKey]; - column = column_reference_from_key_path(desc, fullKeyPath, true); - } - - return {collectionOperationName, std::move(linkColumn), std::move(column)}; -} - -void QueryBuilder::apply_collection_operator_expression(RLMObjectSchema *desc, - NSString *keyPath, id value, - NSComparisonPredicate *pred) { - CollectionOperation operation = collection_operation_from_key_path(desc, keyPath); - operation.validate_comparison(value); - - if (pred.leftExpression.expressionType == NSKeyPathExpressionType) { - add_collection_operation_constraint(pred.predicateOperatorType, operation, operation, value); - } else { - add_collection_operation_constraint(pred.predicateOperatorType, operation, value, operation); - } -} - -void QueryBuilder::apply_value_expression(RLMObjectSchema *desc, - NSString *keyPath, id value, - NSComparisonPredicate *pred) -{ - if (key_path_contains_collection_operator(keyPath)) { - apply_collection_operator_expression(desc, keyPath, value, pred); - return; - } - - bool isAny = pred.comparisonPredicateModifier == NSAnyPredicateModifier; - ColumnReference column = column_reference_from_key_path(desc, keyPath, isAny); - - // check to see if this is a between query - if (pred.predicateOperatorType == NSBetweenPredicateOperatorType) { - add_between_constraint(std::move(column), value); - return; - } - - // turn "key.path IN collection" into ored together ==. "collection IN key.path" is handled elsewhere. - if (pred.predicateOperatorType == NSInPredicateOperatorType) { - process_or_group(m_query, value, [&](id item) { - id normalized = value_from_constant_expression_or_value(item); - validate_property_value(column, normalized, - @"Expected object of type %@ in IN clause for property '%@' on object of type '%@', but received: %@", desc, keyPath); - add_constraint(column.type(), NSEqualToPredicateOperatorType, pred.options, column, normalized); - }); - return; - } - - validate_property_value(column, value, @"Expected object of type %@ for property '%@' on object of type '%@', but received: %@", desc, keyPath); - if (pred.leftExpression.expressionType == NSKeyPathExpressionType) { - add_constraint(column.type(), pred.predicateOperatorType, pred.options, std::move(column), value); - } else { - add_constraint(column.type(), pred.predicateOperatorType, pred.options, value, std::move(column)); - } -} - -void QueryBuilder::apply_column_expression(RLMObjectSchema *desc, - NSString *leftKeyPath, NSString *rightKeyPath, - NSComparisonPredicate *predicate) -{ - bool left_key_path_contains_collection_operator = key_path_contains_collection_operator(leftKeyPath); - bool right_key_path_contains_collection_operator = key_path_contains_collection_operator(rightKeyPath); - if (left_key_path_contains_collection_operator && right_key_path_contains_collection_operator) { - @throw RLMPredicateException(@"Unsupported predicate", @"Key paths including aggregate operations cannot be compared with other aggregate operations."); - } - - if (left_key_path_contains_collection_operator) { - CollectionOperation left = collection_operation_from_key_path(desc, leftKeyPath); - ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, false); - left.validate_comparison(right); - add_collection_operation_constraint(predicate.predicateOperatorType, left, left, std::move(right)); - return; - } - if (right_key_path_contains_collection_operator) { - ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, false); - CollectionOperation right = collection_operation_from_key_path(desc, rightKeyPath); - right.validate_comparison(left); - add_collection_operation_constraint(predicate.predicateOperatorType, right, std::move(left), right); - return; - } - - bool isAny = false; - ColumnReference left = column_reference_from_key_path(desc, leftKeyPath, isAny); - ColumnReference right = column_reference_from_key_path(desc, rightKeyPath, isAny); - - // NOTE: It's assumed that column type must match and no automatic type conversion is supported. - RLMPrecondition(left.type() == right.type(), - RLMPropertiesComparisonTypeMismatchException, - RLMPropertiesComparisonTypeMismatchReason, - RLMTypeToString(left.type()), - RLMTypeToString(right.type())); - - // TODO: Should we handle special case where left row is the same as right row (tautology) - add_constraint(left.type(), predicate.predicateOperatorType, predicate.options, - std::move(left), std::move(right)); -} - -// Identify expressions of the form [SELF valueForKeyPath:] -bool is_self_value_for_key_path_function_expression(NSExpression *expression) -{ - if (expression.expressionType != NSFunctionExpressionType) - return false; - - if (expression.operand.expressionType != NSEvaluatedObjectExpressionType) - return false; - - return [expression.function isEqualToString:@"valueForKeyPath:"]; -} - -// -[NSPredicate predicateWithSubtitutionVariables:] results in function expressions of the form [SELF valueForKeyPath:] -// that apply_predicate cannot handle. Replace such expressions with equivalent NSKeyPathExpressionType expressions. -NSExpression *simplify_self_value_for_key_path_function_expression(NSExpression *expression) { - if (is_self_value_for_key_path_function_expression(expression)) { - if (NSString *keyPath = [expression.arguments.firstObject keyPath]) { - return [NSExpression expressionForKeyPath:keyPath]; - } - } - return expression; -} - -void QueryBuilder::apply_subquery_count_expression(RLMObjectSchema *objectSchema, - NSExpression *subqueryExpression, NSPredicateOperatorType operatorType, NSExpression *right) { - if (right.expressionType != NSConstantValueExpressionType || ![right.constantValue isKindOfClass:[NSNumber class]]) { - @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY(…).@count is only supported when compared with a constant number."); - } - int64_t value = [right.constantValue integerValue]; - - ColumnReference collectionColumn = column_reference_from_key_path(objectSchema, [subqueryExpression.collection keyPath], true); - RLMObjectSchema *collectionMemberObjectSchema = m_schema[collectionColumn.property().objectClassName]; - - // Eliminate references to the iteration variable in the subquery. - NSPredicate *subqueryPredicate = [subqueryExpression.predicate predicateWithSubstitutionVariables:@{ subqueryExpression.variable : [NSExpression expressionForEvaluatedObject] }]; - subqueryPredicate = transformPredicate(subqueryPredicate, simplify_self_value_for_key_path_function_expression); - - Query subquery = RLMPredicateToQuery(subqueryPredicate, collectionMemberObjectSchema, m_schema, m_group); - add_numeric_constraint(RLMPropertyTypeInt, operatorType, - collectionColumn.resolve(std::move(subquery)).count(), value); -} - -void QueryBuilder::apply_function_subquery_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, - NSPredicateOperatorType operatorType, NSExpression *right) { - if (![functionExpression.function isEqualToString:@"valueForKeyPath:"] || functionExpression.arguments.count != 1) { - @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported on the result of a SUBQUERY.", functionExpression.function); - } - - NSExpression *keyPathExpression = functionExpression.arguments.firstObject; - if ([keyPathExpression.keyPath isEqualToString:@"@count"]) { - apply_subquery_count_expression(objectSchema, functionExpression.operand, operatorType, right); - } else { - @throw RLMPredicateException(@"Invalid predicate", @"SUBQUERY is only supported when immediately followed by .@count that is compared with a constant number."); - } -} - -void QueryBuilder::apply_function_expression(RLMObjectSchema *objectSchema, NSExpression *functionExpression, - NSPredicateOperatorType operatorType, NSExpression *right) { - if (functionExpression.operand.expressionType == NSSubqueryExpressionType) { - apply_function_subquery_expression(objectSchema, functionExpression, operatorType, right); - } else { - @throw RLMPredicateException(@"Invalid predicate", @"The '%@' function is not supported.", functionExpression.function); - } -} - - -void QueryBuilder::apply_predicate(NSPredicate *predicate, RLMObjectSchema *objectSchema) -{ - // Compound predicates. - if ([predicate isMemberOfClass:[NSCompoundPredicate class]]) { - NSCompoundPredicate *comp = (NSCompoundPredicate *)predicate; - - switch ([comp compoundPredicateType]) { - case NSAndPredicateType: - if (comp.subpredicates.count) { - // Add all of the subpredicates. - m_query.group(); - for (NSPredicate *subp in comp.subpredicates) { - apply_predicate(subp, objectSchema); - } - m_query.end_group(); - } else { - // NSCompoundPredicate's documentation states that an AND predicate with no subpredicates evaluates to TRUE. - m_query.and_query(std::unique_ptr(new TrueExpression)); - } - break; - - case NSOrPredicateType: { - // Add all of the subpredicates with ors inbetween. - process_or_group(m_query, comp.subpredicates, [&](__unsafe_unretained NSPredicate *const subp) { - apply_predicate(subp, objectSchema); - }); - break; - } - - case NSNotPredicateType: - // Add the negated subpredicate - m_query.Not(); - apply_predicate(comp.subpredicates.firstObject, objectSchema); - break; - - default: - @throw RLMPredicateException(@"Invalid compound predicate type", - @"Only support AND, OR and NOT predicate types"); - } - } - else if ([predicate isMemberOfClass:[NSComparisonPredicate class]]) { - NSComparisonPredicate *compp = (NSComparisonPredicate *)predicate; - - // check modifier - RLMPrecondition(compp.comparisonPredicateModifier != NSAllPredicateModifier, - @"Invalid predicate", @"ALL modifier not supported"); - - NSExpressionType exp1Type = compp.leftExpression.expressionType; - NSExpressionType exp2Type = compp.rightExpression.expressionType; - - if (compp.comparisonPredicateModifier == NSAnyPredicateModifier) { - // for ANY queries - RLMPrecondition(exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType, - @"Invalid predicate", - @"Predicate with ANY modifier must compare a KeyPath with RLMArray with a value"); - } - - if (compp.predicateOperatorType == NSBetweenPredicateOperatorType || compp.predicateOperatorType == NSInPredicateOperatorType) { - // Inserting an array via %@ gives NSConstantValueExpressionType, but including it directly gives NSAggregateExpressionType - if (exp1Type == NSKeyPathExpressionType && (exp2Type == NSAggregateExpressionType || exp2Type == NSConstantValueExpressionType)) { - // "key.path IN %@", "key.path IN {…}", "key.path BETWEEN %@", or "key.path BETWEEN {…}". - exp2Type = NSConstantValueExpressionType; - } - else if (compp.predicateOperatorType == NSInPredicateOperatorType && exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) { - // "%@ IN key.path" is equivalent to "ANY key.path IN %@". Rewrite the former into the latter. - compp = [NSComparisonPredicate predicateWithLeftExpression:compp.rightExpression rightExpression:compp.leftExpression - modifier:NSAnyPredicateModifier type:NSEqualToPredicateOperatorType options:0]; - exp1Type = NSKeyPathExpressionType; - exp2Type = NSConstantValueExpressionType; - } - else { - if (compp.predicateOperatorType == NSBetweenPredicateOperatorType) { - @throw RLMPredicateException(@"Invalid predicate", - @"Predicate with BETWEEN operator must compare a KeyPath with an aggregate with two values"); - } - else if (compp.predicateOperatorType == NSInPredicateOperatorType) { - @throw RLMPredicateException(@"Invalid predicate", - @"Predicate with IN operator must compare a KeyPath with an aggregate"); - } - } - } - - if (exp1Type == NSKeyPathExpressionType && exp2Type == NSKeyPathExpressionType) { - // both expression are KeyPaths - apply_column_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.keyPath, compp); - } - else if (exp1Type == NSKeyPathExpressionType && exp2Type == NSConstantValueExpressionType) { - // comparing keypath to value - apply_value_expression(objectSchema, compp.leftExpression.keyPath, compp.rightExpression.constantValue, compp); - } - else if (exp1Type == NSConstantValueExpressionType && exp2Type == NSKeyPathExpressionType) { - // comparing value to keypath - apply_value_expression(objectSchema, compp.rightExpression.keyPath, compp.leftExpression.constantValue, compp); - } - else if (exp1Type == NSFunctionExpressionType) { - apply_function_expression(objectSchema, compp.leftExpression, compp.predicateOperatorType, compp.rightExpression); - } - else if (exp1Type == NSSubqueryExpressionType) { - // The subquery expressions that we support are handled by the NSFunctionExpressionType case above. - @throw RLMPredicateException(@"Invalid predicate expression", @"SUBQUERY is only supported when immediately followed by .@count."); - } - else { - @throw RLMPredicateException(@"Invalid predicate expressions", - @"Predicate expressions must compare a keypath and another keypath or a constant value"); - } - } - else if ([predicate isEqual:[NSPredicate predicateWithValue:YES]]) { - m_query.and_query(std::unique_ptr(new TrueExpression)); - } else if ([predicate isEqual:[NSPredicate predicateWithValue:NO]]) { - m_query.and_query(std::unique_ptr(new FalseExpression)); - } - else { - // invalid predicate type - @throw RLMPredicateException(@"Invalid predicate", - @"Only support compound, comparison, and constant predicates"); - } -} -} // namespace - -realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema, - RLMSchema *schema, Group &group) -{ - auto query = get_table(group, objectSchema).where(); - - // passing a nil predicate is a no-op - if (!predicate) { - return query; - } - - @autoreleasepool { - QueryBuilder(query, group, schema).apply_predicate(predicate, objectSchema); - } - - // Test the constructed query in core - std::string validateMessage = query.validate(); - RLMPrecondition(validateMessage.empty(), @"Invalid query", @"%.*s", - (int)validateMessage.size(), validateMessage.c_str()); - return query; -} diff --git a/Lesson14/Pods/Realm/Realm/RLMRealm+Sync.mm b/Lesson14/Pods/Realm/Realm/RLMRealm+Sync.mm deleted file mode 100644 index 02f10d7..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMRealm+Sync.mm +++ /dev/null @@ -1,86 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "RLMRealm+Sync.h" - -#import "RLMObjectBase.h" -#import "RLMQueryUtil.hpp" -#import "RLMObjectSchema.h" -#import "RLMRealm_Private.hpp" -#import "RLMResults_Private.hpp" -#import "RLMSchema.h" -#import "RLMSyncSession.h" - -#import "results.hpp" -#import "shared_realm.hpp" -#import "sync/partial_sync.hpp" -#import "sync/subscription_state.hpp" - -using namespace realm; - -@implementation RLMRealm (Sync) - -- (void)subscribeToObjects:(Class)type where:(NSString *)query callback:(RLMPartialSyncFetchCallback)callback { - [self verifyThread]; - - RLMClassInfo& info = _info[[type className]]; - Query q = RLMPredicateToQuery([NSPredicate predicateWithFormat:query], - info.rlmObjectSchema, self.schema, self.group); - struct Holder { - partial_sync::Subscription subscription; - partial_sync::SubscriptionNotificationToken token; - - Holder(partial_sync::Subscription&& s) : subscription(std::move(s)) { } - }; - auto state = std::make_shared(partial_sync::subscribe(Results(_realm, std::move(q)), {})); - state->token = state->subscription.add_notification_callback([=]() mutable { - if (!callback) { - return; - } - switch (state->subscription.state()) { - case partial_sync::SubscriptionState::Invalidated: - case partial_sync::SubscriptionState::Pending: - case partial_sync::SubscriptionState::Creating: - return; - - case partial_sync::SubscriptionState::Error: - try { - rethrow_exception(state->subscription.error()); - } - catch (...) { - NSError *error = nil; - RLMRealmTranslateException(&error); - callback(nil, error); - } - break; - - case partial_sync::SubscriptionState::Complete: - callback([RLMResults emptyDetachedResults], nil); - break; - } - - callback = nil; - state->token = {}; - }); -} - -- (RLMSyncSession *)syncSession { - return [RLMSyncSession sessionForRealm:self]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMRealm.mm b/Lesson14/Pods/Realm/Realm/RLMRealm.mm deleted file mode 100644 index 2ec9b2b..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMRealm.mm +++ /dev/null @@ -1,1033 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMRealm_Private.hpp" - -#import "RLMAnalytics.hpp" -#import "RLMArray_Private.hpp" -#import "RLMMigration_Private.h" -#import "RLMObject_Private.h" -#import "RLMObject_Private.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObservation.hpp" -#import "RLMProperty.h" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMRealmConfiguration_Private.hpp" -#import "RLMRealmUtil.hpp" -#import "RLMSchema_Private.hpp" -#import "RLMThreadSafeReference_Private.hpp" -#import "RLMUpdateChecker.hpp" -#import "RLMUtil.hpp" - -#include "impl/realm_coordinator.hpp" -#include "object_store.hpp" -#include "schema.hpp" -#include "shared_realm.hpp" -#include "thread_safe_reference.hpp" - -#include -#include -#include - -#if REALM_ENABLE_SYNC -#import "RLMSyncManager_Private.h" -#import "RLMSyncSession_Private.hpp" -#import "RLMSyncUtil_Private.hpp" - -#import "sync/async_open_task.hpp" -#import "sync/sync_session.hpp" -#endif - -using namespace realm; -using util::File; - -@interface RLMRealmNotificationToken : RLMNotificationToken -@property (nonatomic, strong) RLMRealm *realm; -@property (nonatomic, copy) RLMNotificationBlock block; -@end - -@interface RLMRealm () -@property (nonatomic, strong) NSHashTable *notificationHandlers; -- (void)sendNotifications:(RLMNotification)notification; -@end - -void RLMDisableSyncToDisk() { - realm::disable_sync_to_disk(); -} - -static void RLMAddSkipBackupAttributeToItemAtPath(std::string const& path) { - [[NSURL fileURLWithPath:@(path.c_str())] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; -} - -@implementation RLMRealmNotificationToken -- (void)invalidate { - [_realm verifyThread]; - [_realm.notificationHandlers removeObject:self]; - _realm = nil; - _block = nil; -} - -- (void)suppressNextNotification { - // Temporarily replace the block with one which restores the old block - // rather than producing a notification. - - // This briefly creates a retain cycle but it's fine because the block will - // be synchronously called shortly after this method is called. Unlike with - // collection notifications, this does not have to go through the object - // store or do fancy things to handle transaction coalescing because it's - // called synchronously by the obj-c code and not by the object store. - auto notificationBlock = _block; - _block = ^(RLMNotification, RLMRealm *) { - _block = notificationBlock; - }; -} - -- (void)dealloc { - if (_realm || _block) { - NSLog(@"RLMNotificationToken released without unregistering a notification. You must hold " - @"on to the RLMNotificationToken returned from addNotificationBlock and call " - @"-[RLMNotificationToken invalidate] when you no longer wish to receive RLMRealm notifications."); - } -} -@end - -#if !REALM_ENABLE_SYNC -@interface RLMAsyncOpenTask : NSObject -@end -@implementation RLMAsyncOpenTask -@end -#endif - -static bool shouldForciblyDisableEncryption() { - static bool disableEncryption = getenv("REALM_DISABLE_ENCRYPTION"); - return disableEncryption; -} - -NSData *RLMRealmValidatedEncryptionKey(NSData *key) { - if (shouldForciblyDisableEncryption()) { - return nil; - } - - if (key && key.length != 64) { - @throw RLMException(@"Encryption key must be exactly 64 bytes long"); - } - - return key; -} - -@implementation RLMRealm { - NSHashTable *_collectionEnumerators; - bool _sendingNotifications; -} - -+ (BOOL)isCoreDebug { - return realm::Version::has_feature(realm::feature_Debug); -} - -+ (void)initialize { - static bool initialized; - if (initialized) { - return; - } - initialized = true; - - RLMCheckForUpdates(); - RLMSendAnalytics(); -} - -- (instancetype)initPrivate { - self = [super init]; - return self; -} - -- (BOOL)isEmpty { - return realm::ObjectStore::is_empty(self.group); -} - -- (void)verifyThread { - try { - _realm->verify_thread(); - } - catch (std::exception const& e) { - @throw RLMException(e); - } -} - -- (BOOL)inWriteTransaction { - return _realm->is_in_transaction(); -} - -- (realm::Group &)group { - return _realm->read_group(); -} - -- (BOOL)autorefresh { - return _realm->auto_refresh(); -} - -- (void)setAutorefresh:(BOOL)autorefresh { - _realm->set_auto_refresh(autorefresh); -} - -+ (instancetype)defaultRealm { - return [RLMRealm realmWithConfiguration:[RLMRealmConfiguration rawDefaultConfiguration] error:nil]; -} - -+ (instancetype)realmWithURL:(NSURL *)fileURL { - RLMRealmConfiguration *configuration = [RLMRealmConfiguration defaultConfiguration]; - configuration.fileURL = fileURL; - return [RLMRealm realmWithConfiguration:configuration error:nil]; -} - -// The server doesn't send us the subscriptions for permission types until the -// first subscription is created. This is fine for synchronous opens (if we're -// creating a new Realm we create the permission objects ourselves), but it -// causes issues for asyncOpen because it means that when our download completes -// we don't actually have the full Realm state yet. -static void waitForPartialSyncSubscriptions(Realm::Config const& config) { -#if REALM_ENABLE_SYNC - auto realm = Realm::get_shared_realm(config); - auto table = ObjectStore::table_for_object_type(realm->read_group(), "__ResultSets"); - - realm->begin_transaction(); - size_t row = realm::sync::create_object(realm->read_group(), *table); - - // Set expires_at to time 0 so that this object will be cleaned up the first - // time the user creates a subscription - size_t expires_at_col = table->get_column_index("expires_at"); - if (expires_at_col == npos) { - expires_at_col = table->add_column(type_Timestamp, "expires_at", true); - } - table->set_timestamp(expires_at_col, row, Timestamp(0, 0)); - realm->commit_transaction(); - - NotificationToken token; - Results results(realm, *table); - CFRunLoopRef runLoop = CFRunLoopGetCurrent(); - CFRunLoopPerformBlock(runLoop, kCFRunLoopDefaultMode, [&]() mutable { - token = results.add_notification_callback([&](CollectionChangeSet const&, std::exception_ptr) mutable { - if (table->size() > 1) { - token = {}; - CFRunLoopStop(runLoop); - } - }); - }); - CFRunLoopRun(); -#else - static_cast(config); -#endif -} - -static dispatch_queue_t s_async_open_queue = dispatch_queue_create("io.realm.asyncOpenDispatchQueue", - DISPATCH_QUEUE_CONCURRENT); -void RLMSetAsyncOpenQueue(dispatch_queue_t queue) { - s_async_open_queue = queue; -} - -+ (RLMAsyncOpenTask *)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration - callbackQueue:(dispatch_queue_t)callbackQueue - callback:(RLMAsyncOpenRealmCallback)callback { - auto openCompletion = [=](ThreadSafeReference ref, std::exception_ptr err) { - @autoreleasepool { - if (err) { - try { - std::rethrow_exception(err); - } - catch (...) { - NSError *error; - RLMRealmTranslateException(&error); - dispatch_async(callbackQueue, ^{ - callback(nil, error); - }); - } - return; - } - - auto complete = ^{ - dispatch_async(callbackQueue, ^{ - @autoreleasepool { - NSError *error; - RLMRealm *localRealm = [RLMRealm realmWithConfiguration:configuration error:&error]; - callback(localRealm, error); - } - }); - }; - - auto realm = Realm::get_shared_realm(std::move(ref)); - bool needsSubscriptions = realm->is_partial() && ObjectStore::table_for_object_type(realm->read_group(), "__ResultSets")->size() == 0; - if (needsSubscriptions) { - // We need to dispatch back to the work queue to wait for the - // subscriptions as we're currently running on the sync worker - // thread and blocking it to wait for subscriptions means no syncing - dispatch_async(s_async_open_queue, ^{ - @autoreleasepool { - waitForPartialSyncSubscriptions(realm->config()); - complete(); - } - }); - } - else { - complete(); - } - } - }; - - RLMAsyncOpenTask *ret = [RLMAsyncOpenTask new]; - dispatch_async(s_async_open_queue, ^{ - @autoreleasepool { - Realm::Config& config = configuration.config; - if (config.sync_config) { -#if REALM_ENABLE_SYNC - auto task = realm::Realm::get_synchronized_realm(config); - ret.task = task; - task->start(openCompletion); -#else - @throw RLMException(@"Realm was not built with sync enabled"); -#endif - } - else { - try { - openCompletion(realm::_impl::RealmCoordinator::get_coordinator(config)->get_unbound_realm(), nullptr); - } - catch (...) { - openCompletion({}, std::current_exception()); - } - } - } - }); - return ret; -} - -// ARC tries to eliminate calls to autorelease when the value is then immediately -// returned, but this results in significantly different semantics between debug -// and release builds for RLMRealm, so force it to always autorelease. -static id RLMAutorelease(__unsafe_unretained id value) { - // +1 __bridge_retained, -1 CFAutorelease - return value ? (__bridge id)CFAutorelease((__bridge_retained CFTypeRef)value) : nil; -} - -+ (instancetype)realmWithSharedRealm:(SharedRealm)sharedRealm schema:(RLMSchema *)schema { - RLMRealm *realm = [[RLMRealm alloc] initPrivate]; - realm->_realm = sharedRealm; - realm->_dynamic = YES; - realm->_schema = schema; - realm->_info = RLMSchemaInfo(realm); - return RLMAutorelease(realm); -} - -REALM_NOINLINE void RLMRealmTranslateException(NSError **error) { - try { - throw; - } - catch (RealmFileException const& ex) { - switch (ex.kind()) { - case RealmFileException::Kind::PermissionDenied: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFilePermissionDenied, ex), error); - break; - case RealmFileException::Kind::IncompatibleLockFile: { - NSString *err = @"Realm file is currently open in another process " - "which cannot share access with this process. All " - "processes sharing a single file must be the same " - "architecture. For sharing files between the Realm " - "Browser and an iOS simulator, this means that you " - "must use a 64-bit simulator."; - RLMSetErrorOrThrow(RLMMakeError(RLMErrorIncompatibleLockFile, - File::PermissionDenied(err.UTF8String, ex.path())), error); - break; - } - case RealmFileException::Kind::NotFound: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileNotFound, ex), error); - break; - case RealmFileException::Kind::Exists: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileExists, ex), error); - break; - case RealmFileException::Kind::BadHistoryError: { - NSString *err = @"Realm file's history format is incompatible with the " - "settings in the configuration object being used to open " - "the Realm. Note that Realms configured for sync cannot be " - "opened as non-synced Realms, and vice versa. Otherwise, the " - "file may be corrupt."; - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess, - File::AccessError(err.UTF8String, ex.path())), error); - break; - } - case RealmFileException::Kind::AccessError: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileAccess, ex), error); - break; - case RealmFileException::Kind::FormatUpgradeRequired: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFileFormatUpgradeRequired, ex), error); - break; - default: - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, ex), error); - break; - } - } - catch (AddressSpaceExhausted const &ex) { - RLMSetErrorOrThrow(RLMMakeError(RLMErrorAddressSpaceExhausted, ex), error); - } - catch (SchemaMismatchException const& ex) { - RLMSetErrorOrThrow(RLMMakeError(RLMErrorSchemaMismatch, ex), error); - } - catch (std::system_error const& ex) { - RLMSetErrorOrThrow(RLMMakeError(ex), error); - } - catch (const std::exception &exp) { - RLMSetErrorOrThrow(RLMMakeError(RLMErrorFail, exp), error); - } -} - -REALM_NOINLINE static void translateSharedGroupOpenException(RLMRealmConfiguration *originalConfiguration, NSError **error) { - try { - throw; - } - catch (RealmFileException const& ex) { - switch (ex.kind()) { - case RealmFileException::Kind::IncompatibleSyncedRealm: { - RLMRealmConfiguration *configuration = [originalConfiguration copy]; - configuration.fileURL = [NSURL fileURLWithPath:@(ex.path().data())]; - configuration.readOnly = YES; - - NSError *intermediateError = RLMMakeError(RLMErrorIncompatibleSyncedFile, ex); - NSMutableDictionary *userInfo = [intermediateError.userInfo mutableCopy]; - userInfo[RLMBackupRealmConfigurationErrorKey] = configuration; - NSError *finalError = [NSError errorWithDomain:intermediateError.domain code:intermediateError.code - userInfo:userInfo]; - RLMSetErrorOrThrow(finalError, error); - break; - } - default: - RLMRealmTranslateException(error); - break; - } - } - catch (...) { - RLMRealmTranslateException(error); - } -} - - -+ (instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { - bool dynamic = configuration.dynamic; - bool cache = configuration.cache; - bool readOnly = configuration.readOnly; - - { - Realm::Config& config = configuration.config; - - // try to reuse existing realm first - if (cache || dynamic) { - if (RLMRealm *realm = RLMGetThreadLocalCachedRealmForPath(config.path)) { - auto const& old_config = realm->_realm->config(); - if (old_config.immutable() != config.immutable() - || old_config.read_only_alternative() != config.read_only_alternative()) { - @throw RLMException(@"Realm at path '%s' already opened with different read permissions", config.path.c_str()); - } - if (old_config.in_memory != config.in_memory) { - @throw RLMException(@"Realm at path '%s' already opened with different inMemory settings", config.path.c_str()); - } - if (realm->_dynamic != dynamic) { - @throw RLMException(@"Realm at path '%s' already opened with different dynamic settings", config.path.c_str()); - } - if (old_config.encryption_key != config.encryption_key) { - @throw RLMException(@"Realm at path '%s' already opened with different encryption key", config.path.c_str()); - } - return RLMAutorelease(realm); - } - } - } - - configuration = [configuration copy]; - Realm::Config& config = configuration.config; - - RLMRealm *realm = [[self alloc] initPrivate]; - realm->_dynamic = dynamic; - - // protects the realm cache and accessors cache - static std::mutex& initLock = *new std::mutex(); - std::lock_guard lock(initLock); - - try { - realm->_realm = Realm::get_shared_realm(config); - } - catch (...) { - translateSharedGroupOpenException(configuration, error); - return nil; - } - - // if we have a cached realm on another thread we can skip a few steps and - // just grab its schema - @autoreleasepool { - // ensure that cachedRealm doesn't end up in this thread's autorelease pool - if (auto cachedRealm = RLMGetAnyCachedRealmForPath(config.path)) { - realm->_realm->set_schema_subset(cachedRealm->_realm->schema()); - realm->_schema = cachedRealm.schema; - realm->_info = cachedRealm->_info.clone(cachedRealm->_realm->schema(), realm); - } - } - - if (realm->_schema) { } - else if (dynamic) { - realm->_schema = [RLMSchema dynamicSchemaFromObjectStoreSchema:realm->_realm->schema()]; - realm->_info = RLMSchemaInfo(realm); - } - else { - // set/align schema or perform migration if needed - RLMSchema *schema = configuration.customSchema ?: RLMSchema.sharedSchema; - - Realm::MigrationFunction migrationFunction; - auto migrationBlock = configuration.migrationBlock; - if (migrationBlock && configuration.schemaVersion > 0) { - migrationFunction = [=](SharedRealm old_realm, SharedRealm realm, Schema& mutableSchema) { - RLMSchema *oldSchema = [RLMSchema dynamicSchemaFromObjectStoreSchema:old_realm->schema()]; - RLMRealm *oldRealm = [RLMRealm realmWithSharedRealm:old_realm schema:oldSchema]; - - // The destination RLMRealm can't just use the schema from the - // SharedRealm because it doesn't have information about whether or - // not a class was defined in Swift, which effects how new objects - // are created - RLMRealm *newRealm = [RLMRealm realmWithSharedRealm:realm schema:schema.copy]; - - [[[RLMMigration alloc] initWithRealm:newRealm oldRealm:oldRealm schema:mutableSchema] execute:migrationBlock]; - - oldRealm->_realm = nullptr; - newRealm->_realm = nullptr; - }; - } - - try { - realm->_realm->update_schema(schema.objectStoreCopy, config.schema_version, - std::move(migrationFunction)); - } - catch (...) { - RLMRealmTranslateException(error); - return nil; - } - - realm->_schema = schema; - realm->_info = RLMSchemaInfo(realm); - RLMRealmCreateAccessors(realm.schema); - - if (!readOnly) { - // initializing the schema started a read transaction, so end it - [realm invalidate]; - - RLMAddSkipBackupAttributeToItemAtPath(config.path + ".management"); - RLMAddSkipBackupAttributeToItemAtPath(config.path + ".lock"); - RLMAddSkipBackupAttributeToItemAtPath(config.path + ".note"); - } - } - - if (cache) { - RLMCacheRealm(config.path, realm); - } - - if (!readOnly) { - realm->_realm->m_binding_context = RLMCreateBindingContext(realm); - realm->_realm->m_binding_context->realm = realm->_realm; - } - - return RLMAutorelease(realm); -} - -+ (instancetype)uncachedSchemalessRealmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { - RLMRealm *realm = [[RLMRealm alloc] initPrivate]; - try { - realm->_realm = Realm::get_shared_realm(configuration.config); - } - catch (...) { - translateSharedGroupOpenException(configuration, error); - return nil; - } - return realm; -} - -+ (void)resetRealmState { - RLMClearRealmCache(); - realm::_impl::RealmCoordinator::clear_cache(); - [RLMRealmConfiguration resetRealmConfigurationState]; -} - -- (void)verifyNotificationsAreSupported:(bool)isCollection { - [self verifyThread]; - if (_realm->config().immutable()) { - @throw RLMException(@"Read-only Realms do not change and do not have change notifications"); - } - if (!_realm->can_deliver_notifications()) { - @throw RLMException(@"Can only add notification blocks from within runloops."); - } - if (isCollection && _realm->is_in_transaction()) { - @throw RLMException(@"Cannot register notification blocks from within write transactions."); - } -} - -- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block { - if (!block) { - @throw RLMException(@"The notification block should not be nil"); - } - [self verifyNotificationsAreSupported:false]; - - _realm->read_group(); - - if (!_notificationHandlers) { - _notificationHandlers = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]; - } - - RLMRealmNotificationToken *token = [[RLMRealmNotificationToken alloc] init]; - token.realm = self; - token.block = block; - [_notificationHandlers addObject:token]; - return token; -} - -- (void)sendNotifications:(RLMNotification)notification { - NSAssert(!_realm->config().immutable(), @"Read-only realms do not have notifications"); - if (_sendingNotifications) { - return; - } - NSUInteger count = _notificationHandlers.count; - if (count == 0) { - return; - } - - _sendingNotifications = true; - auto cleanup = realm::util::make_scope_exit([&]() noexcept { - _sendingNotifications = false; - }); - - // call this realm's notification blocks - if (count == 1) { - if (auto block = [_notificationHandlers.anyObject block]) { - block(notification, self); - } - } - else { - for (RLMRealmNotificationToken *token in _notificationHandlers.allObjects) { - if (auto block = token.block) { - block(notification, self); - } - } - } -} - -- (RLMRealmConfiguration *)configuration { - RLMRealmConfiguration *configuration = [[RLMRealmConfiguration alloc] init]; - configuration.config = _realm->config(); - configuration.dynamic = _dynamic; - configuration.customSchema = _schema; - return configuration; -} - -- (void)beginWriteTransaction { - try { - _realm->begin_transaction(); - } - catch (std::exception &ex) { - @throw RLMException(ex); - } -} - -- (void)commitWriteTransaction { - [self commitWriteTransaction:nil]; -} - -- (BOOL)commitWriteTransaction:(NSError **)error { - return [self commitWriteTransactionWithoutNotifying:@[] error:error]; -} - -- (BOOL)commitWriteTransactionWithoutNotifying:(NSArray *)tokens error:(NSError **)error { - for (RLMNotificationToken *token in tokens) { - if (token.realm != self) { - @throw RLMException(@"Incorrect Realm: only notifications for the Realm being modified can be skipped."); - } - [token suppressNextNotification]; - } - - try { - _realm->commit_transaction(); - return YES; - } - catch (...) { - RLMRealmTranslateException(error); - return NO; - } -} - -- (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block { - [self transactionWithBlock:block error:nil]; -} - -- (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)outError { - return [self transactionWithoutNotifying:@[] block:block error:outError]; -} - -- (void)transactionWithoutNotifying:(NSArray *)tokens block:(__attribute__((noescape)) void(^)(void))block { - [self transactionWithoutNotifying:tokens block:block error:nil]; -} - -- (BOOL)transactionWithoutNotifying:(NSArray *)tokens block:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error { - [self beginWriteTransaction]; - block(); - if (_realm->is_in_transaction()) { - return [self commitWriteTransactionWithoutNotifying:tokens error:error]; - } - return YES; -} - -- (void)cancelWriteTransaction { - try { - _realm->cancel_transaction(); - } - catch (std::exception &ex) { - @throw RLMException(ex); - } -} - -- (void)invalidate { - if (_realm->is_in_transaction()) { - NSLog(@"WARNING: An RLMRealm instance was invalidated during a write " - "transaction and all pending changes have been rolled back."); - } - - [self detachAllEnumerators]; - - for (auto& objectInfo : _info) { - for (RLMObservationInfo *info : objectInfo.second.observedObjects) { - info->willChange(RLMInvalidatedKey); - } - } - - _realm->invalidate(); - - for (auto& objectInfo : _info) { - for (RLMObservationInfo *info : objectInfo.second.observedObjects) { - info->didChange(RLMInvalidatedKey); - } - objectInfo.second.releaseTable(); - } -} - -- (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference { - return [reference resolveReferenceInRealm:self]; -} - -/** - Replaces all string columns in this Realm with a string enumeration column and compacts the - database file. - - Cannot be called from a write transaction. - - Compaction will not occur if other `RLMRealm` instances exist. - - While compaction is in progress, attempts by other threads or processes to open the database will - wait. - - Be warned that resource requirements for compaction is proportional to the amount of live data in - the database. - - Compaction works by writing the database contents to a temporary database file and then replacing - the database with the temporary one. The name of the temporary file is formed by appending - `.tmp_compaction_space` to the name of the database. - - @return YES if the compaction succeeded. - */ -- (BOOL)compact { - // compact() automatically ends the read transaction, but we need to clean - // up cached state and send invalidated notifications when that happens, so - // explicitly end it first unless we're in a write transaction (in which - // case compact() will throw an exception) - if (!_realm->is_in_transaction()) { - [self invalidate]; - } - - try { - return _realm->compact(); - } - catch (std::exception const& ex) { - @throw RLMException(ex); - } -} - -- (void)dealloc { - if (_realm) { - if (_realm->is_in_transaction()) { - [self cancelWriteTransaction]; - NSLog(@"WARNING: An RLMRealm instance was deallocated during a write transaction and all " - "pending changes have been rolled back. Make sure to retain a reference to the " - "RLMRealm for the duration of the write transaction."); - } - } -} - -- (BOOL)refresh { - return _realm->refresh(); -} - -- (void)addObject:(__unsafe_unretained RLMObject *const)object { - RLMAddObjectToRealm(object, self, RLMUpdatePolicyError); -} - -- (void)addObjects:(id)objects { - for (RLMObject *obj in objects) { - if (![obj isKindOfClass:RLMObjectBase.class]) { - @throw RLMException(@"Cannot insert objects of type %@ with addObjects:. Only RLMObjects are supported.", - NSStringFromClass(obj.class)); - } - [self addObject:obj]; - } -} - -- (void)addOrUpdateObject:(RLMObject *)object { - // verify primary key - if (!object.objectSchema.primaryKeyProperty) { - @throw RLMException(@"'%@' does not have a primary key and can not be updated", object.objectSchema.className); - } - - RLMAddObjectToRealm(object, self, RLMUpdatePolicyUpdateAll); -} - -- (void)addOrUpdateObjects:(id)objects { - for (RLMObject *obj in objects) { - if (![obj isKindOfClass:RLMObjectBase.class]) { - @throw RLMException(@"Cannot add or update objects of type %@ with addOrUpdateObjects:. Only RLMObjects are" - " supported.", - NSStringFromClass(obj.class)); - } - [self addOrUpdateObject:obj]; - } -} - -- (void)deleteObject:(RLMObject *)object { - RLMDeleteObjectFromRealm(object, self); -} - -- (void)deleteObjects:(id)objects { - id idObjects = objects; - if ([idObjects respondsToSelector:@selector(realm)] - && [idObjects respondsToSelector:@selector(deleteObjectsFromRealm)]) { - if (self != (RLMRealm *)[idObjects realm]) { - @throw RLMException(@"Can only delete objects from the Realm they belong to."); - } - [idObjects deleteObjectsFromRealm]; - return; - } - if (auto array = RLMDynamicCast(objects)) { - if (array.type != RLMPropertyTypeObject) { - @throw RLMException(@"Cannot delete objects from RLMArray<%@>: only RLMObjects can be deleted.", - RLMTypeToString(array.type)); - } - } - for (RLMObject *obj in objects) { - if (![obj isKindOfClass:RLMObjectBase.class]) { - @throw RLMException(@"Cannot delete objects of type %@ with deleteObjects:. Only RLMObjects can be deleted.", - NSStringFromClass(obj.class)); - } - RLMDeleteObjectFromRealm(obj, self); - } -} - -- (void)deleteAllObjects { - RLMDeleteAllObjectsFromRealm(self); -} - -- (RLMResults *)allObjects:(NSString *)objectClassName { - return RLMGetObjects(self, objectClassName, nil); -} - -- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - RLMResults *results = [self objects:objectClassName where:predicateFormat args:args]; - va_end(args); - return results; -} - -- (RLMResults *)objects:(NSString *)objectClassName where:(NSString *)predicateFormat args:(va_list)args { - return [self objects:objectClassName withPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; -} - -- (RLMResults *)objects:(NSString *)objectClassName withPredicate:(NSPredicate *)predicate { - return RLMGetObjects(self, objectClassName, predicate); -} - -- (RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey { - return RLMGetObject(self, className, primaryKey); -} - -+ (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error { - RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; - try { - config.fileURL = fileURL; - config.encryptionKey = RLMRealmValidatedEncryptionKey(key); - - uint64_t version = Realm::get_schema_version(config.config); - if (version == realm::ObjectStore::NotVersioned) { - RLMSetErrorOrThrow([NSError errorWithDomain:RLMErrorDomain code:RLMErrorFail userInfo:@{NSLocalizedDescriptionKey:@"Cannot open an uninitialized realm in read-only mode"}], error); - } - return version; - } - catch (...) { - translateSharedGroupOpenException(config, error); - return RLMNotVersioned; - } -} - -+ (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error { - if (RLMGetAnyCachedRealmForPath(configuration.config.path)) { - @throw RLMException(@"Cannot migrate Realms that are already open."); - } - - NSError *localError; // Prevents autorelease - BOOL success; - @autoreleasepool { - success = [RLMRealm realmWithConfiguration:configuration error:&localError] != nil; - } - if (!success && error) { - *error = localError; // Must set outside pool otherwise will free anyway - } - return success; -} - -- (RLMObject *)createObject:(NSString *)className withValue:(id)value { - return (RLMObject *)RLMCreateObjectInRealmWithValue(self, className, value, RLMUpdatePolicyError); -} - -- (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(NSData *)key error:(NSError **)error { - key = RLMRealmValidatedEncryptionKey(key); - NSString *path = fileURL.path; - - try { - _realm->write_copy(path.UTF8String, {static_cast(key.bytes), key.length}); - return YES; - } - catch (...) { - __autoreleasing NSError *dummyError; - if (!error) { - error = &dummyError; - } - RLMRealmTranslateException(error); - return NO; - } - - return NO; -} - -+ (BOOL)fileExistsForConfiguration:(RLMRealmConfiguration *)config { - return [NSFileManager.defaultManager fileExistsAtPath:config.pathOnDisk]; -} - -+ (BOOL)deleteFilesForConfiguration:(RLMRealmConfiguration *)config error:(NSError **)error { - auto& path = config.config.path; - bool anyDeleted = false; - NSError *localError; - bool didCall = SharedGroup::call_with_lock(path, [&](auto const& path) { - NSURL *url = [NSURL fileURLWithPath:@(path.c_str())]; - NSFileManager *fm = NSFileManager.defaultManager; - - anyDeleted = [fm removeItemAtURL:url error:&localError]; - if (localError && localError.code != NSFileNoSuchFileError) { - return; - } - - [fm removeItemAtURL:[url URLByAppendingPathExtension:@"management"] error:&localError]; - if (localError && localError.code != NSFileNoSuchFileError) { - return; - } - - [fm removeItemAtURL:[url URLByAppendingPathExtension:@"note"] error:&localError]; - }); - if (error && localError && localError.code != NSFileNoSuchFileError) { - *error = localError; - } - else if (!didCall) { - if (error) { - NSString *msg = [NSString stringWithFormat:@"Realm file at path %s cannot be deleted because it is currently opened.", path.c_str()]; - *error = [NSError errorWithDomain:RLMErrorDomain - code:RLMErrorAlreadyOpen - userInfo:@{NSLocalizedDescriptionKey: msg}]; - } - } - return anyDeleted; -} - -#if REALM_ENABLE_SYNC -using Privilege = realm::ComputedPrivileges; -static bool hasPrivilege(realm::ComputedPrivileges actual, realm::ComputedPrivileges expected) { - return (static_cast(actual) & static_cast(expected)) == static_cast(expected); -} - -- (RLMRealmPrivileges)privilegesForRealm { - auto p = _realm->get_privileges(); - return { - .read = hasPrivilege(p, Privilege::Read), - .update = hasPrivilege(p, Privilege::Update), - .setPermissions = hasPrivilege(p, Privilege::SetPermissions), - .modifySchema = hasPrivilege(p, Privilege::ModifySchema), - }; -} - -- (RLMObjectPrivileges)privilegesForObject:(RLMObject *)object { - RLMVerifyAttached(object); - auto p = _realm->get_privileges(object->_row); - return { - .read = hasPrivilege(p, Privilege::Read), - .update = hasPrivilege(p, Privilege::Update), - .del = hasPrivilege(p, Privilege::Delete), - .setPermissions = hasPrivilege(p, Privilege::Delete), - }; -} - -- (RLMClassPrivileges)privilegesForClass:(Class)cls { - if (![cls respondsToSelector:@selector(_realmObjectName)]) { - @throw RLMException(@"Cannot get privileges for non-RLMObject class %@", cls); - } - return [self privilegesForClassNamed:[cls _realmObjectName] ?: [cls className]]; -} - -- (RLMClassPrivileges)privilegesForClassNamed:(NSString *)className { - auto p = _realm->get_privileges(className.UTF8String); - return { - .read = hasPrivilege(p, Privilege::Read), - .update = hasPrivilege(p, Privilege::Update), - .setPermissions = hasPrivilege(p, Privilege::SetPermissions), - .subscribe = hasPrivilege(p, Privilege::Query), - .create = hasPrivilege(p, Privilege::Create), - }; -} -#endif - -- (void)registerEnumerator:(RLMFastEnumerator *)enumerator { - if (!_collectionEnumerators) { - _collectionEnumerators = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]; - } - [_collectionEnumerators addObject:enumerator]; -} - -- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator { - [_collectionEnumerators removeObject:enumerator]; -} - -- (void)detachAllEnumerators { - for (RLMFastEnumerator *enumerator in _collectionEnumerators) { - [enumerator detach]; - } - _collectionEnumerators = nil; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm b/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm deleted file mode 100644 index 36721d8..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration+Sync.mm +++ /dev/null @@ -1,73 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMRealmConfiguration+Sync.h" - -#import "RLMRealmConfiguration_Private.hpp" -#import "RLMSyncConfiguration_Private.hpp" -#import "RLMSyncUser_Private.hpp" -#import "RLMSyncManager_Private.h" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -#import "sync/sync_config.hpp" -#import "sync/sync_manager.hpp" - -@implementation RLMRealmConfiguration (Sync) - -#pragma mark - API - -- (void)setSyncConfiguration:(RLMSyncConfiguration *)syncConfiguration { - if (self.config.should_compact_on_launch_function) { - @throw RLMException(@"Cannot set `syncConfiguration` when `shouldCompactOnLaunch` is set."); - } - RLMSyncUser *user = syncConfiguration.user; - if (user.state == RLMSyncUserStateError) { - @throw RLMException(@"Cannot set a sync configuration which has an errored-out user."); - } - - // Ensure sync manager is initialized, if it hasn't already been. - [RLMSyncManager sharedManager]; - NSAssert(user.identity, @"Cannot call this method on a user that doesn't have an identity."); - self.config.in_memory = false; - self.config.sync_config = std::make_shared([syncConfiguration rawConfiguration]); - self.config.schema_mode = realm::SchemaMode::Additive; - - if (syncConfiguration.customFileURL) { - self.config.path = syncConfiguration.customFileURL.path.UTF8String; - } else { - self.config.path = SyncManager::shared().path_for_realm(*[user _syncUser], - self.config.sync_config->realm_url()); - } - - if (!self.config.encryption_key.empty()) { - auto& sync_encryption_key = self.config.sync_config->realm_encryption_key; - sync_encryption_key = std::array(); - std::copy_n(self.config.encryption_key.begin(), 64, sync_encryption_key->begin()); - } -} - -- (RLMSyncConfiguration *)syncConfiguration { - if (!self.config.sync_config) { - return nil; - } - realm::SyncConfig& sync_config = *self.config.sync_config; - return [[RLMSyncConfiguration alloc] initWithRawConfig:sync_config]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration.mm b/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration.mm deleted file mode 100644 index 114b8d6..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMRealmConfiguration.mm +++ /dev/null @@ -1,318 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMRealmConfiguration_Private.h" - -#import "RLMObjectSchema_Private.hpp" -#import "RLMRealm_Private.h" -#import "RLMSchema_Private.hpp" -#import "RLMUtil.hpp" - -#import "schema.hpp" -#import "shared_realm.hpp" - -#if REALM_ENABLE_SYNC -#import "sync/sync_config.hpp" -#else -@class RLMSyncConfiguration; -#endif - -static NSString *const c_RLMRealmConfigurationProperties[] = { - @"fileURL", - @"inMemoryIdentifier", - @"encryptionKey", - @"readOnly", - @"schemaVersion", - @"migrationBlock", - @"deleteRealmIfMigrationNeeded", - @"shouldCompactOnLaunch", - @"dynamic", - @"customSchema", -}; - -static NSString *const c_defaultRealmFileName = @"default.realm"; -RLMRealmConfiguration *s_defaultConfiguration; - -NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *bundleIdentifier) { - return [RLMDefaultDirectoryForBundleIdentifier(bundleIdentifier) - stringByAppendingPathComponent:fileName]; -} - -NSString *RLMRealmPathForFile(NSString *fileName) { - static NSString *directory = RLMDefaultDirectoryForBundleIdentifier(nil); - return [directory stringByAppendingPathComponent:fileName]; -} - -@implementation RLMRealmConfiguration { - realm::Realm::Config _config; -} - -- (realm::Realm::Config&)config { - return _config; -} - -+ (instancetype)defaultConfiguration { - return [[self rawDefaultConfiguration] copy]; -} - -+ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration { - if (!configuration) { - @throw RLMException(@"Cannot set the default configuration to nil."); - } - @synchronized(c_defaultRealmFileName) { - s_defaultConfiguration = [configuration copy]; - } -} - -+ (RLMRealmConfiguration *)rawDefaultConfiguration { - RLMRealmConfiguration *configuration; - @synchronized(c_defaultRealmFileName) { - if (!s_defaultConfiguration) { - s_defaultConfiguration = [[RLMRealmConfiguration alloc] init]; - } - configuration = s_defaultConfiguration; - } - return configuration; -} - -+ (void)resetRealmConfigurationState { - @synchronized(c_defaultRealmFileName) { - s_defaultConfiguration = nil; - } -} - -- (instancetype)init { - self = [super init]; - if (self) { - static NSURL *defaultRealmURL = [NSURL fileURLWithPath:RLMRealmPathForFile(c_defaultRealmFileName)]; - self.fileURL = defaultRealmURL; - self.schemaVersion = 0; - self.cache = YES; - - // We have our own caching of RLMRealm instances, so the ObjectStore - // cache is at best pointless, and may result in broken behavior when - // a realm::Realm instance outlives the RLMRealm (due to collection - // notifiers being in the middle of running when the RLMRealm is - // dealloced) and then reused for a new RLMRealm - _config.cache = false; - } - - return self; -} - -- (instancetype)copyWithZone:(NSZone *)zone { - RLMRealmConfiguration *configuration = [[[self class] allocWithZone:zone] init]; - configuration->_config = _config; - configuration->_cache = _cache; - configuration->_dynamic = _dynamic; - configuration->_migrationBlock = _migrationBlock; - configuration->_shouldCompactOnLaunch = _shouldCompactOnLaunch; - configuration->_customSchema = _customSchema; - return configuration; -} - -- (NSString *)description { - NSMutableString *string = [NSMutableString stringWithFormat:@"%@ {\n", self.class]; - for (NSString *key : c_RLMRealmConfigurationProperties) { - NSString *description = [[self valueForKey:key] description]; - description = [description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]; - - [string appendFormat:@"\t%@ = %@;\n", key, description]; - } - return [string stringByAppendingString:@"}"]; -} - -static void RLMNSStringToStdString(std::string &out, NSString *in) { - out.resize([in maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]); - if (out.empty()) { - return; - } - - NSUInteger size = out.size(); - [in getBytes:&out[0] - maxLength:size - usedLength:&size - encoding:NSUTF8StringEncoding - options:0 range:{0, in.length} remainingRange:nullptr]; - out.resize(size); -} - -- (NSURL *)fileURL { - if (_config.in_memory || _config.sync_config) { - return nil; - } - return [NSURL fileURLWithPath:@(_config.path.c_str())]; -} - -- (void)setFileURL:(NSURL *)fileURL { - NSString *path = fileURL.path; - if (path.length == 0) { - @throw RLMException(@"Realm path must not be empty"); - } - _config.sync_config = nullptr; - - RLMNSStringToStdString(_config.path, path); - _config.in_memory = false; -} - -- (NSString *)inMemoryIdentifier { - if (!_config.in_memory) { - return nil; - } - return [@(_config.path.c_str()) lastPathComponent]; -} - -- (void)setInMemoryIdentifier:(NSString *)inMemoryIdentifier { - if (inMemoryIdentifier.length == 0) { - @throw RLMException(@"In-memory identifier must not be empty"); - } - _config.sync_config = nullptr; - - RLMNSStringToStdString(_config.path, [NSTemporaryDirectory() stringByAppendingPathComponent:inMemoryIdentifier]); - _config.in_memory = true; -} - -- (NSData *)encryptionKey { - return _config.encryption_key.empty() ? nil : [NSData dataWithBytes:_config.encryption_key.data() length:_config.encryption_key.size()]; -} - -- (void)setEncryptionKey:(NSData * __nullable)encryptionKey { - if (NSData *key = RLMRealmValidatedEncryptionKey(encryptionKey)) { - auto bytes = static_cast(key.bytes); - _config.encryption_key.assign(bytes, bytes + key.length); -#if REALM_ENABLE_SYNC - if (_config.sync_config) { - auto& sync_encryption_key = self.config.sync_config->realm_encryption_key; - sync_encryption_key = std::array(); - std::copy_n(_config.encryption_key.begin(), 64, sync_encryption_key->begin()); - } -#endif - } - else { - _config.encryption_key.clear(); -#if REALM_ENABLE_SYNC - if (_config.sync_config) - _config.sync_config->realm_encryption_key = realm::util::none; -#endif - } -} - -- (BOOL)readOnly { - return _config.immutable(); -} - -- (void)setReadOnly:(BOOL)readOnly { - if (readOnly) { - if (self.deleteRealmIfMigrationNeeded) { - @throw RLMException(@"Cannot set `readOnly` when `deleteRealmIfMigrationNeeded` is set."); - } else if (self.shouldCompactOnLaunch) { - @throw RLMException(@"Cannot set `readOnly` when `shouldCompactOnLaunch` is set."); - } - _config.schema_mode = realm::SchemaMode::Immutable; - } - else if (self.readOnly) { - _config.schema_mode = realm::SchemaMode::Automatic; - } -} - -- (uint64_t)schemaVersion { - return _config.schema_version; -} - -- (void)setSchemaVersion:(uint64_t)schemaVersion { - if (schemaVersion == RLMNotVersioned) { - @throw RLMException(@"Cannot set schema version to %llu (RLMNotVersioned)", RLMNotVersioned); - } - _config.schema_version = schemaVersion; -} - -- (BOOL)deleteRealmIfMigrationNeeded { - return _config.schema_mode == realm::SchemaMode::ResetFile; -} - -- (void)setDeleteRealmIfMigrationNeeded:(BOOL)deleteRealmIfMigrationNeeded { - if (deleteRealmIfMigrationNeeded) { - if (self.readOnly) { - @throw RLMException(@"Cannot set `deleteRealmIfMigrationNeeded` when `readOnly` is set."); - } - _config.schema_mode = realm::SchemaMode::ResetFile; - } - else if (self.deleteRealmIfMigrationNeeded) { - _config.schema_mode = realm::SchemaMode::Automatic; - } -} - -- (NSArray *)objectClasses { - return [_customSchema.objectSchema valueForKeyPath:@"objectClass"]; -} - -- (void)setObjectClasses:(NSArray *)objectClasses { - self.customSchema = [RLMSchema schemaWithObjectClasses:objectClasses]; -} - -- (void)setDynamic:(bool)dynamic { - _dynamic = dynamic; - self.cache = !dynamic; -} - -- (bool)disableFormatUpgrade { - return _config.disable_format_upgrade; -} - -- (void)setDisableFormatUpgrade:(bool)disableFormatUpgrade { - _config.disable_format_upgrade = disableFormatUpgrade; -} - -- (realm::SchemaMode)schemaMode { - return _config.schema_mode; -} - -- (void)setSchemaMode:(realm::SchemaMode)mode { - _config.schema_mode = mode; -} - -- (NSString *)pathOnDisk { - return @(_config.path.c_str()); -} - -- (void)setShouldCompactOnLaunch:(RLMShouldCompactOnLaunchBlock)shouldCompactOnLaunch { - if (shouldCompactOnLaunch) { - if (self.readOnly) { - @throw RLMException(@"Cannot set `shouldCompactOnLaunch` when `readOnly` is set."); - } - _config.should_compact_on_launch_function = [=](size_t totalBytes, size_t usedBytes) { - return shouldCompactOnLaunch(totalBytes, usedBytes); - }; - } - else { - _config.should_compact_on_launch_function = nullptr; - } - _shouldCompactOnLaunch = shouldCompactOnLaunch; -} - -- (void)setCustomSchemaWithoutCopying:(RLMSchema *)schema { - _customSchema = schema; -} - -#if !REALM_ENABLE_SYNC -- (RLMSyncConfiguration *)syncConfiguration { - return nil; -} -#endif - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMRealmUtil.mm b/Lesson14/Pods/Realm/Realm/RLMRealmUtil.mm deleted file mode 100644 index 10d6ff3..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMRealmUtil.mm +++ /dev/null @@ -1,147 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMRealmUtil.hpp" - -#import "RLMObjectSchema_Private.hpp" -#import "RLMObservation.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMUtil.hpp" - -#import -#import - -#import "binding_context.hpp" - -#import -#import -#import -#import -#import -#import - -// Global realm state -static std::mutex& s_realmCacheMutex = *new std::mutex(); -static std::map& s_realmsPerPath = *new std::map(); - -void RLMCacheRealm(std::string const& path, __unsafe_unretained RLMRealm *const realm) { - std::lock_guard lock(s_realmCacheMutex); - NSMapTable *realms = s_realmsPerPath[path]; - if (!realms) { - s_realmsPerPath[path] = realms = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsOpaquePersonality|NSPointerFunctionsOpaqueMemory - valueOptions:NSPointerFunctionsWeakMemory]; - } - [realms setObject:realm forKey:(__bridge id)pthread_self()]; -} - -RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path) { - std::lock_guard lock(s_realmCacheMutex); - return [s_realmsPerPath[path] objectEnumerator].nextObject; -} - -RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path) { - std::lock_guard lock(s_realmCacheMutex); - return [s_realmsPerPath[path] objectForKey:(__bridge id)pthread_self()]; -} - -void RLMClearRealmCache() { - std::lock_guard lock(s_realmCacheMutex); - s_realmsPerPath.clear(); -} - -bool RLMIsInRunLoop() { - // The main thread may not be in a run loop yet if we're called from - // something like `applicationDidFinishLaunching:`, but it presumably will - // be in the future - if ([NSThread isMainThread]) { - return true; - } - // Current mode indicates why the current callout from the runloop was made, - // and is null if a runloop callout isn't currently being processed - if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) { - CFRelease(mode); - return true; - } - return false; -} - -namespace { -class RLMNotificationHelper : public realm::BindingContext { -public: - RLMNotificationHelper(RLMRealm *realm) : _realm(realm) { } - - bool can_deliver_notifications() const noexcept override { - return RLMIsInRunLoop(); - } - - void changes_available() override { - @autoreleasepool { - auto realm = _realm; - if (realm && !realm.autorefresh) { - [realm sendNotifications:RLMRealmRefreshRequiredNotification]; - } - } - } - - std::vector get_observed_rows() override { - @autoreleasepool { - if (auto realm = _realm) { - [realm detachAllEnumerators]; - return RLMGetObservedRows(realm->_info); - } - return {}; - } - } - - void will_change(std::vector const& observed, std::vector const& invalidated) override { - @autoreleasepool { - RLMWillChange(observed, invalidated); - } - } - - void did_change(std::vector const& observed, std::vector const& invalidated, bool version_changed) override { - try { - @autoreleasepool { - RLMDidChange(observed, invalidated); - if (version_changed) { - [_realm sendNotifications:RLMRealmDidChangeNotification]; - } - } - } - catch (...) { - // This can only be called during a write transaction if it was - // called due to the transaction beginning, so cancel it to ensure - // exceptions thrown here behave the same as exceptions thrown when - // actually beginning the write - if (_realm.inWriteTransaction) { - [_realm cancelWriteTransaction]; - } - throw; - } - } - -private: - // This is owned by the realm, so it needs to not retain the realm - __weak RLMRealm *const _realm; -}; -} // anonymous namespace - - -std::unique_ptr RLMCreateBindingContext(__unsafe_unretained RLMRealm *const realm) { - return std::unique_ptr(new RLMNotificationHelper(realm)); -} diff --git a/Lesson14/Pods/Realm/Realm/RLMResults.mm b/Lesson14/Pods/Realm/Realm/RLMResults.mm deleted file mode 100644 index 77b1471..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMResults.mm +++ /dev/null @@ -1,528 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMResults_Private.hpp" - -#import "RLMAccessor.hpp" -#import "RLMArray_Private.hpp" -#import "RLMCollection_Private.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObject_Private.hpp" -#import "RLMObservation.hpp" -#import "RLMProperty_Private.h" -#import "RLMQueryUtil.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMSchema_Private.h" -#import "RLMThreadSafeReference_Private.hpp" -#import "RLMUtil.hpp" - -#import "results.hpp" -#import "shared_realm.hpp" - -#import -#import - -using namespace realm; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wincomplete-implementation" -@implementation RLMNotificationToken -@end -#pragma clang diagnostic pop - -@interface RLMResults () -@end - -// -// RLMResults implementation -// -@implementation RLMResults { - RLMRealm *_realm; - RLMClassInfo *_info; -} - -- (instancetype)initPrivate { - self = [super init]; - return self; -} - -- (instancetype)initWithResults:(Results)results { - if (self = [super init]) { - _results = std::move(results); - } - return self; -} - -static void assertKeyPathIsNotNested(NSString *keyPath) { - if ([keyPath rangeOfString:@"."].location != NSNotFound) { - @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators."); - } -} - -void RLMThrowResultsError(NSString *aggregateMethod) { - try { - throw; - } - catch (realm::InvalidTransactionException const&) { - @throw RLMException(@"Cannot modify Results outside of a write transaction."); - } - catch (realm::IncorrectThreadException const&) { - @throw RLMException(@"Realm accessed from incorrect thread."); - } - catch (realm::Results::InvalidatedException const&) { - @throw RLMException(@"RLMResults has been invalidated."); - } - catch (realm::Results::DetatchedAccessorException const&) { - @throw RLMException(@"Object has been invalidated."); - } - catch (realm::Results::IncorrectTableException const& e) { - @throw RLMException(@"Object of type '%s' does not match RLMResults type '%s'.", - e.actual.data(), e.expected.data()); - } - catch (realm::Results::OutOfBoundsIndexException const& e) { - @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).", - e.requested, e.valid_count); - } - catch (realm::Results::UnsupportedColumnTypeException const& e) { - @throw RLMException(@"%@ is not supported for %s%s property '%s'.", - aggregateMethod, - string_for_property_type(e.property_type), - is_nullable(e.property_type) ? "?" : "", - e.column_name.data()); - } - catch (std::exception const& e) { - @throw RLMException(e); - } -} - -- (instancetype)initWithObjectInfo:(RLMClassInfo&)info - results:(realm::Results&&)results { - if (self = [super init]) { - _results = std::move(results); - _realm = info.realm; - _info = &info; - } - return self; -} - -+ (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info - results:(realm::Results&&)results { - return [[self alloc] initWithObjectInfo:info results:std::move(results)]; -} - -+ (instancetype)emptyDetachedResults { - return [[self alloc] initPrivate]; -} - -- (instancetype)subresultsWithResults:(realm::Results)results { - return [self.class resultsWithObjectInfo:*_info results:std::move(results)]; -} - -static inline void RLMResultsValidateInWriteTransaction(__unsafe_unretained RLMResults *const ar) { - ar->_realm->_realm->verify_thread(); - ar->_realm->_realm->verify_in_write(); -} - -- (BOOL)isInvalidated { - return translateRLMResultsErrors([&] { return !_results.is_valid(); }); -} - -- (NSUInteger)count { - return translateRLMResultsErrors([&] { return _results.size(); }); -} - -- (RLMPropertyType)type { - return translateRLMResultsErrors([&] { - return static_cast(_results.get_type() & ~realm::PropertyType::Nullable); - }); -} - -- (BOOL)isOptional { - return translateRLMResultsErrors([&] { - return is_nullable(_results.get_type()); - }); -} - -- (NSString *)objectClassName { - return translateRLMResultsErrors([&] { - if (_info && _results.get_type() == realm::PropertyType::Object) { - return _info->rlmObjectSchema.className; - } - return (NSString *)nil; - }); -} - -- (RLMClassInfo *)objectInfo { - return _info; -} - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - objects:(__unused __unsafe_unretained id [])buffer - count:(NSUInteger)len { - if (!_info) { - return 0; - } - return RLMFastEnumerate(state, len, self); -} - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args]; - va_end(args); - return index; -} - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args { - return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat - arguments:args]]; -} - -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate { - if (_results.get_mode() == Results::Mode::Empty) { - return NSNotFound; - } - - return translateRLMResultsErrors([&] { - if (_results.get_type() != realm::PropertyType::Object) { - @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); - } - return RLMConvertNotFound(_results.index_of(RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group))); - }); -} - -- (id)objectAtIndex:(NSUInteger)index { - RLMAccessorContext ctx(*_info); - return translateRLMResultsErrors([&] { - return _results.get(ctx, index); - }); -} - -- (id)firstObject { - if (!_info) { - return nil; - } - RLMAccessorContext ctx(*_info); - return translateRLMResultsErrors([&] { - return _results.first(ctx); - }); -} - -- (id)lastObject { - if (!_info) { - return nil; - } - RLMAccessorContext ctx(*_info); - return translateRLMResultsErrors([&] { - return _results.last(ctx); - }); -} - -- (NSUInteger)indexOfObject:(RLMObject *)object { - if (!_info || !object || (!object->_realm && !object.invalidated)) { - return NSNotFound; - } - RLMAccessorContext ctx(*_info); - return translateRLMResultsErrors([&] { - return RLMConvertNotFound(_results.index_of(ctx, object)); - }); -} - -- (id)valueForKeyPath:(NSString *)keyPath { - if ([keyPath characterAtIndex:0] != '@') { - return [super valueForKeyPath:keyPath]; - } - if ([keyPath isEqualToString:@"@count"]) { - return @(self.count); - } - - NSRange operatorRange = [keyPath rangeOfString:@"." options:NSLiteralSearch]; - NSUInteger keyPathLength = keyPath.length; - NSUInteger separatorIndex = operatorRange.location != NSNotFound ? operatorRange.location : keyPathLength; - NSString *operatorName = [keyPath substringWithRange:NSMakeRange(1, separatorIndex - 1)]; - SEL opSelector = NSSelectorFromString([NSString stringWithFormat:@"_%@ForKeyPath:", operatorName]); - if (![self respondsToSelector:opSelector]) { - @throw RLMException(@"Unsupported KVC collection operator found in key path '%@'", keyPath); - } - if (separatorIndex >= keyPathLength - 1) { - @throw RLMException(@"Missing key path for KVC collection operator %@ in key path '%@'", - operatorName, keyPath); - } - NSString *operatorKeyPath = [keyPath substringFromIndex:separatorIndex + 1]; - return ((id(*)(id, SEL, id))objc_msgSend)(self, opSelector, operatorKeyPath); -} - -- (id)valueForKey:(NSString *)key { - if (!_info) { - return @[]; - } - return translateRLMResultsErrors([&] { - return RLMCollectionValueForKey(_results, key, *_info); - }); -} - -- (void)setValue:(id)value forKey:(NSString *)key { - translateRLMResultsErrors([&] { RLMResultsValidateInWriteTransaction(self); }); - RLMCollectionSetValueForKey(self, key, value); -} - -- (NSNumber *)_aggregateForKeyPath:(NSString *)keyPath - method:(util::Optional (Results::*)(size_t))method - methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty { - assertKeyPathIsNotNested(keyPath); - return [self aggregate:keyPath method:method methodName:methodName returnNilForEmpty:returnNilForEmpty]; -} - -- (NSNumber *)_minForKeyPath:(NSString *)keyPath { - return [self _aggregateForKeyPath:keyPath method:&Results::min methodName:@"@min" returnNilForEmpty:YES]; -} - -- (NSNumber *)_maxForKeyPath:(NSString *)keyPath { - return [self _aggregateForKeyPath:keyPath method:&Results::max methodName:@"@max" returnNilForEmpty:YES]; -} - -- (NSNumber *)_sumForKeyPath:(NSString *)keyPath { - return [self _aggregateForKeyPath:keyPath method:&Results::sum methodName:@"@sum" returnNilForEmpty:NO]; -} - -- (NSNumber *)_avgForKeyPath:(NSString *)keyPath { - assertKeyPathIsNotNested(keyPath); - return [self averageOfProperty:keyPath]; -} - -- (NSArray *)_unionOfObjectsForKeyPath:(NSString *)keyPath { - assertKeyPathIsNotNested(keyPath); - return translateRLMResultsErrors([&] { - return RLMCollectionValueForKey(_results, keyPath, *_info); - }); -} - -- (NSArray *)_distinctUnionOfObjectsForKeyPath:(NSString *)keyPath { - return [NSSet setWithArray:[self _unionOfObjectsForKeyPath:keyPath]].allObjects; -} - -- (NSArray *)_unionOfArraysForKeyPath:(NSString *)keyPath { - assertKeyPathIsNotNested(keyPath); - if ([keyPath isEqualToString:@"self"]) { - @throw RLMException(@"self is not a valid key-path for a KVC array collection operator as 'unionOfArrays'."); - } - - return translateRLMResultsErrors([&] { - NSMutableArray *flatArray = [NSMutableArray new]; - for (id array in RLMCollectionValueForKey(_results, keyPath, *_info)) { - for (id value in array) { - [flatArray addObject:value]; - } - } - return flatArray; - }); -} - -- (NSArray *)_distinctUnionOfArraysForKeyPath:(__unused NSString *)keyPath { - return [NSSet setWithArray:[self _unionOfArraysForKeyPath:keyPath]].allObjects; -} - -- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... { - va_list args; - va_start(args, predicateFormat); - RLMResults *results = [self objectsWhere:predicateFormat args:args]; - va_end(args); - return results; -} - -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args { - return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]]; -} - -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate { - return translateRLMResultsErrors([&] { - if (_results.get_mode() == Results::Mode::Empty) { - return self; - } - if (_results.get_type() != realm::PropertyType::Object) { - @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects"); - } - auto query = RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group); - return [self subresultsWithResults:_results.filter(std::move(query))]; - }); -} - -- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending { - return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]]; -} - -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties { - if (properties.count == 0) { - return self; - } - return translateRLMResultsErrors([&] { - if (_results.get_mode() == Results::Mode::Empty) { - return self; - } - return [self subresultsWithResults:_results.sort(RLMSortDescriptorsToKeypathArray(properties))]; - }); -} - -- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray *)keyPaths { - for (NSString *keyPath in keyPaths) { - if ([keyPath rangeOfString:@"@"].location != NSNotFound) { - @throw RLMException(@"Cannot distinct on keypath '%@': KVC collection operators are not supported.", keyPath); - } - } - - return translateRLMResultsErrors([&] { - if (_results.get_mode() == Results::Mode::Empty) { - return self; - } - - std::vector keyPathsVector; - for (NSString *keyPath in keyPaths) { - keyPathsVector.push_back(keyPath.UTF8String); - } - - return [self subresultsWithResults:_results.distinct(keyPathsVector)]; - }); -} - -- (id)objectAtIndexedSubscript:(NSUInteger)index { - return [self objectAtIndex:index]; -} - -- (id)aggregate:(NSString *)property method:(util::Optional (Results::*)(size_t))method - methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty { - if (_results.get_mode() == Results::Mode::Empty) { - return returnNilForEmpty ? nil : @0; - } - size_t column = 0; - if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) { - column = _info->tableColumn(property); - } - - auto value = translateRLMResultsErrors([&] { return (_results.*method)(column); }, methodName); - return value ? RLMMixedToObjc(*value) : nil; -} - -- (id)minOfProperty:(NSString *)property { - return [self aggregate:property method:&Results::min - methodName:@"minOfProperty" returnNilForEmpty:YES]; -} - -- (id)maxOfProperty:(NSString *)property { - return [self aggregate:property method:&Results::max - methodName:@"maxOfProperty" returnNilForEmpty:YES]; -} - -- (id)sumOfProperty:(NSString *)property { - return [self aggregate:property method:&Results::sum - methodName:@"sumOfProperty" returnNilForEmpty:NO]; -} - -- (id)averageOfProperty:(NSString *)property { - if (_results.get_mode() == Results::Mode::Empty) { - return nil; - } - size_t column = 0; - if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) { - column = _info->tableColumn(property); - } - auto value = translateRLMResultsErrors([&] { return _results.average(column); }, @"averageOfProperty"); - return value ? @(*value) : nil; -} - -- (void)deleteObjectsFromRealm { - if (self.type != RLMPropertyTypeObject) { - @throw RLMException(@"Cannot delete objects from RLMResults<%@>: only RLMObjects can be deleted.", - RLMTypeToString(self.type)); - } - return translateRLMResultsErrors([&] { - if (_results.get_mode() == Results::Mode::Table) { - RLMResultsValidateInWriteTransaction(self); - RLMClearTable(*_info); - } - else { - RLMTrackDeletions(_realm, [&] { _results.clear(); }); - } - }); -} - -- (NSString *)description { - return RLMDescriptionWithMaxDepth(@"RLMResults", self, RLMDescriptionMaxDepth); -} - -- (realm::TableView)tableView { - return translateRLMResultsErrors([&] { return _results.get_tableview(); }); -} - -- (RLMFastEnumerator *)fastEnumerator { - return translateRLMResultsErrors([&] { - return [[RLMFastEnumerator alloc] initWithResults:_results collection:self - classInfo:*_info]; - }); -} - -// The compiler complains about the method's argument type not matching due to -// it not having the generic type attached, but it doesn't seem to be possible -// to actually include the generic type -// http://www.openradar.me/radar?id=6135653276319744 -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wmismatched-parameter-types" -- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *, RLMCollectionChange *, NSError *))block { - if (!_realm) { - @throw RLMException(@"Linking objects notifications are only supported on managed objects."); - } - [_realm verifyNotificationsAreSupported:true]; - return RLMAddNotificationBlock(self, _results, block, true); -} -#pragma clang diagnostic pop - -- (BOOL)isAttached -{ - return !!_realm; -} - -#pragma mark - Thread Confined Protocol Conformance - -- (std::unique_ptr)makeThreadSafeReference { - return std::make_unique>(_realm->_realm->obtain_thread_safe_reference(_results)); -} - -- (id)objectiveCMetadata { - return nil; -} - -+ (instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference - metadata:(__unused id)metadata - realm:(RLMRealm *)realm { - REALM_ASSERT_DEBUG(dynamic_cast *>(reference.get())); - auto results_reference = static_cast *>(reference.get()); - - Results results = realm->_realm->resolve_thread_safe_reference(std::move(*results_reference)); - - return [RLMResults resultsWithObjectInfo:realm->_info[RLMStringDataToNSString(results.get_object_type())] - results:std::move(results)]; -} - -@end - -@implementation RLMLinkingObjects -- (NSString *)description { - return RLMDescriptionWithMaxDepth(@"RLMLinkingObjects", self, RLMDescriptionMaxDepth); -} -@end - diff --git a/Lesson14/Pods/Realm/Realm/RLMSchema.mm b/Lesson14/Pods/Realm/Realm/RLMSchema.mm deleted file mode 100644 index 0787125..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSchema.mm +++ /dev/null @@ -1,378 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMSchema_Private.h" - -#import "RLMAccessor.h" -#import "RLMObjectBase_Private.h" -#import "RLMObject_Private.hpp" -#import "RLMObjectSchema_Private.hpp" -#import "RLMProperty_Private.h" -#import "RLMRealm_Private.hpp" -#import "RLMSwiftSupport.h" -#import "RLMUtil.hpp" - -#import "object_schema.hpp" -#import "object_store.hpp" -#import "schema.hpp" - -#import - -#import -#include - -using namespace realm; - -const uint64_t RLMNotVersioned = realm::ObjectStore::NotVersioned; - -// RLMSchema private properties -@interface RLMSchema () -@property (nonatomic, readwrite) NSMutableDictionary *objectSchemaByName; -@end - -// Private RLMSchema subclass that skips class registration on lookup -@interface RLMPrivateSchema : RLMSchema -@end -@implementation RLMPrivateSchema -- (RLMObjectSchema *)schemaForClassName:(NSString *)className { - return self.objectSchemaByName[className]; -} - -- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className { - return [self schemaForClassName:className]; -} -@end - -static RLMSchema *s_sharedSchema = [[RLMSchema alloc] init]; -static NSMutableDictionary *s_localNameToClass = [[NSMutableDictionary alloc] init]; -static RLMSchema *s_privateSharedSchema = [[RLMPrivateSchema alloc] init]; - -static enum class SharedSchemaState { - Uninitialized, - Initializing, - Initialized -} s_sharedSchemaState = SharedSchemaState::Uninitialized; - -@implementation RLMSchema { - NSArray *_objectSchema; - realm::Schema _objectStoreSchema; -} - -// Caller must @synchronize on s_localNameToClass -static RLMObjectSchema *RLMRegisterClass(Class cls) { - if (RLMObjectSchema *schema = s_privateSharedSchema[[cls className]]) { - return schema; - } - - auto prevState = s_sharedSchemaState; - s_sharedSchemaState = SharedSchemaState::Initializing; - RLMObjectSchema *schema = [RLMObjectSchema schemaForObjectClass:cls]; - s_sharedSchemaState = prevState; - - // set unmanaged class on shared shema for unmanaged object creation - schema.unmanagedClass = RLMUnmanagedAccessorClassForObjectClass(schema.objectClass, schema); - - // override sharedSchema class methods for performance - RLMReplaceSharedSchemaMethod(cls, schema); - - s_privateSharedSchema.objectSchemaByName[schema.className] = schema; - if ([cls shouldIncludeInDefaultSchema] && prevState != SharedSchemaState::Initialized) { - s_sharedSchema.objectSchemaByName[schema.className] = schema; - } - - return schema; -} - -// Caller must @synchronize on s_localNameToClass -static void RLMRegisterClassLocalNames(Class *classes, NSUInteger count) { - for (NSUInteger i = 0; i < count; i++) { - Class cls = classes[i]; - if (!RLMIsObjectSubclass(cls)) { - continue; - } - if ([cls _realmIgnoreClass]) { - continue; - } - - NSString *className = NSStringFromClass(cls); - if ([className hasPrefix:@"RLM:"] || [className hasPrefix:@"NSKVONotifying"]) { - continue; - } - - if ([RLMSwiftSupport isSwiftClassName:className]) { - className = [RLMSwiftSupport demangleClassName:className]; - } - // NSStringFromClass demangles the names for top-level Swift classes - // but not for nested classes. _T indicates it's a Swift symbol, t - // indicates it's a type, and C indicates it's a class. - else if ([className hasPrefix:@"_TtC"]) { - @throw RLMException(@"RLMObject subclasses cannot be nested within other declarations. Please move %@ to global scope.", className); - } - - if (Class existingClass = s_localNameToClass[className]) { - if (existingClass != cls) { - @throw RLMException(@"RLMObject subclasses with the same name cannot be included twice in the same target. " - @"Please make sure '%@' is only linked once to your current target.", className); - } - continue; - } - - s_localNameToClass[className] = cls; - RLMReplaceClassNameMethod(cls, className); - } -} - -- (instancetype)init { - self = [super init]; - if (self) { - _objectSchemaByName = [[NSMutableDictionary alloc] init]; - } - return self; -} - -- (NSArray *)objectSchema { - if (!_objectSchema) { - _objectSchema = [_objectSchemaByName allValues]; - } - return _objectSchema; -} - -- (void)setObjectSchema:(NSArray *)objectSchema { - _objectSchema = objectSchema; - _objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:objectSchema.count]; - for (RLMObjectSchema *object in objectSchema) { - [_objectSchemaByName setObject:object forKey:object.className]; - } -} - -- (RLMObjectSchema *)schemaForClassName:(NSString *)className { - if (RLMObjectSchema *schema = _objectSchemaByName[className]) { - return schema; // fast path for already-initialized schemas - } else if (Class cls = [RLMSchema classForString:className]) { - [cls sharedSchema]; // initialize the schema - return _objectSchemaByName[className]; // try again - } else { - return nil; - } -} - -- (RLMObjectSchema *)objectForKeyedSubscript:(__unsafe_unretained NSString *const)className { - RLMObjectSchema *schema = [self schemaForClassName:className]; - if (!schema) { - @throw RLMException(@"Object type '%@' not managed by the Realm", className); - } - return schema; -} - -+ (instancetype)schemaWithObjectClasses:(NSArray *)classes { - NSUInteger count = classes.count; - auto classArray = std::make_unique<__unsafe_unretained Class[]>(count); - [classes getObjects:classArray.get() range:NSMakeRange(0, count)]; - - RLMSchema *schema = [[self alloc] init]; - @synchronized(s_localNameToClass) { - RLMRegisterClassLocalNames(classArray.get(), count); - - schema->_objectSchemaByName = [NSMutableDictionary dictionaryWithCapacity:count]; - for (Class cls in classes) { - if (!RLMIsObjectSubclass(cls)) { - @throw RLMException(@"Can't add non-Object type '%@' to a schema.", cls); - } - schema->_objectSchemaByName[[cls className]] = RLMRegisterClass(cls); - } - } - - NSMutableArray *errors = [NSMutableArray new]; - // Verify that all of the targets of links are included in the class list - [schema->_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(id, RLMObjectSchema *objectSchema, BOOL *) { - for (RLMProperty *prop in objectSchema.properties) { - if (prop.type != RLMPropertyTypeObject) { - continue; - } - if (!schema->_objectSchemaByName[prop.objectClassName]) { - [errors addObject:[NSString stringWithFormat:@"- '%@.%@' links to class '%@', which is missing from the list of classes managed by the Realm", objectSchema.className, prop.name, prop.objectClassName]]; - } - } - }]; - if (errors.count) { - @throw RLMException(@"Invalid class subset list:\n%@", [errors componentsJoinedByString:@"\n"]); - } - - return schema; -} - -+ (RLMObjectSchema *)sharedSchemaForClass:(Class)cls { - @synchronized(s_localNameToClass) { - // We create instances of Swift objects during schema init, and they - // obviously need to not also try to initialize the schema - if (s_sharedSchemaState == SharedSchemaState::Initializing) { - return nil; - } - - RLMRegisterClassLocalNames(&cls, 1); - RLMObjectSchema *objectSchema = RLMRegisterClass(cls); - [cls initializeLinkedObjectSchemas]; - return objectSchema; - } -} - -+ (instancetype)partialSharedSchema { - return s_sharedSchema; -} - -+ (instancetype)partialPrivateSharedSchema { - return s_privateSharedSchema; -} - -// schema based on runtime objects -+ (instancetype)sharedSchema { - @synchronized(s_localNameToClass) { - // We replace this method with one which just returns s_sharedSchema - // once initialization is complete, but we still need to check if it's - // already complete because it may have been done by another thread - // while we were waiting for the lock - if (s_sharedSchemaState == SharedSchemaState::Initialized) { - return s_sharedSchema; - } - - if (s_sharedSchemaState == SharedSchemaState::Initializing) { - @throw RLMException(@"Illegal recursive call of +[%@ %@]. Note: Properties of Swift `Object` classes must not be prepopulated with queried results from a Realm.", self, NSStringFromSelector(_cmd)); - } - - s_sharedSchemaState = SharedSchemaState::Initializing; - try { - // Make sure we've discovered all classes - { - unsigned int numClasses; - using malloc_ptr = std::unique_ptr<__unsafe_unretained Class[], decltype(&free)>; - malloc_ptr classes(objc_copyClassList(&numClasses), &free); - RLMRegisterClassLocalNames(classes.get(), numClasses); - } - - [s_localNameToClass enumerateKeysAndObjectsUsingBlock:^(NSString *, Class cls, BOOL *) { - RLMRegisterClass(cls); - }]; - } - catch (...) { - s_sharedSchemaState = SharedSchemaState::Uninitialized; - throw; - } - - // Replace this method with one that doesn't need to acquire a lock - Class metaClass = objc_getMetaClass(class_getName(self)); - IMP imp = imp_implementationWithBlock(^{ return s_sharedSchema; }); - class_replaceMethod(metaClass, @selector(sharedSchema), imp, "@@:"); - - s_sharedSchemaState = SharedSchemaState::Initialized; - } - - return s_sharedSchema; -} - -// schema based on tables in a realm -+ (instancetype)dynamicSchemaFromObjectStoreSchema:(Schema const&)objectStoreSchema { - // cache descriptors for all subclasses of RLMObject - NSMutableArray *schemaArray = [NSMutableArray arrayWithCapacity:objectStoreSchema.size()]; - for (auto &objectSchema : objectStoreSchema) { - RLMObjectSchema *schema = [RLMObjectSchema objectSchemaForObjectStoreSchema:objectSchema]; - [schemaArray addObject:schema]; - } - - // set class array and mapping - RLMSchema *schema = [RLMSchema new]; - schema.objectSchema = schemaArray; - return schema; -} - -+ (Class)classForString:(NSString *)className { - if (Class cls = s_localNameToClass[className]) { - return cls; - } - - if (Class cls = NSClassFromString(className)) { - return RLMIsObjectSubclass(cls) ? cls : nil; - } - - // className might be the local name of a Swift class we haven't registered - // yet, so scan them all then recheck - { - unsigned int numClasses; - std::unique_ptr<__unsafe_unretained Class[], decltype(&free)> classes(objc_copyClassList(&numClasses), &free); - RLMRegisterClassLocalNames(classes.get(), numClasses); - } - - return s_localNameToClass[className]; -} - -- (id)copyWithZone:(NSZone *)zone { - RLMSchema *schema = [[RLMSchema allocWithZone:zone] init]; - schema->_objectSchemaByName = [[NSMutableDictionary allocWithZone:zone] - initWithDictionary:_objectSchemaByName copyItems:YES]; - return schema; -} - -- (BOOL)isEqualToSchema:(RLMSchema *)schema { - if (_objectSchemaByName.count != schema->_objectSchemaByName.count) { - return NO; - } - __block BOOL matches = YES; - [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, RLMObjectSchema *objectSchema, BOOL *stop) { - if (![schema->_objectSchemaByName[name] isEqualToObjectSchema:objectSchema]) { - *stop = YES; - matches = NO; - } - }]; - return matches; -} - -- (NSString *)description { - NSMutableString *objectSchemaString = [NSMutableString string]; - NSArray *sort = @[[NSSortDescriptor sortDescriptorWithKey:@"className" ascending:YES]]; - for (RLMObjectSchema *objectSchema in [self.objectSchema sortedArrayUsingDescriptors:sort]) { - [objectSchemaString appendFormat:@"\t%@\n", - [objectSchema.description stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]]; - } - return [NSString stringWithFormat:@"Schema {\n%@}", objectSchemaString]; -} - -- (Schema)objectStoreCopy { - if (_objectStoreSchema.size() == 0) { - std::vector schema; - schema.reserve(_objectSchemaByName.count); - [_objectSchemaByName enumerateKeysAndObjectsUsingBlock:[&](NSString *, RLMObjectSchema *objectSchema, BOOL *) { - schema.push_back([objectSchema objectStoreCopy:self]); - }]; - - // Having both obj-c and Swift classes for the same tables results in - // duplicate ObjectSchemas that we need to filter out - std::sort(begin(schema), end(schema), [](auto&& a, auto&& b) { return a.name < b.name; }); - schema.erase(std::unique(begin(schema), end(schema), [](auto&& a, auto&& b) { - if (a.name == b.name) { - // If we make _realmObjectName public this needs to be turned into an exception - REALM_ASSERT_DEBUG(a.persisted_properties == b.persisted_properties); - return true; - } - return false; - }), end(schema)); - - _objectStoreSchema = std::move(schema); - } - return _objectStoreSchema; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSwiftSupport.m b/Lesson14/Pods/Realm/Realm/RLMSwiftSupport.m deleted file mode 100644 index e16c79e..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSwiftSupport.m +++ /dev/null @@ -1,31 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMSwiftSupport.h" - -@implementation RLMSwiftSupport - -+ (BOOL)isSwiftClassName:(NSString *)className { - return [className rangeOfString:@"."].location != NSNotFound; -} - -+ (NSString *)demangleClassName:(NSString *)className { - return [className substringFromIndex:[className rangeOfString:@"."].location + 1]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncConfiguration.mm b/Lesson14/Pods/Realm/Realm/RLMSyncConfiguration.mm deleted file mode 100644 index b082477..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncConfiguration.mm +++ /dev/null @@ -1,323 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncConfiguration_Private.hpp" - -#import "RLMRealmConfiguration+Sync.h" -#import "RLMSyncManager_Private.h" -#import "RLMSyncSession_Private.hpp" -#import "RLMSyncSessionRefreshHandle.hpp" -#import "RLMSyncUser_Private.hpp" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -#import "sync/sync_manager.hpp" -#import "sync/sync_config.hpp" - -#import - -using namespace realm; - -namespace { -using ProtocolError = realm::sync::ProtocolError; - -RLMSyncSystemErrorKind errorKindForSyncError(SyncError error) { - if (error.is_client_reset_requested()) { - return RLMSyncSystemErrorKindClientReset; - } else if (error.error_code == ProtocolError::permission_denied) { - return RLMSyncSystemErrorKindPermissionDenied; - } else if (error.error_code == ProtocolError::bad_authentication) { - return RLMSyncSystemErrorKindUser; - } else if (error.is_session_level_protocol_error()) { - return RLMSyncSystemErrorKindSession; - } else if (error.is_connection_level_protocol_error()) { - return RLMSyncSystemErrorKindConnection; - } else if (error.is_client_error()) { - return RLMSyncSystemErrorKindClient; - } else { - return RLMSyncSystemErrorKindUnknown; - } -} - -BOOL isValidRealmURL(NSURL *url) { - NSString *scheme = [url scheme]; - return [scheme isEqualToString:@"realm"] || [scheme isEqualToString:@"realms"]; -} -} - -@interface RLMSyncConfiguration () { - std::unique_ptr _config; -} - -- (instancetype)initWithUser:(RLMSyncUser *)user - realmURL:(NSURL *)url - customFileURL:(nullable NSURL *)customFileURL - isPartial:(BOOL)isPartial - stopPolicy:(RLMSyncStopPolicy)stopPolicy; -@end - -@implementation RLMSyncConfiguration - -@dynamic stopPolicy; - -- (instancetype)initWithRawConfig:(realm::SyncConfig)config { - if (self = [super init]) { - _config = std::make_unique(std::move(config)); - } - return self; -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[RLMSyncConfiguration class]]) { - return NO; - } - RLMSyncConfiguration *that = (RLMSyncConfiguration *)object; - return [self.realmURL isEqual:that.realmURL] - && [self.user isEqual:that.user] - && self.stopPolicy == that.stopPolicy - && self.fullSynchronization == that.fullSynchronization; -} - -- (void)setEnableSSLValidation:(BOOL)enableSSLValidation { - _config->client_validate_ssl = (bool)enableSSLValidation; -} - -- (BOOL)enableSSLValidation { - return (BOOL)_config->client_validate_ssl; -} - -- (void)setIsPartial:(BOOL)isPartial { - _config->is_partial = (bool)isPartial; -} - -- (BOOL)isPartial { - return (BOOL)_config->is_partial; -} - -- (NSURL *)pinnedCertificateURL { - if (auto& path = _config->ssl_trust_certificate_path) { - return [NSURL fileURLWithPath:RLMStringDataToNSString(*path)]; - } - return nil; -} - -- (void)setPinnedCertificateURL:(NSURL *)pinnedCertificateURL { - if (pinnedCertificateURL) { - if ([pinnedCertificateURL respondsToSelector:@selector(UTF8String)]) { - _config->ssl_trust_certificate_path = std::string([(id)pinnedCertificateURL UTF8String]); - } - else { - _config->ssl_trust_certificate_path = std::string(pinnedCertificateURL.path.UTF8String); - } - } - else { - _config->ssl_trust_certificate_path = util::none; - } -} - -- (void)setFullSynchronization:(BOOL)fullSynchronization { - _config->is_partial = !(bool)fullSynchronization; -} - -- (BOOL)fullSynchronization { - return !(BOOL)_config->is_partial; -} - -- (realm::SyncConfig&)rawConfiguration { - return *_config; -} - -- (RLMSyncUser *)user { - return [[RLMSyncUser alloc] initWithSyncUser:_config->user]; -} - -- (RLMSyncStopPolicy)stopPolicy { - return translateStopPolicy(_config->stop_policy); -} - -- (void)setStopPolicy:(RLMSyncStopPolicy)stopPolicy { - _config->stop_policy = translateStopPolicy(stopPolicy); -} - -- (NSString *)urlPrefix { - if (_config->url_prefix) { - return @(_config->url_prefix->c_str()); - } - return nil; -} - -- (void)setUrlPrefix:(NSString *)urlPrefix { - if (urlPrefix) { - _config->url_prefix.emplace(urlPrefix.UTF8String); - } else { - _config->url_prefix = none; - } -} - -- (bool)cancelAsyncOpenOnNonFatalErrors { - return _config->cancel_waits_on_nonfatal_error; -} - -- (void)setCancelAsyncOpenOnNonFatalErrors:(bool)cancelAsyncOpenOnNonFatalErrors { - _config->cancel_waits_on_nonfatal_error = cancelAsyncOpenOnNonFatalErrors; -} - -- (NSURL *)realmURL { - NSString *rawStringURL = @(_config->reference_realm_url.c_str()); - return [NSURL URLWithString:rawStringURL]; -} - -- (instancetype)initWithUser:(RLMSyncUser *)user realmURL:(NSURL *)url { - return [self initWithUser:user - realmURL:url - customFileURL:nil - isPartial:NO - stopPolicy:RLMSyncStopPolicyAfterChangesUploaded]; -} - -- (instancetype)initWithUser:(RLMSyncUser *)user - realmURL:(NSURL *)url - isPartial:(BOOL)isPartial - urlPrefix:(NSString *)urlPrefix - stopPolicy:(RLMSyncStopPolicy)stopPolicy - enableSSLValidation:(BOOL)enableSSLValidation - certificatePath:(nullable NSURL *)certificatePath { - auto config = [self initWithUser:user - realmURL:url - customFileURL:nil - isPartial:isPartial - stopPolicy:stopPolicy]; - config.urlPrefix = urlPrefix; - config.enableSSLValidation = enableSSLValidation; - config.pinnedCertificateURL = certificatePath; - return config; -} - -static void bindHandler(std::string const&, SyncConfig const& config, std::shared_ptr session) { - const std::shared_ptr& user = config.user; - NSURL *realmURL = [NSURL URLWithString:@(config.realm_url().c_str())]; - NSString *path = [realmURL path]; - REALM_ASSERT(realmURL && path); - auto handle = [[RLMSyncSessionRefreshHandle alloc] initWithRealmURL:realmURL - user:user - session:std::move(session) - completionBlock:RLMSyncManager.sharedManager.sessionCompletionNotifier]; - context_for(user).register_refresh_handle([path UTF8String], handle); -} - -static void errorHandler(std::shared_ptr errored_session, SyncError error) { - NSString *recoveryPath; - RLMSyncErrorActionToken *token; - for (auto& pair : error.user_info) { - if (pair.first == realm::SyncError::c_original_file_path_key) { - token = [[RLMSyncErrorActionToken alloc] initWithOriginalPath:pair.second]; - } - else if (pair.first == realm::SyncError::c_recovery_file_path_key) { - recoveryPath = @(pair.second.c_str()); - } - } - - BOOL shouldMakeError = YES; - NSDictionary *custom = nil; - // Note that certain types of errors are 'interactive'; users have several options - // as to how to proceed after the error is reported. - auto errorClass = errorKindForSyncError(error); - switch (errorClass) { - case RLMSyncSystemErrorKindClientReset: { - custom = @{kRLMSyncPathOfRealmBackupCopyKey: recoveryPath, kRLMSyncErrorActionTokenKey: token}; - break; - } - case RLMSyncSystemErrorKindPermissionDenied: { - custom = @{kRLMSyncErrorActionTokenKey: token}; - break; - } - case RLMSyncSystemErrorKindUser: - case RLMSyncSystemErrorKindSession: - break; - case RLMSyncSystemErrorKindConnection: - case RLMSyncSystemErrorKindClient: - case RLMSyncSystemErrorKindUnknown: - // Report the error. There's nothing the user can do about it, though. - shouldMakeError = error.is_fatal; - break; - } - auto errorHandler = RLMSyncManager.sharedManager.errorHandler; - if (!shouldMakeError || !errorHandler) { - return; - } - NSError *nsError = make_sync_error(errorClass, @(error.message.c_str()), error.error_code.value(), custom); - RLMSyncSession *session = [[RLMSyncSession alloc] initWithSyncSession:errored_session]; - dispatch_async(dispatch_get_main_queue(), ^{ - errorHandler(nsError, session); - }); -}; - -- (instancetype)initWithUser:(RLMSyncUser *)user - realmURL:(NSURL *)url - customFileURL:(nullable NSURL *)customFileURL - isPartial:(BOOL)isPartial - stopPolicy:(RLMSyncStopPolicy)stopPolicy { - if (self = [super init]) { - if (!isValidRealmURL(url)) { - @throw RLMException(@"The provided URL (%@) was not a valid Realm URL.", [url absoluteString]); - } - - _config = std::make_unique(SyncConfig{ - [user _syncUser], - [[url absoluteString] UTF8String] - }); - _config->stop_policy = translateStopPolicy(stopPolicy); - _config->bind_session_handler = bindHandler; - _config->error_handler = errorHandler; - _config->is_partial = isPartial; - _config->client_resync_mode = realm::ClientResyncMode::Manual; - - if (NSString *authorizationHeaderName = [RLMSyncManager sharedManager].authorizationHeaderName) { - _config->authorization_header_name.emplace(authorizationHeaderName.UTF8String); - } - if (NSDictionary *customRequestHeaders = [RLMSyncManager sharedManager].customRequestHeaders) { - for (NSString *key in customRequestHeaders) { - _config->custom_http_headers.emplace(key.UTF8String, customRequestHeaders[key].UTF8String); - } - } - - self.customFileURL = customFileURL; - return self; - } - return nil; -} - -+ (RLMRealmConfiguration *)automaticConfiguration { - if (RLMSyncUser.allUsers.count != 1) - @throw RLMException(@"The automatic configuration requires there be exactly one logged-in sync user."); - - return [RLMSyncConfiguration automaticConfigurationForUser:RLMSyncUser.currentUser]; -} - -+ (RLMRealmConfiguration *)automaticConfigurationForUser:(RLMSyncUser *)user { - RLMSyncConfiguration *syncConfig = [[RLMSyncConfiguration alloc] initWithUser:user - realmURL:user.defaultRealmURL - customFileURL:nil - isPartial:YES - stopPolicy:RLMSyncStopPolicyAfterChangesUploaded]; - RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; - config.syncConfiguration = syncConfig; - return config; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncCredentials.m b/Lesson14/Pods/Realm/Realm/RLMSyncCredentials.m deleted file mode 100644 index 480c539..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncCredentials.m +++ /dev/null @@ -1,132 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncCredentials.h" -#import "RLMSyncUtil_Private.h" - -/// A Twitter account as an identity provider. -//extern RLMIdentityProvider const RLMIdentityProviderTwitter; - -RLMIdentityProvider const RLMIdentityProviderDebug = @"debug"; -RLMIdentityProvider const RLMIdentityProviderRealm = @"realm"; -RLMIdentityProvider const RLMIdentityProviderUsernamePassword = @"password"; -RLMIdentityProvider const RLMIdentityProviderFacebook = @"facebook"; -RLMIdentityProvider const RLMIdentityProviderTwitter = @"twitter"; -RLMIdentityProvider const RLMIdentityProviderGoogle = @"google"; -RLMIdentityProvider const RLMIdentityProviderCloudKit = @"cloudkit"; -RLMIdentityProvider const RLMIdentityProviderJWT = @"jwt"; -RLMIdentityProvider const RLMIdentityProviderAnonymous = @"anonymous"; -RLMIdentityProvider const RLMIdentityProviderNickname = @"nickname"; -RLMIdentityProvider const RLMIdentityProviderCustomRefreshToken = @"customrefreshtoken"; - -@interface RLMSyncCredentials () - -- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token - provider:(RLMIdentityProvider)provider - userInfo:(NSDictionary *)userInfo NS_DESIGNATED_INITIALIZER; - -@property (nonatomic, readwrite) RLMSyncCredentialsToken token; -@property (nonatomic, readwrite) RLMIdentityProvider provider; -@property (nonatomic, readwrite) NSDictionary *userInfo; - -@end - -@implementation RLMSyncCredentials - -+ (instancetype)credentialsWithFacebookToken:(RLMSyncCredentialsToken)token { - return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderFacebook userInfo:nil]; -} - -+ (instancetype)credentialsWithGoogleToken:(RLMSyncCredentialsToken)token { - return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderGoogle userInfo:nil]; -} - -+ (instancetype)credentialsWithCloudKitToken:(RLMSyncCredentialsToken)token { - return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderCloudKit userInfo:nil]; -} - -+ (instancetype)credentialsWithUsername:(NSString *)username - password:(NSString *)password - register:(BOOL)shouldRegister { - return [[self alloc] initWithCustomToken:username - provider:RLMIdentityProviderUsernamePassword - userInfo:@{kRLMSyncPasswordKey: password, - kRLMSyncRegisterKey: @(shouldRegister)}]; -} - -+ (instancetype)credentialsWithJWT:(NSString *)token { - return [[self alloc] initWithCustomToken:token provider:RLMIdentityProviderJWT userInfo:nil]; -} - -+ (instancetype)anonymousCredentials { - return [[self alloc] initWithCustomToken:@"" provider:RLMIdentityProviderAnonymous userInfo:nil]; -} - -+ (instancetype)credentialsWithNickname:(NSString *)nickname isAdmin:(BOOL)isAdmin { - return [[self alloc] initWithCustomToken:nickname - provider:RLMIdentityProviderNickname - userInfo:@{kRLMSyncIsAdminKey: @(isAdmin), kRLMSyncDataKey: nickname}]; -} - -/// Intended only for testing use. Will only work if the ROS is started with the `debug` provider enabled. -+ (instancetype)credentialsWithDebugUserID:(NSString *)userID isAdmin:(BOOL)isAdmin { - return [[self alloc] initWithCustomToken:userID - provider:RLMIdentityProviderDebug - userInfo:@{kRLMSyncIsAdminKey: @(isAdmin)}]; -} - -+ (instancetype)credentialsWithAccessToken:(RLMServerToken)accessToken identity:(NSString *)identity { - return [[self alloc] initWithCustomToken:accessToken - provider:RLMIdentityProviderAccessToken - userInfo:@{kRLMSyncIdentityKey: identity}]; -} - -+ (instancetype)credentialsWithCustomRefreshToken:(NSString *)token identity:(NSString *)identity isAdmin:(BOOL)isAdmin { - NSDictionary *userInfo = @{ - kRLMSyncIdentityKey: identity, - kRLMSyncIsAdminKey: @(isAdmin) - }; - return [[self alloc] initWithCustomToken:token - provider:RLMIdentityProviderCustomRefreshToken - userInfo:userInfo]; - -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[RLMSyncCredentials class]]) { - return NO; - } - RLMSyncCredentials *that = (RLMSyncCredentials *)object; - return ([self.token isEqualToString:that.token] - && [self.provider isEqualToString:that.provider] - && [self.userInfo isEqual:that.userInfo]); -} - -- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token - provider:(RLMIdentityProvider)provider - userInfo:(NSDictionary *)userInfo { - if (self = [super init]) { - self.token = token; - self.provider = provider; - self.userInfo = userInfo; - return self; - } - return nil; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncManager.mm b/Lesson14/Pods/Realm/Realm/RLMSyncManager.mm deleted file mode 100644 index cb2e1d3..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncManager.mm +++ /dev/null @@ -1,295 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncManager_Private.h" - -#import "RLMRealmConfiguration+Sync.h" -#import "RLMSyncConfiguration_Private.hpp" -#import "RLMSyncSession_Private.hpp" -#import "RLMSyncUser_Private.hpp" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -#import "sync/sync_config.hpp" -#import "sync/sync_manager.hpp" -#import "sync/sync_session.hpp" - -#if !defined(REALM_COCOA_VERSION) -#import "RLMVersion.h" -#endif - -using namespace realm; -using Level = realm::util::Logger::Level; - -namespace { - -Level levelForSyncLogLevel(RLMSyncLogLevel logLevel) { - switch (logLevel) { - case RLMSyncLogLevelOff: return Level::off; - case RLMSyncLogLevelFatal: return Level::fatal; - case RLMSyncLogLevelError: return Level::error; - case RLMSyncLogLevelWarn: return Level::warn; - case RLMSyncLogLevelInfo: return Level::info; - case RLMSyncLogLevelDetail: return Level::detail; - case RLMSyncLogLevelDebug: return Level::debug; - case RLMSyncLogLevelTrace: return Level::trace; - case RLMSyncLogLevelAll: return Level::all; - } - REALM_UNREACHABLE(); // Unrecognized log level. -} - -RLMSyncLogLevel logLevelForLevel(Level logLevel) { - switch (logLevel) { - case Level::off: return RLMSyncLogLevelOff; - case Level::fatal: return RLMSyncLogLevelFatal; - case Level::error: return RLMSyncLogLevelError; - case Level::warn: return RLMSyncLogLevelWarn; - case Level::info: return RLMSyncLogLevelInfo; - case Level::detail: return RLMSyncLogLevelDetail; - case Level::debug: return RLMSyncLogLevelDebug; - case Level::trace: return RLMSyncLogLevelTrace; - case Level::all: return RLMSyncLogLevelAll; - } - REALM_UNREACHABLE(); // Unrecognized log level. -} - -#pragma mark - Loggers - -struct CocoaSyncLogger : public realm::util::RootLogger { - void do_log(Level, std::string message) override { - NSLog(@"Sync: %@", RLMStringDataToNSString(message)); - } -}; - -struct CocoaSyncLoggerFactory : public realm::SyncLoggerFactory { - std::unique_ptr make_logger(realm::util::Logger::Level level) override { - auto logger = std::make_unique(); - logger->set_level_threshold(level); - return std::move(logger); - } -} s_syncLoggerFactory; - -struct CallbackLogger : public realm::util::RootLogger { - RLMSyncLogFunction logFn; - void do_log(Level level, std::string message) override { - @autoreleasepool { - logFn(logLevelForLevel(level), RLMStringDataToNSString(message)); - } - } -}; -struct CallbackLoggerFactory : public realm::SyncLoggerFactory { - RLMSyncLogFunction logFn; - std::unique_ptr make_logger(realm::util::Logger::Level level) override { - auto logger = std::make_unique(); - logger->logFn = logFn; - logger->set_level_threshold(level); - return std::move(logger); // not a redundant move because it's a different type - } - - CallbackLoggerFactory(RLMSyncLogFunction logFn) : logFn(logFn) { } -}; - -} // anonymous namespace - -#pragma mark - RLMSyncManager - -@interface RLMSyncTimeoutOptions () { - @public - realm::SyncClientTimeouts _options; -} -@end - -@implementation RLMSyncManager { - std::unique_ptr _loggerFactory; -} - -static RLMSyncManager *s_sharedManager = nil; - -- (instancetype)initPrivate { - return self = [super init]; -} - -+ (instancetype)sharedManager { - static std::once_flag flag; - std::call_once(flag, [] { - try { - [RLMSyncUser _setUpBindingContextFactory]; - s_sharedManager = [[RLMSyncManager alloc] initPrivate]; - [s_sharedManager configureWithRootDirectory:nil]; - } - catch (std::exception const& e) { - @throw RLMException(e); - } - }); - return s_sharedManager; -} - -- (void)configureWithRootDirectory:(NSURL *)rootDirectory { - SyncClientConfig config; - bool should_encrypt = !getenv("REALM_DISABLE_METADATA_ENCRYPTION") && !RLMIsRunningInPlayground(); - config.logger_factory = &s_syncLoggerFactory; - config.metadata_mode = should_encrypt ? SyncManager::MetadataMode::Encryption - : SyncManager::MetadataMode::NoEncryption; - @autoreleasepool { - rootDirectory = rootDirectory ?: [NSURL fileURLWithPath:RLMDefaultDirectoryForBundleIdentifier(nil)]; - config.base_file_path = rootDirectory.path.UTF8String; - - bool isSwift = !!NSClassFromString(@"RealmSwiftObjectUtil"); - config.user_agent_binding_info = - util::format("Realm%1/%2", isSwift ? "Swift" : "ObjectiveC", - RLMStringDataWithNSString(REALM_COCOA_VERSION)); - config.user_agent_application_info = RLMStringDataWithNSString(self.appID); - } - SyncManager::shared().configure(config); -} - -- (NSString *)appID { - if (!_appID) { - _appID = [[NSBundle mainBundle] bundleIdentifier] ?: @"(none)"; - } - return _appID; -} - -- (void)setUserAgent:(NSString *)userAgent { - SyncManager::shared().set_user_agent(RLMStringDataWithNSString(userAgent)); - _userAgent = userAgent; -} - -- (void)setCustomRequestHeaders:(NSDictionary *)customRequestHeaders { - _customRequestHeaders = customRequestHeaders.copy; - - for (auto&& user : SyncManager::shared().all_logged_in_users()) { - for (auto&& session : user->all_sessions()) { - auto config = session->config(); - config.custom_http_headers.clear();; - for (NSString *key in customRequestHeaders) { - config.custom_http_headers.emplace(key.UTF8String, customRequestHeaders[key].UTF8String); - } - session->update_configuration(std::move(config)); - } - } -} - -- (void)setLogger:(RLMSyncLogFunction)logFn { - _logger = logFn; - if (_logger) { - _loggerFactory = std::make_unique(logFn); - SyncManager::shared().set_logger_factory(*_loggerFactory); - } - else { - _loggerFactory = nullptr; - SyncManager::shared().set_logger_factory(s_syncLoggerFactory); - } -} - -- (void)setTimeoutOptions:(RLMSyncTimeoutOptions *)timeoutOptions { - _timeoutOptions = timeoutOptions; - SyncManager::shared().set_timeouts(timeoutOptions->_options); -} - -#pragma mark - Passthrough properties - -- (RLMSyncLogLevel)logLevel { - return logLevelForLevel(realm::SyncManager::shared().log_level()); -} - -- (void)setLogLevel:(RLMSyncLogLevel)logLevel { - realm::SyncManager::shared().set_log_level(levelForSyncLogLevel(logLevel)); -} - -#pragma mark - Private API - -- (void)_fireError:(NSError *)error { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.errorHandler) { - self.errorHandler(error, nil); - } - }); -} - -- (NSArray *)_allUsers { - NSMutableArray *buffer = [NSMutableArray array]; - for (auto user : SyncManager::shared().all_logged_in_users()) { - [buffer addObject:[[RLMSyncUser alloc] initWithSyncUser:std::move(user)]]; - } - return buffer; -} - -+ (void)resetForTesting { - RLMSyncManager *manager = self.sharedManager; - manager->_errorHandler = nil; - manager->_appID = nil; - manager->_userAgent = nil; - manager->_logger = nil; - manager->_authorizationHeaderName = nil; - manager->_customRequestHeaders = nil; - manager->_pinnedCertificatePaths = nil; - manager->_timeoutOptions = nil; - - SyncManager::shared().reset_for_testing(); -} - -- (RLMNetworkRequestOptions *)networkRequestOptions { - RLMNetworkRequestOptions *options = [[RLMNetworkRequestOptions alloc] init]; - options.authorizationHeaderName = self.authorizationHeaderName; - options.customHeaders = self.customRequestHeaders; - options.pinnedCertificatePaths = self.pinnedCertificatePaths; - return options; -} - -@end - -#pragma mark - RLMSyncTimeoutOptions - -@implementation RLMSyncTimeoutOptions -- (NSUInteger)connectTimeout { - return _options.connect_timeout; -} -- (void)setConnectTimeout:(NSUInteger)connectTimeout { - _options.connect_timeout = connectTimeout; -} - -- (NSUInteger)connectLingerTime { - return _options.connection_linger_time; -} -- (void)setConnectionLingerTime:(NSUInteger)connectionLingerTime { - _options.connection_linger_time = connectionLingerTime; -} - -- (NSUInteger)pingKeepalivePeriod { - return _options.ping_keepalive_period; -} -- (void)setPingKeepalivePeriod:(NSUInteger)pingKeepalivePeriod { - _options.ping_keepalive_period = pingKeepalivePeriod; -} - -- (NSUInteger)pongKeepaliveTimeout { - return _options.pong_keepalive_timeout; -} -- (void)setPongKeepaliveTimeout:(NSUInteger)pongKeepaliveTimeout { - _options.pong_keepalive_timeout = pongKeepaliveTimeout; -} - -- (NSUInteger)fastReconnectLimit { - return _options.fast_reconnect_limit; -} -- (void)setFastReconnectLimit:(NSUInteger)fastReconnectLimit { - _options.fast_reconnect_limit = fastReconnectLimit; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncPermission.mm b/Lesson14/Pods/Realm/Realm/RLMSyncPermission.mm deleted file mode 100644 index 6cbd0eb..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncPermission.mm +++ /dev/null @@ -1,375 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "RLMSyncPermission.h" - -#import "RLMArray.h" -#import "RLMObjectSchema.h" -#import "RLMRealm_Dynamic.h" -#import "RLMResults.h" -#import "RLMSyncUser.h" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -using namespace realm; - -static void verifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm, SEL sel) { - if (!realm) { - @throw RLMException(@"Cannot call %@ on an unmanaged object.", NSStringFromSelector(sel)); - } - if (!realm.inWriteTransaction) { - @throw RLMException(@"Cannot call %@ outside of a write transaction.", NSStringFromSelector(sel)); - } -} - -id RLMPermissionForRole(RLMArray *array, id role) { - RLMResults *filtered = [array objectsWhere:@"role.name = %@", [role name]]; - RLMPermission *permission; - for (RLMPermission *p in filtered) { - if (permission == nil) { - permission = p; - } - // If there's more than one permission for the role, merge it into the first - // one and then delete it as otherwise revoking permissions won't actually work - else { - if (p.canRead && !permission.canRead) { - permission.canRead = true; - } - if (p.canUpdate && !permission.canUpdate) { - permission.canUpdate = true; - } - if (p.canDelete && !permission.canDelete) { - permission.canDelete = true; - } - if (p.canSetPermissions && !permission.canSetPermissions) { - permission.canSetPermissions = true; - } - if (p.canQuery && !permission.canQuery) { - permission.canQuery = true; - } - if (p.canCreate && !permission.canCreate) { - permission.canCreate = true; - } - if (p.canModifySchema && !permission.canModifySchema) { - permission.canModifySchema = true; - } - [array.realm deleteObject:p]; - } - } - if (!permission) { - // Use the dynamic API to create the appropriate Permission class for the array - permission = (id)[array.realm createObject:array.objectClassName withValue:@[role]]; - [array addObject:permission]; - } - return permission; -} - -@implementation RLMPermissionRole -+ (NSString *)_realmObjectName { - return @"__Role"; -} -+ (NSString *)primaryKey { - return @"name"; -} -+ (NSArray *)requiredProperties { - return @[@"name"]; -} -+ (NSDictionary *)_realmColumnNames { - return @{@"users": @"members"}; -} -@end - -@implementation RLMPermissionUser -+ (NSString *)_realmObjectName { - return @"__User"; -} -+ (NSString *)primaryKey { - return @"identity"; -} -+ (NSArray *)requiredProperties { - return @[@"identity"]; -} -+ (NSDictionary *)_realmColumnNames { - return @{@"identity": @"id", @"role": @"role"}; -} -+ (NSDictionary *)linkingObjectsProperties { - return @{@"roles": [RLMPropertyDescriptor descriptorWithClass:RLMPermissionRole.class propertyName:@"users"]}; -} - -+ (RLMPermissionUser *)userInRealm:(RLMRealm *)realm withIdentity:(NSString *)identity { - return [self createOrUpdateInRealm:realm withValue:@[identity]]; -} -@end - -@implementation RLMPermission -+ (NSString *)_realmObjectName { - return @"__Permission"; -} -+ (NSDictionary *)defaultPropertyValues { - return @{@"canRead": @NO, - @"canUpdate": @NO, - @"canDelete": @NO, - @"canSetPermissions": @NO, - @"canQuery": @NO, - @"canCreate": @NO, - @"canModifySchema": @NO}; -} - -+ (RLMPermission *)permissionForRole:(RLMPermissionRole *)role inArray:(RLMArray *)array { - verifyInWriteTransaction(array.realm, _cmd); - auto index = [array indexOfObjectWhere:@"role = %@", role]; - if (index != NSNotFound) { - return array[index]; - } - RLMPermission *permission = [RLMPermission createInRealm:role.realm withValue:@[role]]; - [array addObject:permission]; - return permission; -} - -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName inArray:(RLMArray *)array { - verifyInWriteTransaction(array.realm, _cmd); - return RLMPermissionForRole(array, [RLMPermissionRole createOrUpdateInRealm:array.realm withValue:@{@"name": roleName}]); -} - -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onRealm:(RLMRealm *)realm { - verifyInWriteTransaction(realm, _cmd); - return [self permissionForRoleNamed:roleName - inArray:[RLMRealmPermission objectInRealm:realm].permissions]; - -} - -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClass:(Class)cls realm:(RLMRealm *)realm { - verifyInWriteTransaction(realm, _cmd); - return [self permissionForRoleNamed:roleName - inArray:[RLMClassPermission objectInRealm:realm forClass:cls].permissions]; -} - -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClassNamed:(NSString *)className realm:(RLMRealm *)realm { - verifyInWriteTransaction(realm, _cmd); - return [self permissionForRoleNamed:roleName - inArray:[RLMClassPermission objectInRealm:realm forClassNamed:className].permissions]; -} - -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onObject:(RLMObject *)object { - verifyInWriteTransaction(object.realm, _cmd); - for (RLMProperty *prop in object.objectSchema.properties) { - if (prop.array && [prop.objectClassName isEqualToString:@"RLMPermission"]) { - return [self permissionForRoleNamed:roleName - inArray:[object valueForKey:prop.name]]; - } - } - @throw RLMException(@"Object %@ does not have a RLMArray property.", object); -} -@end - -@implementation RLMClassPermission -+ (NSString *)_realmObjectName { - return @"__Class"; -} -+ (NSString *)primaryKey { - return @"name"; -} -+ (NSArray *)requiredProperties { - return @[@"name"]; -} - -+ (instancetype)objectInRealm:(RLMRealm *)realm forClassNamed:(NSString *)name { - return [RLMClassPermission objectInRealm:realm forPrimaryKey:name]; -} -+ (instancetype)objectInRealm:(RLMRealm *)realm forClass:(Class)cls { - return [RLMClassPermission objectInRealm:realm forPrimaryKey:[cls _realmObjectName] ?: [cls className]]; -} -@end - -@interface RLMRealmPermission () -@property (nonatomic) int pk; -@end - -@implementation RLMRealmPermission -+ (NSString *)_realmObjectName { - return @"__Realm"; -} -+ (NSDictionary *)_realmColumnNames { - return @{@"pk": @"id"}; -} -+ (NSString *)primaryKey { - return @"pk"; -} - -+ (instancetype)objectInRealm:(RLMRealm *)realm { - return [RLMRealmPermission objectInRealm:realm forPrimaryKey:@0]; -} -@end - -#pragma mark - Permission - -@implementation RLMSyncPermission - -- (instancetype)initWithRealmPath:(NSString *)path - identity:(NSString *)identity - accessLevel:(RLMSyncAccessLevel)accessLevel { - if (self = [super init]) { - _accessLevel = accessLevel; - _path = path; - _identity = identity; - if (!identity) { - @throw RLMException(@"A permission value cannot be created without a valid user ID"); - } - _updatedAt = [NSDate date]; - } - return self; -} - -- (instancetype)initWithRealmPath:(NSString *)path - username:(NSString *)username - accessLevel:(RLMSyncAccessLevel)accessLevel { - if (self = [super init]) { - _accessLevel = accessLevel; - _path = path; - _identity = nil; - _key = @"email"; - _value = username; - _updatedAt = [NSDate date]; - } - return self; -} - -+ (BOOL)accessInstanceVariablesDirectly { - return NO; -} - -- (BOOL)mayRead { - return self.accessLevel > RLMSyncAccessLevelNone; -} - -- (BOOL)mayWrite { - return self.accessLevel > RLMSyncAccessLevelRead; -} - -- (BOOL)mayManage { - return self.accessLevel == RLMSyncAccessLevelAdmin; -} - -- (NSUInteger)hash { - return self.identity.hash ^ self.accessLevel ^ self.path.hash ^ self.key.hash ^ self.value.hash; -} - -- (BOOL)isEqual:(id)object { - if (self == object) { - return YES; - } - if (![object isKindOfClass:[RLMSyncPermission class]]) { - return NO; - } - - RLMSyncPermission *that = (RLMSyncPermission *)object; - if (self.accessLevel != that.accessLevel) { - return NO; - } - if (![self.path isEqualToString:that.path]) { - return NO; - } - if (self.identity) { - if (!that.identity || ![self.identity isEqualToString:that.identity]) { - return NO; - } - } - else { - if (that.identity || ![self.key isEqualToString:that.key] || ![self.value isEqualToString:that.value]) { - return NO; - } - } - return YES; -} - -- (RLMSyncPermission *)tildeExpandedSyncPermissionForUser:(RLMSyncUser *)user { - if (![self.path hasPrefix:@"/~/"]) { - return self; - } - NSString *path = [self.path stringByReplacingCharactersInRange:{1, 1} withString:user.identity]; - if (_identity) { - return [[RLMSyncPermission alloc] initWithRealmPath:path identity:_identity accessLevel:_accessLevel]; - } - return [[RLMSyncPermission alloc] initWithRealmPath:path username:_value accessLevel:_accessLevel]; -} - -- (NSString *)description { - NSString *typeDescription = nil; - if (self.identity) { - typeDescription = [NSString stringWithFormat:@"identity: %@", self.identity]; - } else { - typeDescription = [NSString stringWithFormat:@"key: %@, value: %@", self.key, self.value]; - } - return [NSString stringWithFormat:@" %@, path: %@, access level: %@", - typeDescription, self.path, RLMSyncAccessLevelToString(self.accessLevel)]; -} - -NSString *RLMSyncAccessLevelToString(RLMSyncAccessLevel level) { - switch (level) { - case RLMSyncAccessLevelNone: return @"none"; - case RLMSyncAccessLevelRead: return @"read"; - case RLMSyncAccessLevelWrite: return @"write"; - case RLMSyncAccessLevelAdmin: return @"admin"; - } - return @"unknown"; -} - -RLMSyncAccessLevel RLMSyncAccessLevelFromString(NSString *level) { - if ([level isEqualToString:@"none"]) { - return RLMSyncAccessLevelNone; - } - if ([level isEqualToString:@"read"]) { - return RLMSyncAccessLevelRead; - } - if ([level isEqualToString:@"write"]) { - return RLMSyncAccessLevelWrite; - } - if ([level isEqualToString:@"admin"]) { - return RLMSyncAccessLevelAdmin; - } - @throw RLMException(@"Invalid access level %@", level); -} - -@end - -@implementation RLMSyncPermissionOffer -- (instancetype)initWithRealmPath:(NSString *)path - token:(NSString *)token - expiresAt:(NSDate *)expiresAt - createdAt:(NSDate *)createdAt - accessLevel:(RLMSyncAccessLevel)accessLevel { - if (self = [super init]) { - _realmPath = path; - _token = token; - _expiresAt = expiresAt; - _createdAt = createdAt; - _accessLevel = accessLevel; - } - return self; -} - -+ (BOOL)accessInstanceVariablesDirectly { - return NO; -} - -- (NSString *)description { - return [NSString stringWithFormat:@" path: %@, access level: %@, token: %@, createdAt: %@, expiresAt: %@", - self, _realmPath, RLMSyncAccessLevelToString(_accessLevel), - _token, _createdAt, _expiresAt]; -} -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncSession.mm b/Lesson14/Pods/Realm/Realm/RLMSyncSession.mm deleted file mode 100644 index cddaade..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncSession.mm +++ /dev/null @@ -1,306 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncSession_Private.hpp" - -#import "RLMRealm_Private.hpp" -#import "RLMSyncConfiguration_Private.hpp" -#import "RLMSyncUser_Private.hpp" -#import "RLMSyncUtil_Private.hpp" - -#import "sync/async_open_task.hpp" -#import "sync/sync_session.hpp" - -using namespace realm; - -@interface RLMSyncErrorActionToken () { -@public - std::string _originalPath; - BOOL _isValid; -} -@end - -@interface RLMProgressNotificationToken() { - uint64_t _token; - std::weak_ptr _session; -} -@end - -@implementation RLMProgressNotificationToken - -- (void)suppressNextNotification { - // No-op, but implemented in case this token is passed to - // `-[RLMRealm commitWriteTransactionWithoutNotifying:]`. -} - -- (void)invalidate { - if (auto session = _session.lock()) { - session->unregister_progress_notifier(_token); - _session.reset(); - _token = 0; - } -} - -- (void)dealloc { - if (_token != 0) { - NSLog(@"RLMProgressNotificationToken released without unregistering a notification. " - @"You must hold on to the RLMProgressNotificationToken and call " - @"-[RLMProgressNotificationToken invalidate] when you no longer wish to receive " - @"progress update notifications."); - } -} - -- (nullable instancetype)initWithTokenValue:(uint64_t)token - session:(std::shared_ptr)session { - if (token == 0) { - return nil; - } - if (self = [super init]) { - _token = token; - _session = session; - return self; - } - return nil; -} - -@end - -@interface RLMSyncSession () -@property (class, nonatomic, readonly) dispatch_queue_t notificationsQueue; -@property (atomic, readwrite) RLMSyncConnectionState connectionState; -@end - -@implementation RLMSyncSession - -+ (dispatch_queue_t)notificationsQueue { - static dispatch_queue_t queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - queue = dispatch_queue_create("io.realm.sync.sessionsNotificationQueue", DISPATCH_QUEUE_SERIAL); - }); - return queue; -} - -static RLMSyncConnectionState convertConnectionState(SyncSession::ConnectionState state) { - switch (state) { - case SyncSession::ConnectionState::Disconnected: return RLMSyncConnectionStateDisconnected; - case SyncSession::ConnectionState::Connecting: return RLMSyncConnectionStateConnecting; - case SyncSession::ConnectionState::Connected: return RLMSyncConnectionStateConnected; - } -} - -- (instancetype)initWithSyncSession:(std::shared_ptr const&)session { - if (self = [super init]) { - _session = session; - _connectionState = convertConnectionState(session->connection_state()); - // No need to save the token as RLMSyncSession always outlives the - // underlying SyncSession - session->register_connection_change_callback([=](auto, auto newState) { - dispatch_async(dispatch_get_main_queue(), ^{ - self.connectionState = convertConnectionState(newState); - }); - }); - return self; - } - return nil; -} - -- (RLMSyncConfiguration *)configuration { - if (auto session = _session.lock()) { - return [[RLMSyncConfiguration alloc] initWithRawConfig:session->config()]; - } - return nil; -} - -- (NSURL *)realmURL { - if (auto session = _session.lock()) { - if (auto url = session->full_realm_url()) { - return [NSURL URLWithString:@(url->c_str())]; - } - } - return nil; -} - -- (RLMSyncUser *)parentUser { - if (auto session = _session.lock()) { - return [[RLMSyncUser alloc] initWithSyncUser:session->user()]; - } - return nil; -} - -- (RLMSyncSessionState)state { - if (auto session = _session.lock()) { - if (session->state() == SyncSession::PublicState::Inactive) { - return RLMSyncSessionStateInactive; - } - return RLMSyncSessionStateActive; - } - return RLMSyncSessionStateInvalid; -} - -- (void)suspend { - if (auto session = _session.lock()) { - session->log_out(); - } -} - -- (void)resume { - if (auto session = _session.lock()) { - session->revive_if_needed(); - } -} - -- (BOOL)waitForUploadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback { - if (auto session = _session.lock()) { - queue = queue ?: dispatch_get_main_queue(); - session->wait_for_upload_completion([=](std::error_code err) { - NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err); - dispatch_async(queue, ^{ - callback(error); - }); - }); - return YES; - } - return NO; -} - -- (BOOL)waitForDownloadCompletionOnQueue:(dispatch_queue_t)queue callback:(void(^)(NSError *))callback { - if (auto session = _session.lock()) { - queue = queue ?: dispatch_get_main_queue(); - session->wait_for_download_completion([=](std::error_code err) { - NSError *error = (err == std::error_code{}) ? nil : make_sync_error(err); - dispatch_async(queue, ^{ - callback(error); - }); - }); - return YES; - } - return NO; -} - -- (RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction - mode:(RLMSyncProgressMode)mode - block:(RLMProgressNotificationBlock)block { - if (auto session = _session.lock()) { - dispatch_queue_t queue = RLMSyncSession.notificationsQueue; - auto notifier_direction = (direction == RLMSyncProgressDirectionUpload - ? SyncSession::NotifierType::upload - : SyncSession::NotifierType::download); - bool is_streaming = (mode == RLMSyncProgressModeReportIndefinitely); - uint64_t token = session->register_progress_notifier([=](uint64_t transferred, uint64_t transferrable) { - dispatch_async(queue, ^{ - block((NSUInteger)transferred, (NSUInteger)transferrable); - }); - }, notifier_direction, is_streaming); - return [[RLMProgressNotificationToken alloc] initWithTokenValue:token session:std::move(session)]; - } - return nil; -} - -+ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token { - if (!token->_isValid) { - return; - } - token->_isValid = NO; - SyncManager::shared().immediately_run_file_actions(std::move(token->_originalPath)); -} - -+ (nullable RLMSyncSession *)sessionForRealm:(RLMRealm *)realm { - auto& config = realm->_realm->config().sync_config; - if (!config) { - return nil; - } - if (auto session = config->user->session_for_on_disk_path(realm->_realm->config().path)) { - return [[RLMSyncSession alloc] initWithSyncSession:session]; - } - return nil; -} - -@end - -// MARK: - Error action token - -@implementation RLMSyncErrorActionToken - -- (instancetype)initWithOriginalPath:(std::string)originalPath { - if (self = [super init]) { - _isValid = YES; - _originalPath = std::move(originalPath); - return self; - } - return nil; -} - -@end - -@implementation RLMAsyncOpenTask { - bool _cancel; - NSMutableArray *_blocks; -} - -- (void)addProgressNotificationOnQueue:(dispatch_queue_t)queue block:(RLMProgressNotificationBlock)block { - auto wrappedBlock = ^(NSUInteger transferred_bytes, NSUInteger transferrable_bytes) { - dispatch_async(queue, ^{ - @autoreleasepool { - block(transferred_bytes, transferrable_bytes); - } - }); - }; - - @synchronized (self) { - if (_task) { - _task->register_download_progress_notifier(wrappedBlock); - } - else if (!_cancel) { - if (!_blocks) { - _blocks = [NSMutableArray new]; - } - [_blocks addObject:wrappedBlock]; - } - } -} - -- (void)addProgressNotificationBlock:(RLMProgressNotificationBlock)block { - [self addProgressNotificationOnQueue:dispatch_get_main_queue() block:block]; -} - -- (void)cancel { - @synchronized (self) { - if (_task) { - _task->cancel(); - } - else { - _cancel = true; - _blocks = nil; - } - } -} - -- (void)setTask:(std::shared_ptr)task { - @synchronized (self) { - _task = task; - if (_cancel) { - _task->cancel(); - } - for (RLMProgressNotificationBlock block in _blocks) { - _task->register_download_progress_notifier(block); - } - _blocks = nil; - } -} -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm b/Lesson14/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm deleted file mode 100644 index b2de98d..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncSessionRefreshHandle.mm +++ /dev/null @@ -1,278 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncSessionRefreshHandle.hpp" - -#import "RLMJSONModels.h" -#import "RLMNetworkClient.h" -#import "RLMSyncManager_Private.h" -#import "RLMSyncUser_Private.hpp" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -#import "sync/sync_session.hpp" - -using namespace realm; - -namespace { - -void unregisterRefreshHandle(const std::weak_ptr& user, const std::string& path) { - if (auto strong_user = user.lock()) { - context_for(strong_user).unregister_refresh_handle(path); - } -} - -void reportInvalidAccessToken(const std::weak_ptr& user, NSError *error) { - if (auto strong_user = user.lock()) { - if (RLMUserErrorReportingBlock block = context_for(strong_user).error_handler()) { - RLMSyncUser *theUser = [[RLMSyncUser alloc] initWithSyncUser:std::move(strong_user)]; - [theUser logOut]; - block(theUser, error); - } - } -} - -} - -static const NSTimeInterval RLMRefreshBuffer = 10; - -@interface RLMSyncSessionRefreshHandle () { - std::weak_ptr _user; - std::string _path; - std::weak_ptr _session; - std::shared_ptr _strongSession; -} - -@property (nonatomic) dispatch_source_t timer; - -@property (nonatomic) NSURL *realmURL; -@property (nonatomic) NSURL *authServerURL; -@property (nonatomic, copy) RLMSyncBasicErrorReportingBlock completionBlock; - -@end - -@implementation RLMSyncSessionRefreshHandle - -- (instancetype)initWithRealmURL:(NSURL *)realmURL - user:(std::shared_ptr)user - session:(std::shared_ptr)session - completionBlock:(RLMSyncBasicErrorReportingBlock)completionBlock { - if (self = [super init]) { - NSString *path = [realmURL path]; - _path = [path UTF8String]; - self.authServerURL = [NSURL URLWithString:@(user->server_url().c_str())]; - if (!self.authServerURL) { - @throw RLMException(@"User object isn't configured with an auth server URL."); - } - self.completionBlock = completionBlock; - self.realmURL = realmURL; - // For the initial bind, we want to prolong the session's lifetime. - _strongSession = std::move(session); - _session = _strongSession; - _user = user; - // Immediately fire off the network request. - [self _timerFired]; - return self; - } - return nil; -} - -- (void)dealloc { - [self cancelTimer]; -} - -- (void)invalidate { - _strongSession = nullptr; - [self cancelTimer]; -} - -- (void)cancelTimer { - if (self.timer) { - dispatch_source_cancel(self.timer); - self.timer = nil; - } -} - -+ (NSDate *)fireDateForTokenExpirationDate:(NSDate *)date nowDate:(NSDate *)nowDate { - NSDate *fireDate = [date dateByAddingTimeInterval:-RLMRefreshBuffer]; - // Only fire times in the future are valid. - return ([fireDate compare:nowDate] == NSOrderedDescending ? fireDate : nil); -} - -- (void)scheduleRefreshTimer:(NSDate *)dateWhenTokenExpires { - [self cancelTimer]; - - NSDate *fireDate = [RLMSyncSessionRefreshHandle fireDateForTokenExpirationDate:dateWhenTokenExpires - nowDate:[NSDate date]]; - if (!fireDate) { - unregisterRefreshHandle(_user, _path); - return; - } - - NSTimeInterval timeToExpiration = [fireDate timeIntervalSinceNow]; - self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); - dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, timeToExpiration * NSEC_PER_SEC), - /* interval */ DISPATCH_TIME_FOREVER, - /* leeway */ NSEC_PER_SEC * (timeToExpiration / 10)); - dispatch_source_set_event_handler(self.timer, ^{ [self _timerFired]; }); - dispatch_resume(self.timer); -} - -/// Handler for network requests whose responses successfully parse into an auth response model. -- (BOOL)_handleSuccessfulRequest:(RLMAuthResponseModel *)model session:(SyncSession&)session { - // Realm Cloud will give us a url prefix in the auth response that we need - // to pass onto objectstore to have it connect to the proper sync worker - if (model.urlPrefix) { - session.set_url_prefix(model.urlPrefix.UTF8String); - } - - // Calculate the resolved path. - NSString *resolvedURLString = nil; - RLMServerPath resolvedPath = model.accessToken.tokenData.path; - // Munge the path back onto the original URL, because the `sync` API expects an entire URL. - NSURLComponents *urlBuffer = [NSURLComponents componentsWithURL:self.realmURL - resolvingAgainstBaseURL:YES]; - urlBuffer.path = resolvedPath; - resolvedURLString = [[urlBuffer URL] absoluteString]; - if (!resolvedURLString) { - @throw RLMException(@"Resolved path returned from the server was invalid (%@).", resolvedPath); - } - // Pass the token and resolved path to the underlying sync subsystem. - session.refresh_access_token([model.accessToken.token UTF8String], {resolvedURLString.UTF8String}); - - // Schedule a refresh. If we're successful we must already have `bind()`ed the session - // initially, so we can null out the strong pointer. - _strongSession = nullptr; - NSDate *expires = [NSDate dateWithTimeIntervalSince1970:model.accessToken.tokenData.expires]; - [self scheduleRefreshTimer:expires]; - - if (self.completionBlock) { - self.completionBlock(nil); - } - return true; -} - -/// Handler for network requests that failed before the JSON parsing stage. -- (void)_handleFailedRequest:(NSError *)error { - NSError *authError; - if ([error.domain isEqualToString:RLMSyncAuthErrorDomain]) { - // Network client may return sync related error - authError = error; - // Try to report this error to the expiration callback. - reportInvalidAccessToken(_user, authError); - } else { - // Something else went wrong - authError = make_auth_error_bad_response(); - } - if (self.completionBlock) { - self.completionBlock(authError); - } - [[RLMSyncManager sharedManager] _fireError:make_sync_error(authError)]; - // Certain errors related to network connectivity should trigger a retry. - NSDate *nextTryDate = nil; - if ([error.domain isEqualToString:NSURLErrorDomain]) { - switch (error.code) { - case NSURLErrorCannotConnectToHost: - case NSURLErrorNotConnectedToInternet: - case NSURLErrorNetworkConnectionLost: - case NSURLErrorTimedOut: - case NSURLErrorDNSLookupFailed: - case NSURLErrorCannotFindHost: - // FIXME: 10 seconds is an arbitrarily chosen value, consider rationalizing it. - nextTryDate = [NSDate dateWithTimeIntervalSinceNow:RLMRefreshBuffer + 10]; - break; - default: - break; - } - } - if (!nextTryDate) { - // This error isn't a network failure error. Just invalidate the refresh handle and stop. - if (_strongSession) { - _strongSession->log_out(); - } - unregisterRefreshHandle(_user, _path); - [self invalidate]; - return; - } - // If we tried to initially bind the session and failed, we'll try again. However, each - // subsequent attempt will use a weak pointer to avoid prolonging the session's lifetime - // unnecessarily. - _strongSession = nullptr; - [self scheduleRefreshTimer:nextTryDate]; - return; -} - -/// Callback handler for network requests. -- (BOOL)_onRefreshCompletionWithError:(NSError *)error json:(NSDictionary *)json { - std::shared_ptr session = _session.lock(); - if (!session) { - // The session is dead or in a fatal error state. - unregisterRefreshHandle(_user, _path); - [self invalidate]; - return NO; - } - - if (json && !error) { - RLMAuthResponseModel *model = [[RLMAuthResponseModel alloc] initWithDictionary:json - requireAccessToken:YES - requireRefreshToken:NO]; - if (model) { - return [self _handleSuccessfulRequest:model session:*session]; - } - // Otherwise, malformed JSON - unregisterRefreshHandle(_user, _path); - NSError *error = make_sync_error(make_auth_error_bad_response(json)); - if (self.completionBlock) { - self.completionBlock(error); - } - [[RLMSyncManager sharedManager] _fireError:error]; - } else { - REALM_ASSERT(error); - [self _handleFailedRequest:error]; - } - return NO; -} - -- (void)_timerFired { - RLMServerToken refreshToken = nil; - if (auto user = _user.lock()) { - refreshToken = @(user->refresh_token().c_str()); - } - if (!refreshToken) { - unregisterRefreshHandle(_user, _path); - return; - } - - NSDictionary *json = @{ - kRLMSyncProviderKey: @"realm", - kRLMSyncPathKey: @(_path.c_str()), - kRLMSyncDataKey: refreshToken, - kRLMSyncAppIDKey: [RLMSyncManager sharedManager].appID, - }; - - __weak RLMSyncSessionRefreshHandle *weakSelf = self; - RLMSyncCompletionBlock handler = ^(NSError *error, NSDictionary *json) { - [weakSelf _onRefreshCompletionWithError:error json:json]; - }; - [RLMSyncAuthEndpoint sendRequestToServer:self.authServerURL - JSON:json - timeout:60.0 - completion:handler]; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncSubscription.mm b/Lesson14/Pods/Realm/Realm/RLMSyncSubscription.mm deleted file mode 100644 index b17c033..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncSubscription.mm +++ /dev/null @@ -1,443 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2018 Realm Inc. -// -// 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 "RLMSyncSubscription.h" - -#import "RLMObjectSchema_Private.hpp" -#import "RLMObject_Private.hpp" -#import "RLMProperty_Private.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMResults_Private.hpp" -#import "RLMUtil.hpp" - -#import "object_store.hpp" -#import "sync/partial_sync.hpp" - -using namespace realm; - -@implementation RLMSyncSubscriptionOptions -@end - -@interface RLMSyncSubscription () -@property (nonatomic, readwrite) RLMSyncSubscriptionState state; -@property (nonatomic, readwrite, nullable) NSError *error; -@property (nonatomic, readwrite) NSString *query; -@property (nonatomic, readwrite, nullable) NSDate *createdAt; -@property (nonatomic, readwrite, nullable) NSDate *updatedAt; -@property (nonatomic, readwrite, nullable) NSDate *expiresAt; -@property (nonatomic, readwrite) NSTimeInterval timeToLive; -@end - -@implementation RLMSyncSubscription { - partial_sync::SubscriptionNotificationToken _token; - util::Optional _subscription; - Object _obj; - RLMRealm *_realm; -} - -static std::vector parseKeypath(StringData keypath, Group const& group, - Schema const& schema, const ObjectSchema *objectSchema) { - auto check = [&](bool condition, const char* fmt, auto... args) { - if (!condition) { - throw std::invalid_argument(util::format("Invalid LinkingObjects inclusion from key path '%1': %2.", - keypath, util::format(fmt, args...))); - } - }; - - const char* begin = keypath.data(); - const char* end = keypath.data() + keypath.size(); - check(begin != end, "missing property name"); - - std::vector ret; - while (begin != end) { - auto sep = std::find(begin, end, '.'); - check(sep != begin && sep + 1 != end, "missing property name"); - StringData key(begin, sep - begin); - begin = sep + (sep != end); - - auto prop = objectSchema->property_for_name(key); - check(prop, "property '%1.%2' does not exist", objectSchema->name, key); - check(prop->type == PropertyType::Object || prop->type == PropertyType::LinkingObjects, - "property '%1.%2' is of unsupported type '%3'", - objectSchema->name, key, string_for_property_type(prop->type)); - - objectSchema = &*schema.find(prop->object_type); - - if (prop->type == PropertyType::Object) { - check(begin != end, "key path must end in a LinkingObjects property and '%1.%2' is of type '%3'", - objectSchema->name, key, string_for_property_type(prop->type)); - ret.emplace_back(prop->table_column); - } - else { - ret.emplace_back(objectSchema->property_for_name(prop->link_origin_property_name)->table_column, - ObjectStore::table_for_object_type(group, objectSchema->name)); - } - } - return ret; -} - -- (instancetype)initWithOptions:(RLMSyncSubscriptionOptions *)options results:(Results const&)results realm:(RLMRealm *)realm { - if (!(self = [super init])) - return nil; - - _name = [options.name copy]; - _timeToLive = NAN; - _realm = realm; - _createdAt = _updatedAt = NSDate.date; - try { - partial_sync::SubscriptionOptions opt; - if (options.name) { - opt.user_provided_name = std::string(RLMStringDataWithNSString(options.name)); - } - if (options.timeToLive > 0) { - opt.time_to_live_ms = options.timeToLive * 1000; - } - opt.update = options.overwriteExisting; - if (options.includeLinkingObjectProperties) { - std::vector> keypaths; - for (NSString *keyPath in options.includeLinkingObjectProperties) { - keypaths.push_back(parseKeypath(keyPath.UTF8String, realm.group, - realm->_realm->schema(), - &results.get_object_schema())); - } - opt.inclusions = IncludeDescriptor{*ObjectStore::table_for_object_type(realm.group, results.get_object_type()), keypaths}; - } - _subscription = partial_sync::subscribe(options.limit ? results.limit(options.limit) : results, std::move(opt)); - } - catch (std::exception const& e) { - @throw RLMException(e); - } - self.state = (RLMSyncSubscriptionState)_subscription->state(); - __weak auto weakSelf = self; - _token = _subscription->add_notification_callback([weakSelf] { - RLMSyncSubscription *self; - @autoreleasepool { - self = weakSelf; - if (!self) - return; - } - - // Retrieve the current error and status. Update our properties only if the values have changed, - // since clients use KVO to observe these properties. - - if (auto error = self->_subscription->error()) { - try { - std::rethrow_exception(error); - } catch (...) { - NSError *nsError; - RLMRealmTranslateException(&nsError); - if (!self.error || ![self.error isEqual:nsError]) - self.error = nsError; - } - } - else if (self.error) { - self.error = nil; - } - - auto status = (RLMSyncSubscriptionState)self->_subscription->state(); - if (status != self.state) { - if (status == RLMSyncSubscriptionStateCreating) { - // If a subscription is deleted without going through this - // object's unsubscribe() method the subscription will transition - // back to Creating rather than Invalidated since it doesn't - // have a good way to track that it previously existed - if (self.state != RLMSyncSubscriptionStateInvalidated) - self.state = RLMSyncSubscriptionStateInvalidated; - } - else { - self.state = status; - } - } - - if (status != RLMSyncSubscriptionStateComplete) { - return; - } - - auto obj = self->_subscription->result_set_object(); - if (obj && obj->is_valid()) { - _obj = std::move(*obj); - _token = {}; - _token.result_sets_token = _obj.add_notification_callback([weakSelf](CollectionChangeSet const&, std::exception_ptr) { - @autoreleasepool { - [weakSelf updateFromRow]; - } - }); - [self updateFromRow]; - } - }); - - return self; -} - -- (void)unsubscribe { - partial_sync::unsubscribe(*_subscription); -} - -- (void)updateFromRow { - // We only want to call the setter if the value actually changed because of KVO -#define REALM_SET_IF_CHANGED(prop, value) do { \ - auto newValue = value; \ - if (prop != newValue) { \ - prop = newValue; \ - } \ -} while (0) - - if (!_obj.is_valid()) { - REALM_SET_IF_CHANGED(self.state, RLMSyncSubscriptionStateInvalidated); - return; - } - - auto row = _obj.row(); - REALM_SET_IF_CHANGED(self.query, RLMStringDataToNSString(row.get_string(row.get_column_index("query")))); - REALM_SET_IF_CHANGED(self.createdAt, RLMTimestampToNSDate(row.get_timestamp(row.get_column_index("created_at")))); - REALM_SET_IF_CHANGED(self.updatedAt, RLMTimestampToNSDate(row.get_timestamp(row.get_column_index("updated_at")))); - REALM_SET_IF_CHANGED(self.expiresAt, RLMTimestampToNSDate(row.get_timestamp(row.get_column_index("expires_at")))); -#undef REALM_SET_IF_CHANGED - - auto ttl = row.get>(row.get_column_index("time_to_live")); - if (ttl && _timeToLive != *ttl / 1000.0) { - self.timeToLive = *ttl / 1000.0; - } - else if (!ttl && !isnan(_timeToLive)) { - self.timeToLive = NAN; - } -} -@end - -@interface RLMSyncSubscriptionObject : RLMObjectBase -@end -@implementation RLMSyncSubscriptionObject { - util::Optional _token; - Object _obj; -} - -+ (NSString *)primaryKey { - return nil; -} - -+ (NSDictionary *)defaultPropertyValues { - return nil; -} - -- (NSString *)name { - return _row.is_attached() ? RLMStringDataToNSString(_row.get_string(_row.get_column_index("name"))) : nil; -} - -- (NSString *)query { - return _row.is_attached() ? RLMStringDataToNSString(_row.get_string(_row.get_column_index("query"))) : nil; -} - -- (RLMSyncSubscriptionState)state { - if (!_row.is_attached()) { - return RLMSyncSubscriptionStateInvalidated; - } - return (RLMSyncSubscriptionState)_row.get_int(_row.get_column_index("status")); -} - -- (NSError *)error { - if (!_row.is_attached()) { - return nil; - } - StringData err = _row.get_string(_row.get_column_index("error_message")); - if (!err.size()) { - return nil; - } - return [NSError errorWithDomain:RLMErrorDomain - code:RLMErrorFail - userInfo:@{NSLocalizedDescriptionKey: RLMStringDataToNSString(err)}]; -} - -- (NSDate *)createdAt { - return _row.is_attached() ? RLMTimestampToNSDate(_row.get_timestamp(_row.get_column_index("created_at"))) : nil; -} - -- (NSDate *)updatedAt { - return _row.is_attached() ? RLMTimestampToNSDate(_row.get_timestamp(_row.get_column_index("updated_at"))) : nil; -} - -- (NSDate *)expiresAt { - return _row.is_attached() ? RLMTimestampToNSDate(_row.get_timestamp(_row.get_column_index("expires_at"))) : nil; -} - -- (NSTimeInterval)timeToLive { - if (!_row.is_attached()) { - return NAN; - } - auto columnIndex = _row.get_column_index("time_to_live"); - if (_row.is_null(columnIndex)) { - return NAN; - } - return _row.get_int(columnIndex) / 1000.0; -} - -- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth { - if (depth == 0) { - return @""; - } - - auto objectType = _row.get_string(_row.get_column_index("matches_property")); - objectType = objectType.substr(0, objectType.size() - strlen("_matches")); - return [NSString stringWithFormat:@"RLMSyncSubscription {\n\tname = %@\n\tobjectType = %@\n\tquery = %@\n\tstatus = %@\n\terror = %@\n\tcreatedAt = %@\n\tupdatedAt = %@\n\texpiresAt = %@\n\ttimeToLive = %@\n}", - self.name, RLMStringDataToNSString(objectType), - RLMStringDataToNSString(_row.get_string(_row.get_column_index("query"))), - @(self.state), self.error, self.createdAt, self.updatedAt, self.expiresAt, @(self.timeToLive)]; -} - -- (void)unsubscribe { - if (_row) { - partial_sync::unsubscribe(Object(_realm->_realm, *_info->objectSchema, _row)); - } -} - -- (void)addObserver:(id)observer - forKeyPath:(NSString *)keyPath - options:(NSKeyValueObservingOptions)options - context:(void *)context { - // Make the `state` property observable by using an object notifier to - // trigger changes. The normal KVO mechanisms don't work for this class due - // to it not being a normal part of the schema. - if (!_token) { - struct { - __weak RLMSyncSubscriptionObject *weakSelf; - - void before(realm::CollectionChangeSet const&) { - @autoreleasepool { - [weakSelf willChangeValueForKey:@"state"]; - } - } - - void after(realm::CollectionChangeSet const&) { - @autoreleasepool { - [weakSelf didChangeValueForKey:@"state"]; - } - } - - void error(std::exception_ptr) {} - } callback{self}; - _obj = Object(_realm->_realm, *_info->objectSchema, _row); - _token = _obj.add_notification_callback(callback); - } - [super addObserver:observer forKeyPath:keyPath options:options context:context]; -} -@end - -static ObjectSchema& addPublicNames(ObjectSchema& os) { - using namespace partial_sync; - os.property_for_name(property_created_at)->public_name = "createdAt"; - os.property_for_name(property_updated_at)->public_name = "updatedAt"; - os.property_for_name(property_expires_at)->public_name = "expiresAt"; - os.property_for_name(property_time_to_live)->public_name = "timeToLive"; - os.property_for_name(property_error_message)->public_name = "error"; - return os; -} - -// RLMClassInfo stores pointers into the schema rather than owning the objects -// it points to, so for a ClassInfo that's not part of the schema we need a -// wrapper object that owns them -RLMResultsSetInfo::RLMResultsSetInfo(__unsafe_unretained RLMRealm *const realm) -: osObjectSchema(realm->_realm->read_group(), partial_sync::result_sets_type_name) -, rlmObjectSchema([RLMObjectSchema objectSchemaForObjectStoreSchema:addPublicNames(osObjectSchema)]) -, info(realm, rlmObjectSchema, &osObjectSchema) -{ - rlmObjectSchema.accessorClass = [RLMSyncSubscriptionObject class]; -} - -RLMClassInfo& RLMResultsSetInfo::get(__unsafe_unretained RLMRealm *const realm) { - if (!realm->_resultsSetInfo) { - realm->_resultsSetInfo = std::make_unique(realm); - } - return realm->_resultsSetInfo->info; -} - -@interface RLMSubscriptionResults : RLMResults -@end - -@implementation RLMSubscriptionResults -+ (instancetype)resultsWithRealm:(RLMRealm *)realm { - auto table = ObjectStore::table_for_object_type(realm->_realm->read_group(), partial_sync::result_sets_type_name); - if (!table) { - @throw RLMException(@"-[RLMRealm subscriptions] can only be called on a Realm using query-based sync"); - } - // The server automatically adds a few subscriptions for the permissions - // types which we want to hide. They're just an implementation detail and - // deleting them won't work out well for the user. - auto query = table->where().ends_with(table->get_column_index("matches_property"), "_matches"); - return [self resultsWithObjectInfo:RLMResultsSetInfo::get(realm) - results:Results(realm->_realm, std::move(query))]; -} - -// These operations require a valid schema for the type. It's unclear how they -// would be useful so it's probably not worth fixing this. -- (RLMResults *)sortedResultsUsingDescriptors:(__unused NSArray *)properties { - @throw RLMException(@"Sorting subscription results is currently not implemented"); -} - -- (RLMResults *)distinctResultsUsingKeyPaths:(__unused NSArray *)keyPaths { - @throw RLMException(@"Distincting subscription results is currently not implemented"); -} -@end - -@implementation RLMResults (SyncSubscription) -- (RLMSyncSubscription *)subscribe { - return [[RLMSyncSubscription alloc] initWithOptions:nil results:_results realm:self.realm]; -} - -- (RLMSyncSubscription *)subscribeWithName:(NSString *)subscriptionName { - auto options = [[RLMSyncSubscriptionOptions alloc] init]; - options.name = subscriptionName; - return [[RLMSyncSubscription alloc] initWithOptions:options results:_results realm:self.realm]; -} - -- (RLMSyncSubscription *)subscribeWithName:(NSString *)subscriptionName limit:(NSUInteger)limit { - auto options = [[RLMSyncSubscriptionOptions alloc] init]; - options.name = subscriptionName; - options.limit = limit; - return [[RLMSyncSubscription alloc] initWithOptions:options results:_results realm:self.realm]; -} - -- (RLMSyncSubscription *)subscribeWithOptions:(RLMSyncSubscriptionOptions *)options { - return [[RLMSyncSubscription alloc] initWithOptions:options results:_results realm:self.realm]; -} -@end - -@implementation RLMRealm (SyncSubscription) -- (RLMResults *)subscriptions { - [self verifyThread]; - return [RLMSubscriptionResults resultsWithRealm:self]; -} - -- (nullable RLMSyncSubscription *)subscriptionWithName:(NSString *)name { - [self verifyThread]; - auto& info = RLMResultsSetInfo::get(self); - if (!info.table()) { - @throw RLMException(@"-[RLMRealm subcriptionWithName:] can only be called on a Realm using query-based sync"); - } - auto row = info.table()->find_first(info.table()->get_column_index("name"), - RLMStringDataWithNSString(name)); - if (row == npos) { - return nil; - } - RLMObjectBase *acc = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info); - acc->_row = info.table()->get(row); - return (RLMSyncSubscription *)acc; -} -@end - -RLMSyncSubscription *RLMCastToSyncSubscription(id obj) { - return obj; -} diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncUser.mm b/Lesson14/Pods/Realm/Realm/RLMSyncUser.mm deleted file mode 100644 index 1c60cd2..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncUser.mm +++ /dev/null @@ -1,686 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncUser_Private.hpp" - -#import "RLMJSONModels.h" -#import "RLMNetworkClient.h" -#import "RLMRealmConfiguration+Sync.h" -#import "RLMRealmConfiguration_Private.hpp" -#import "RLMRealmUtil.hpp" -#import "RLMResults_Private.hpp" -#import "RLMSyncConfiguration.h" -#import "RLMSyncConfiguration_Private.hpp" -#import "RLMSyncManager_Private.h" -#import "RLMSyncPermission.h" -#import "RLMSyncSessionRefreshHandle.hpp" -#import "RLMSyncSession_Private.hpp" -#import "RLMSyncUtil_Private.hpp" -#import "RLMUtil.hpp" - -#import "sync/sync_manager.hpp" -#import "sync/sync_session.hpp" -#import "sync/sync_user.hpp" - -using namespace realm; - -void CocoaSyncUserContext::register_refresh_handle(const std::string& path, RLMSyncSessionRefreshHandle *handle) -{ - REALM_ASSERT(handle); - std::lock_guard lock(m_mutex); - auto& refresh_handle = m_refresh_handles[path]; - [refresh_handle invalidate]; - refresh_handle = handle; -} - -void CocoaSyncUserContext::unregister_refresh_handle(const std::string& path) -{ - std::lock_guard lock(m_mutex); - m_refresh_handles.erase(path); -} - -void CocoaSyncUserContext::invalidate_all_handles() -{ - std::lock_guard lock(m_mutex); - for (auto& it : m_refresh_handles) { - [it.second invalidate]; - } - m_refresh_handles.clear(); -} - -RLMUserErrorReportingBlock CocoaSyncUserContext::error_handler() const -{ - std::lock_guard lock(m_error_handler_mutex); - return m_error_handler; -} - -void CocoaSyncUserContext::set_error_handler(RLMUserErrorReportingBlock block) -{ - std::lock_guard lock(m_error_handler_mutex); - m_error_handler = block; -} - -@interface RLMSyncUserInfo () - -@property (nonatomic, readwrite) NSArray *accounts; -@property (nonatomic, readwrite) NSDictionary *metadata; -@property (nonatomic, readwrite) NSString *identity; -@property (nonatomic, readwrite) BOOL isAdmin; - -+ (instancetype)syncUserInfoWithModel:(RLMUserResponseModel *)model; - -@end - -@interface RLMSyncUser () { - std::shared_ptr _user; -} -@end - -@implementation RLMSyncUser - -#pragma mark - static API - -+ (NSDictionary *)allUsers { - NSArray *allUsers = [[RLMSyncManager sharedManager] _allUsers]; - return [NSDictionary dictionaryWithObjects:allUsers - forKeys:[allUsers valueForKey:@"identity"]]; -} - -+ (RLMSyncUser *)currentUser { - NSArray *allUsers = [[RLMSyncManager sharedManager] _allUsers]; - if (allUsers.count > 1 && [NSSet setWithArray:[allUsers valueForKey:@"identity"]].count > 1) { - @throw RLMException(@"+currentUser cannot be called if more that one valid, logged-in user exists."); - } - return allUsers.firstObject; -} - -#pragma mark - API - -- (instancetype)initWithSyncUser:(std::shared_ptr)user { - if (self = [super init]) { - _user = user; - return self; - } - return nil; -} - -- (BOOL)isEqual:(id)object { - if (![object isKindOfClass:[RLMSyncUser class]]) { - return NO; - } - return _user == ((RLMSyncUser *)object)->_user; -} - -+ (void)logInWithCredentials:(RLMSyncCredentials *)credential - authServerURL:(NSURL *)authServerURL - onCompletion:(RLMUserCompletionBlock)completion { - [self logInWithCredentials:credential - authServerURL:authServerURL - timeout:0 // use timeout from RLMSyncManager - callbackQueue:dispatch_get_main_queue() - onCompletion:completion]; -} - -+ (void)logInWithCredentials:(RLMSyncCredentials *)credentials - authServerURL:(NSURL *)authServerURL - timeout:(NSTimeInterval)timeout - callbackQueue:(dispatch_queue_t)callbackQueue - onCompletion:(RLMUserCompletionBlock)completion { - // Special credential login should be treated differently. - if (credentials.provider == RLMIdentityProviderAccessToken) { - [self _performLoginForDirectAccessTokenCredentials:credentials - authServerURL:authServerURL - completionBlock:completion]; - return; - } - if (credentials.provider == RLMIdentityProviderCustomRefreshToken) { - [self _performLoginForCustomRefreshTokenCredentials:credentials - authServerURL:authServerURL - completionBlock:completion]; - return; - } - if (!authServerURL) { - @throw RLMException(@"A user cannot be logged in without specifying an authentication server URL."); - } - - // Prepare login network request - NSMutableDictionary *json = [@{ - kRLMSyncProviderKey: credentials.provider, - kRLMSyncDataKey: credentials.token, - kRLMSyncAppIDKey: RLMSyncManager.sharedManager.appID, - } mutableCopy]; - if (credentials.userInfo.count) { - // Munge user info into the JSON request. - json[@"user_info"] = credentials.userInfo; - } - - RLMSyncCompletionBlock handler = ^(NSError *error, NSDictionary *json) { - if (error) { - return completion(nil, error); - } - - RLMAuthResponseModel *model = [[RLMAuthResponseModel alloc] initWithDictionary:json - requireAccessToken:NO - requireRefreshToken:YES]; - if (!model) { - // Malformed JSON - return completion(nil, make_auth_error_bad_response(json)); - } - - SyncUserIdentifier identity{model.refreshToken.tokenData.identity.UTF8String, - authServerURL.absoluteString.UTF8String}; - auto sync_user = SyncManager::shared().get_user(identity , [model.refreshToken.token UTF8String]); - if (!sync_user) { - return completion(nil, make_auth_error_client_issue()); - } - sync_user->set_is_admin(model.refreshToken.tokenData.isAdmin); - return completion([[RLMSyncUser alloc] initWithSyncUser:std::move(sync_user)], nil); - }; - - [RLMSyncAuthEndpoint sendRequestToServer:authServerURL - JSON:json - timeout:timeout - completion:^(NSError *error, NSDictionary *dictionary) { - dispatch_async(callbackQueue, ^{ - handler(error, dictionary); - }); - }]; -} - -- (RLMRealmConfiguration *)configuration { - return [self configurationWithURL:nil - fullSynchronization:NO - enableSSLValidation:YES - urlPrefix:nil]; -} - -- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url { - return [self configurationWithURL:url - fullSynchronization:NO - enableSSLValidation:YES - urlPrefix:nil]; -} - -- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url fullSynchronization:(bool)fullSynchronization { - return [self configurationWithURL:url - fullSynchronization:fullSynchronization - enableSSLValidation:YES - urlPrefix:nil]; -} - -- (RLMRealmConfiguration *)configurationWithURL:(NSURL *)url - fullSynchronization:(bool)fullSynchronization - enableSSLValidation:(bool)enableSSLValidation - urlPrefix:(NSString * _Nullable)urlPrefix { - auto syncConfig = [[RLMSyncConfiguration alloc] initWithUser:self - realmURL:url ?: self.defaultRealmURL - customFileURL:nil - isPartial:!fullSynchronization - stopPolicy:RLMSyncStopPolicyAfterChangesUploaded]; - syncConfig.urlPrefix = urlPrefix; - syncConfig.enableSSLValidation = enableSSLValidation; - syncConfig.pinnedCertificateURL = RLMSyncManager.sharedManager.pinnedCertificatePaths[syncConfig.realmURL.host]; - RLMRealmConfiguration *config = [[RLMRealmConfiguration alloc] init]; - config.syncConfiguration = syncConfig; - return config; -} - -- (void)logOut { - if (!_user) { - return; - } - _user->log_out(); - context_for(_user).invalidate_all_handles(); -} - -- (void)invalidate { - if (!_user) { - return; - } - context_for(_user).invalidate_all_handles(); - _user = nullptr; -} - -- (RLMUserErrorReportingBlock)errorHandler { - if (!_user) { - return nil; - } - return context_for(_user).error_handler(); -} - -- (void)setErrorHandler:(RLMUserErrorReportingBlock)errorHandler { - if (!_user) { - return; - } - context_for(_user).set_error_handler([errorHandler copy]); -} - -- (nullable RLMSyncSession *)sessionForURL:(NSURL *)url { - if (!_user) { - return nil; - } - auto path = SyncManager::shared().path_for_realm(*_user, [url.absoluteString UTF8String]); - if (auto session = _user->session_for_on_disk_path(path)) { - return [[RLMSyncSession alloc] initWithSyncSession:session]; - } - return nil; -} - -- (NSArray *)allSessions { - if (!_user) { - return @[]; - } - NSMutableArray *buffer = [NSMutableArray array]; - auto sessions = _user->all_sessions(); - for (auto session : sessions) { - [buffer addObject:[[RLMSyncSession alloc] initWithSyncSession:std::move(session)]]; - } - return [buffer copy]; -} - -- (NSString *)identity { - if (!_user) { - return nil; - } - return @(_user->identity().c_str()); -} - -- (RLMSyncUserState)state { - if (!_user) { - return RLMSyncUserStateError; - } - switch (_user->state()) { - case SyncUser::State::Active: - return RLMSyncUserStateActive; - case SyncUser::State::LoggedOut: - return RLMSyncUserStateLoggedOut; - case SyncUser::State::Error: - return RLMSyncUserStateError; - } -} - -- (NSURL *)authenticationServer { - if (!_user || _user->token_type() == SyncUser::TokenType::Admin) { - return nil; - } - return [NSURL URLWithString:@(_user->server_url().c_str())]; -} - -- (BOOL)isAdmin { - if (!_user) { - return NO; - } - return _user->is_admin(); -} - -#pragma mark - Passwords - -- (void)changePassword:(NSString *)newPassword completion:(RLMPasswordChangeStatusBlock)completion { - [self changePassword:newPassword forUserID:self.identity completion:completion]; -} - -- (void)changePassword:(NSString *)newPassword forUserID:(NSString *)userID completion:(RLMPasswordChangeStatusBlock)completion { - if (self.state != RLMSyncUserStateActive) { - completion([NSError errorWithDomain:RLMSyncErrorDomain - code:RLMSyncErrorClientSessionError - userInfo:nil]); - return; - } - [RLMSyncChangePasswordEndpoint sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken, - kRLMSyncUserIDKey: userID, - kRLMSyncDataKey: @{kRLMSyncNewPasswordKey: newPassword}} - completion:completion]; -} - -+ (void)requestPasswordResetForAuthServer:(NSURL *)serverURL - userEmail:(NSString *)email - completion:(RLMPasswordChangeStatusBlock)completion { - [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL - JSON:@{@"provider_id": email, @"data": @{@"action": @"reset_password"}} - completion:completion]; -} - -+ (void)completePasswordResetForAuthServer:(NSURL *)serverURL - token:(NSString *)token - password:(NSString *)newPassword - completion:(RLMPasswordChangeStatusBlock)completion { - [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL - JSON:@{@"data": @{@"action": @"complete_reset", - @"token": token, - @"new_password": newPassword}} - completion:completion]; -} - -+ (void)requestEmailConfirmationForAuthServer:(NSURL *)serverURL - userEmail:(NSString *)email - completion:(RLMPasswordChangeStatusBlock)completion { - [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL - JSON:@{@"provider_id": email, - @"data": @{@"action": @"request_email_confirmation"}} - completion:completion]; -} - -+ (void)confirmEmailForAuthServer:(NSURL *)serverURL - token:(NSString *)token - completion:(RLMPasswordChangeStatusBlock)completion { - [RLMSyncUpdateAccountEndpoint sendRequestToServer:serverURL - JSON:@{@"data": @{@"action": @"confirm_email", - @"token": token}} - completion:completion]; -} - -#pragma mark - Administrator API - -- (void)retrieveInfoForUser:(NSString *)providerUserIdentity - identityProvider:(RLMIdentityProvider)provider - completion:(RLMRetrieveUserBlock)completion { - [RLMSyncGetUserInfoEndpoint sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncProviderKey: provider, - kRLMSyncProviderIDKey: providerUserIdentity, - kRLMSyncTokenKey: self.refreshToken} - timeout:60 - completion:^(NSError *error, NSDictionary *json) { - if (error) { - return completion(nil, error); - } - RLMUserResponseModel *model = [[RLMUserResponseModel alloc] initWithDictionary:json]; - if (!model) { - return completion(nil, make_auth_error_bad_response(json)); - } - completion([RLMSyncUserInfo syncUserInfoWithModel:model], nil); - }]; -} - -#pragma mark - Permissions API - -namespace { -NSError *checkUser(std::shared_ptr const& user, NSString *msg) { - if (user && user->state() != SyncUser::State::Error) { - return nil; - } - msg = [NSString stringWithFormat:@"Permissions cannot be %@ using an invalid user.", msg]; - return [NSError errorWithDomain:RLMSyncPermissionErrorDomain code:RLMSyncAuthErrorInvalidParameters - userInfo:@{NSLocalizedFailureReasonErrorKey: msg}]; -} -} - -- (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback { - if (NSError *error = checkUser(_user, @"retrieved")) { - callback(nullptr, error); - return; - } - - [RLMSyncGetPermissionsEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken} - timeout:60.0 - completion:^(NSError *error, NSDictionary *json) { - if (error) { - return callback(nil, error); - } - // FIXME: ROS currently gives duplicated results for 'all' due to an incorrect query - NSMutableSet *permissions = [NSMutableSet new]; - for (NSDictionary *permission in json[@"permissions"]) { - // ROS reports the permission for __wildcardpermissions, which we - // don't want to include - if ([permission[@"path"] hasPrefix:@"/__"]) { - continue; - } - - // Wildcard permissions are reported as a null userId - id userId = permission[@"userId"]; - if (userId == NSNull.null) { - userId = @"*"; - } - - [permissions addObject:[[RLMSyncPermission alloc] - initWithRealmPath:permission[@"path"] - identity:userId - accessLevel:RLMSyncAccessLevelFromString(permission[@"accessLevel"])]]; - } - callback(permissions.allObjects, nil); - }]; -} - -- (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback { - if (NSError *error = checkUser(_user, @"applied")) { - callback(error); - return; - } - id condition; - if (permission.identity) { - condition = @{@"userId": permission.identity}; - } - else { - condition = @{@"metadataKey": permission.key, @"metadataValue": permission.value}; - } - [RLMSyncApplyPermissionsEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken, - @"condition": condition, - @"realmPath": permission.path, - @"accessLevel": RLMSyncAccessLevelToString(permission.accessLevel)} - completion:callback]; -} - -- (void)createOfferForRealmAtURL:(NSURL *)url - accessLevel:(RLMSyncAccessLevel)accessLevel - expiration:(NSDate *)expirationDate - callback:(RLMPermissionOfferStatusBlock)callback { - if (NSError *error = checkUser(_user, @"offered")) { - callback(nil, error); - return; - } - - NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; - dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; - dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ"; - dateFormatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; - - [RLMSyncOfferPermissionsEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken, - @"expiresAt": expirationDate ? [RLMISO8601Formatter() stringFromDate:expirationDate] : NSNull.null, - @"realmPath": url.path, - @"accessLevel": RLMSyncAccessLevelToString(accessLevel)} - timeout:60.0 - completion:^(NSError *error, NSDictionary *json) { - callback(json[@"token"], error); - }]; -} - -- (void)acceptOfferForToken:(NSString *)token - callback:(RLMPermissionOfferResponseStatusBlock)callback { - if (NSError *error = checkUser(_user, @"accepted")) { - callback(nil, error); - return; - } - [RLMSyncAcceptPermissionOfferEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken, @"offerToken": token} - timeout:60.0 - completion:^(NSError *error, NSDictionary *json) { - callback([self urlForPath:json[@"path"]], error); - }]; -} - -- (void)invalidateOfferForToken:(NSString *)token - callback:(RLMPermissionStatusBlock)callback { - if (NSError *error = checkUser(_user, @"invalidated")) { - callback(error); - return; - } - [RLMSyncInvalidatePermissionOfferEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken, @"offerToken": token} - timeout:60.0 - completion:^(NSError *error, NSDictionary *) { - callback(error); - }]; -} - -- (void)retrievePermissionOffersWithCallback:(RLMPermissionOfferResultsBlock)callback { - if (NSError *error = checkUser(_user, @"retrieved")) { - callback(nullptr, error); - return; - } - - [RLMSyncGetPermissionOffersEndpoint - sendRequestToServer:self.authenticationServer - JSON:@{kRLMSyncTokenKey: self.refreshToken} - timeout:60.0 - completion:^(NSError *error, NSDictionary *json) { - if (error) { - return callback(nil, error); - } - NSMutableArray *offers = [NSMutableArray new]; - NSDateFormatter *formatter = RLMISO8601Formatter(); - for (NSDictionary *offer in json[@"offers"]) { - NSString *expiresAt = RLMCoerceToNil(offer[@"expiresAt"]); - NSString *createdAt = RLMCoerceToNil(offer[@"createdAt"]); - [offers addObject:[[RLMSyncPermissionOffer alloc] - initWithRealmPath:offer[@"realmPath"] - token:offer[@"token"] - expiresAt:expiresAt ? [formatter dateFromString:expiresAt] : nil - createdAt:createdAt ? [formatter dateFromString:createdAt] : nil - accessLevel:RLMSyncAccessLevelFromString(offer[@"accessLevel"])]]; - } - callback(offers, nil); - }]; -} - -#pragma mark - Private API - -- (NSURL *)urlForPath:(nullable NSString *)path { - if (!path) { - return nil; - } - - NSURLComponents *components = [NSURLComponents componentsWithURL:self.authenticationServer resolvingAgainstBaseURL:YES]; - if ([components.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame) - components.scheme = @"realm"; - else if ([components.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) - components.scheme = @"realms"; - else - @throw RLMException(@"The provided user's authentication server URL (%@) was not valid.", self.authenticationServer); - - components.path = path; - return components.URL; - -} - -- (NSURL *)defaultRealmURL { - return [self urlForPath:@"/default"]; -} - -+ (void)_setUpBindingContextFactory { - SyncUser::set_binding_context_factory([] { - return std::make_shared(); - }); -} - -- (NSString *)refreshToken { - if (!_user) { - return nil; - } - return @(_user->refresh_token().c_str()); -} - -- (std::shared_ptr)_syncUser { - return _user; -} - -+ (void)_performLoginForDirectAccessTokenCredentials:(RLMSyncCredentials *)credentials - authServerURL:(NSURL *)serverURL - completionBlock:(nonnull RLMUserCompletionBlock)completion { - NSString *identity = credentials.userInfo[kRLMSyncIdentityKey]; - std::shared_ptr sync_user; - if (serverURL) { - NSString *scheme = serverURL.scheme; - if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) { - @throw RLMException(@"The Realm Object Server authentication URL provided for this user, \"%@\", " - @" is invalid. It must begin with http:// or https://.", serverURL); - } - // Retrieve the user based on the auth server URL. - util::Optional identity_string; - if (identity) { - identity_string = std::string(identity.UTF8String); - } - sync_user = SyncManager::shared().get_admin_token_user([serverURL absoluteString].UTF8String, - credentials.token.UTF8String, - std::move(identity_string)); - } else { - // Retrieve the user based on the identity. - if (!identity) { - @throw RLMException(@"A direct access credential must specify either an identity, a server URL, or both."); - } - sync_user = SyncManager::shared().get_admin_token_user_from_identity(identity.UTF8String, - none, - credentials.token.UTF8String); - } - if (!sync_user) { - completion(nil, make_auth_error_client_issue()); - return; - } - completion([[RLMSyncUser alloc] initWithSyncUser:std::move(sync_user)], nil); -} - -+ (void)_performLoginForCustomRefreshTokenCredentials:(RLMSyncCredentials *)credentials - authServerURL:(NSURL *)serverURL - completionBlock:(nonnull RLMUserCompletionBlock)completion { - NSString *scheme = serverURL.scheme; - if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) { - @throw RLMException(@"The Realm Object Server authentication URL provided for this user, \"%@\", " - @" is invalid. It must begin with http:// or https://.", serverURL); - } - - NSString *identity = credentials.userInfo[kRLMSyncIdentityKey]; - SyncUserIdentifier identifier{identity.UTF8String, serverURL.absoluteString.UTF8String}; - - std::shared_ptr sync_user = SyncManager::shared().get_user(std::move(identifier), credentials.token.UTF8String); - if (!sync_user) { - completion(nil, make_auth_error_client_issue()); - return; - } - - NSNumber *isAdmin = credentials.userInfo[kRLMSyncIsAdminKey]; - sync_user->set_is_admin(isAdmin.boolValue); - completion([[RLMSyncUser alloc] initWithSyncUser:std::move(sync_user)], nil); -} - -@end - -#pragma mark - RLMSyncUserInfo - -@implementation RLMSyncUserInfo - -- (instancetype)initPrivate { - return [super init]; -} - -+ (instancetype)syncUserInfoWithModel:(RLMUserResponseModel *)model { - RLMSyncUserInfo *info = [[RLMSyncUserInfo alloc] initPrivate]; - info.accounts = model.accounts; - info.metadata = model.metadata; - info.isAdmin = model.isAdmin; - info.identity = model.identity; - return info; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMSyncUtil.mm b/Lesson14/Pods/Realm/Realm/RLMSyncUtil.mm deleted file mode 100644 index 980ba46..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMSyncUtil.mm +++ /dev/null @@ -1,183 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncUtil_Private.hpp" - -#import "RLMJSONModels.h" -#import "RLMObject_Private.hpp" -#import "RLMRealmConfiguration+Sync.h" -#import "RLMRealmConfiguration_Private.hpp" -#import "RLMRealm_Private.hpp" -#import "RLMSyncConfiguration_Private.hpp" -#import "RLMSyncUser_Private.hpp" -#import "RLMUtil.hpp" - -#import "shared_realm.hpp" - -#import "sync/sync_user.hpp" - -RLMIdentityProvider const RLMIdentityProviderAccessToken = @"_access_token"; - -NSString *const RLMSyncErrorDomain = @"io.realm.sync"; -NSString *const RLMSyncAuthErrorDomain = @"io.realm.sync.auth"; -NSString *const RLMSyncPermissionErrorDomain = @"io.realm.sync.permission"; - -NSString *const kRLMSyncPathOfRealmBackupCopyKey = @"recovered_realm_location_path"; -NSString *const kRLMSyncErrorActionTokenKey = @"error_action_token"; - -NSString *const kRLMSyncAppIDKey = @"app_id"; -NSString *const kRLMSyncDataKey = @"data"; -NSString *const kRLMSyncErrorJSONKey = @"json"; -NSString *const kRLMSyncErrorStatusCodeKey = @"statusCode"; -NSString *const kRLMSyncIdentityKey = @"identity"; -NSString *const kRLMSyncIsAdminKey = @"is_admin"; -NSString *const kRLMSyncNewPasswordKey = @"new_password"; -NSString *const kRLMSyncPasswordKey = @"password"; -NSString *const kRLMSyncPathKey = @"path"; -NSString *const kRLMSyncProviderKey = @"provider"; -NSString *const kRLMSyncProviderIDKey = @"provider_id"; -NSString *const kRLMSyncRegisterKey = @"register"; -NSString *const kRLMSyncTokenKey = @"token"; -NSString *const kRLMSyncUnderlyingErrorKey = @"underlying_error"; -NSString *const kRLMSyncUserIDKey = @"user_id"; - -uint8_t RLMGetComputedPermissions(RLMRealm *realm, id _Nullable object) { - if (!object) { - return static_cast(realm->_realm->get_privileges()); - } - if ([object isKindOfClass:[NSString class]]) { - return static_cast(realm->_realm->get_privileges([object UTF8String])); - } - if (auto obj = RLMDynamicCast(object)) { - RLMVerifyAttached(obj); - return static_cast(realm->_realm->get_privileges(obj->_row)); - } - return 0; -} - -#pragma mark - C++ APIs - -SyncSessionStopPolicy translateStopPolicy(RLMSyncStopPolicy stopPolicy) { - switch (stopPolicy) { - case RLMSyncStopPolicyImmediately: return SyncSessionStopPolicy::Immediately; - case RLMSyncStopPolicyLiveIndefinitely: return SyncSessionStopPolicy::LiveIndefinitely; - case RLMSyncStopPolicyAfterChangesUploaded: return SyncSessionStopPolicy::AfterChangesUploaded; - } - REALM_UNREACHABLE(); // Unrecognized stop policy. -} - -RLMSyncStopPolicy translateStopPolicy(SyncSessionStopPolicy stop_policy) { - switch (stop_policy) { - case SyncSessionStopPolicy::Immediately: return RLMSyncStopPolicyImmediately; - case SyncSessionStopPolicy::LiveIndefinitely: return RLMSyncStopPolicyLiveIndefinitely; - case SyncSessionStopPolicy::AfterChangesUploaded: return RLMSyncStopPolicyAfterChangesUploaded; - } - REALM_UNREACHABLE(); -} - -std::shared_ptr sync_session_for_realm(RLMRealm *realm) { - Realm::Config realmConfig = realm.configuration.config; - if (auto config = realmConfig.sync_config) { - std::shared_ptr user = config->user; - if (user && user->state() != SyncUser::State::Error) { - return user->session_for_on_disk_path(realmConfig.path); - } - } - return nullptr; -} - -CocoaSyncUserContext& context_for(const std::shared_ptr& user) -{ - return *std::static_pointer_cast(user->binding_context()); -} - -NSError *make_auth_error_bad_response(NSDictionary *json) { - return [NSError errorWithDomain:RLMSyncAuthErrorDomain - code:RLMSyncAuthErrorBadResponse - userInfo:json ? @{kRLMSyncErrorJSONKey: json} : nil]; -} - -NSError *make_auth_error_http_status(NSInteger status) { - return [NSError errorWithDomain:RLMSyncAuthErrorDomain - code:RLMSyncAuthErrorHTTPStatusCodeError - userInfo:@{kRLMSyncErrorStatusCodeKey: @(status)}]; -} - -NSError *make_auth_error_client_issue() { - return [NSError errorWithDomain:RLMSyncAuthErrorDomain - code:RLMSyncAuthErrorClientSessionError - userInfo:nil]; -} - -NSError *make_auth_error(RLMSyncErrorResponseModel *model) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:2]; - if (NSString *description = model.title) { - [userInfo setObject:description forKey:NSLocalizedDescriptionKey]; - } - if (NSString *hint = model.hint) { - [userInfo setObject:hint forKey:NSLocalizedRecoverySuggestionErrorKey]; - } - return [NSError errorWithDomain:RLMSyncAuthErrorDomain code:model.code userInfo:userInfo]; -} - -NSError *make_sync_error(RLMSyncSystemErrorKind kind, NSString *description, NSInteger code, NSDictionary *custom) { - NSMutableDictionary *buffer = [custom ?: @{} mutableCopy]; - buffer[NSLocalizedDescriptionKey] = description; - if (code != NSNotFound) { - buffer[kRLMSyncErrorStatusCodeKey] = @(code); - } - - RLMSyncError errorCode; - switch (kind) { - case RLMSyncSystemErrorKindClientReset: - errorCode = RLMSyncErrorClientResetError; - break; - case RLMSyncSystemErrorKindPermissionDenied: - errorCode = RLMSyncErrorPermissionDeniedError; - break; - case RLMSyncSystemErrorKindUser: - errorCode = RLMSyncErrorClientUserError; - break; - case RLMSyncSystemErrorKindSession: - errorCode = RLMSyncErrorClientSessionError; - break; - case RLMSyncSystemErrorKindConnection: - case RLMSyncSystemErrorKindClient: - case RLMSyncSystemErrorKindUnknown: - errorCode = RLMSyncErrorClientInternalError; - break; - } - return [NSError errorWithDomain:RLMSyncErrorDomain - code:errorCode - userInfo:[buffer copy]]; -} - -NSError *make_sync_error(NSError *wrapped_auth_error) { - return [NSError errorWithDomain:RLMSyncErrorDomain - code:RLMSyncErrorUnderlyingAuthError - userInfo:@{kRLMSyncUnderlyingErrorKey: wrapped_auth_error}]; -} - -NSError *make_sync_error(std::error_code sync_error, RLMSyncSystemErrorKind kind) { - return [NSError errorWithDomain:RLMSyncErrorDomain - code:kind - userInfo:@{ - NSLocalizedDescriptionKey: @(sync_error.message().c_str()), - kRLMSyncErrorStatusCodeKey: @(sync_error.value()) - }]; -} diff --git a/Lesson14/Pods/Realm/Realm/RLMThreadSafeReference.mm b/Lesson14/Pods/Realm/Realm/RLMThreadSafeReference.mm deleted file mode 100644 index 7149fa4..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMThreadSafeReference.mm +++ /dev/null @@ -1,79 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMThreadSafeReference_Private.hpp" -#import "RLMUtil.hpp" - -template -static auto translateErrors(Function&& f) { - try { - return f(); - } - catch (std::exception const& e) { - @throw RLMException(e); - } -} - -@implementation RLMThreadSafeReference { - std::unique_ptr _reference; - id _metadata; - Class _type; -} - -- (instancetype)initWithThreadConfined:(id)threadConfined { - if (!(self = [super init])) { - return nil; - } - - REALM_ASSERT_DEBUG([threadConfined conformsToProtocol:@protocol(RLMThreadConfined)]); - if (![threadConfined conformsToProtocol:@protocol(RLMThreadConfined_Private)]) { - @throw RLMException(@"Illegal custom conformance to `RLMThreadConfined` by `%@`", threadConfined.class); - } else if (threadConfined.invalidated) { - @throw RLMException(@"Cannot construct reference to invalidated object"); - } else if (!threadConfined.realm) { - @throw RLMException(@"Cannot construct reference to unmanaged object, " - "which can be passed across threads directly"); - } - - translateErrors([&] { - _reference = [(id)threadConfined makeThreadSafeReference]; - _metadata = ((id)threadConfined).objectiveCMetadata; - }); - _type = threadConfined.class; - - return self; -} - -+ (instancetype)referenceWithThreadConfined:(id)threadConfined { - return [[self alloc] initWithThreadConfined:threadConfined]; -} - -- (id)resolveReferenceInRealm:(RLMRealm *)realm { - if (!_reference) { - @throw RLMException(@"Can only resolve a thread safe reference once."); - } - return translateErrors([&] { - return [_type objectWithThreadSafeReference:std::move(_reference) metadata:_metadata realm:realm]; - }); -} - -- (BOOL)isInvalidated { - return !_reference; -} - -@end diff --git a/Lesson14/Pods/Realm/Realm/RLMUpdateChecker.mm b/Lesson14/Pods/Realm/Realm/RLMUpdateChecker.mm deleted file mode 100644 index 4ff0dd6..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMUpdateChecker.mm +++ /dev/null @@ -1,60 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMUpdateChecker.hpp" - -#import "RLMRealm.h" -#import "RLMUtil.hpp" - -#if TARGET_IPHONE_SIMULATOR && !defined(REALM_COCOA_VERSION) -#import "RLMVersion.h" -#endif - -void RLMCheckForUpdates() { -#if TARGET_IPHONE_SIMULATOR - if (getenv("REALM_DISABLE_UPDATE_CHECKER") || RLMIsRunningInPlayground()) { - return; - } - - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"alpha|beta|rc" - options:(NSRegularExpressionOptions)0 - error:nil]; - NSUInteger numberOfMatches = [regex numberOfMatchesInString:REALM_COCOA_VERSION - options:(NSMatchingOptions)0 - range:NSMakeRange(0, REALM_COCOA_VERSION.length)]; - - if (numberOfMatches > 0) { - // pre-release version, skip update checking - return; - } - - auto handler = ^(NSData *data, NSURLResponse *response, NSError *error) { - if (error || ((NSHTTPURLResponse *)response).statusCode != 200) { - return; - } - - NSString *latestVersion = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (![REALM_COCOA_VERSION isEqualToString:latestVersion]) { - NSLog(@"Version %@ of Realm is now available: https://github.com/realm/realm-cocoa/blob/v%@/CHANGELOG.md", latestVersion, latestVersion); - } - }; - - NSString *url = [NSString stringWithFormat:@"https://static.realm.io/update/cocoa?%@", REALM_COCOA_VERSION]; - [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:url] completionHandler:handler] resume]; -#endif -} diff --git a/Lesson14/Pods/Realm/Realm/RLMUtil.mm b/Lesson14/Pods/Realm/Realm/RLMUtil.mm deleted file mode 100644 index 59b9829..0000000 --- a/Lesson14/Pods/Realm/Realm/RLMUtil.mm +++ /dev/null @@ -1,457 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMUtil.hpp" - -#import "RLMArray_Private.hpp" -#import "RLMListBase.h" -#import "RLMObjectSchema_Private.hpp" -#import "RLMObjectStore.h" -#import "RLMObject_Private.hpp" -#import "RLMProperty_Private.h" -#import "RLMSchema_Private.h" -#import "RLMSwiftSupport.h" - -#import "shared_realm.hpp" - -#if REALM_ENABLE_SYNC -#import "RLMSyncUtil.h" -#endif - -#import -#import - -#include -#include - -#if !defined(REALM_COCOA_VERSION) -#import "RLMVersion.h" -#endif - -static inline bool numberIsInteger(__unsafe_unretained NSNumber *const obj) { - char data_type = [obj objCType][0]; - return data_type == *@encode(bool) || - data_type == *@encode(char) || - data_type == *@encode(short) || - data_type == *@encode(int) || - data_type == *@encode(long) || - data_type == *@encode(long long) || - data_type == *@encode(unsigned short) || - data_type == *@encode(unsigned int) || - data_type == *@encode(unsigned long) || - data_type == *@encode(unsigned long long); -} - -static inline bool numberIsBool(__unsafe_unretained NSNumber *const obj) { - // @encode(BOOL) is 'B' on iOS 64 and 'c' - // objcType is always 'c'. Therefore compare to "c". - if ([obj objCType][0] == 'c') { - return true; - } - - if (numberIsInteger(obj)) { - int value = [obj intValue]; - return value == 0 || value == 1; - } - - return false; -} - -static inline bool numberIsFloat(__unsafe_unretained NSNumber *const obj) { - char data_type = [obj objCType][0]; - return data_type == *@encode(float) || - data_type == *@encode(short) || - data_type == *@encode(int) || - data_type == *@encode(long) || - data_type == *@encode(long long) || - data_type == *@encode(unsigned short) || - data_type == *@encode(unsigned int) || - data_type == *@encode(unsigned long) || - data_type == *@encode(unsigned long long) || - // A double is like float if it fits within float bounds or is NaN. - (data_type == *@encode(double) && (ABS([obj doubleValue]) <= FLT_MAX || isnan([obj doubleValue]))); -} - -static inline bool numberIsDouble(__unsafe_unretained NSNumber *const obj) { - char data_type = [obj objCType][0]; - return data_type == *@encode(double) || - data_type == *@encode(float) || - data_type == *@encode(short) || - data_type == *@encode(int) || - data_type == *@encode(long) || - data_type == *@encode(long long) || - data_type == *@encode(unsigned short) || - data_type == *@encode(unsigned int) || - data_type == *@encode(unsigned long) || - data_type == *@encode(unsigned long long); -} - -static inline RLMArray *asRLMArray(__unsafe_unretained id const value) { - return RLMDynamicCast(value) ?: RLMDynamicCast(value)._rlmArray; -} - -static inline bool checkArrayType(__unsafe_unretained RLMArray *const array, - RLMPropertyType type, bool optional, - __unsafe_unretained NSString *const objectClassName) { - return array.type == type && array.optional == optional - && (type != RLMPropertyTypeObject || [array.objectClassName isEqualToString:objectClassName]); -} - -id (*RLMSwiftAsFastEnumeration)(id); -id RLMAsFastEnumeration(__unsafe_unretained id obj) { - if (!obj) { - return nil; - } - if ([obj conformsToProtocol:@protocol(NSFastEnumeration)]) { - return obj; - } - if (RLMSwiftAsFastEnumeration) { - return RLMSwiftAsFastEnumeration(obj); - } - return nil; -} - -BOOL RLMValidateValue(__unsafe_unretained id const value, - RLMPropertyType type, bool optional, bool array, - __unsafe_unretained NSString *const objectClassName) { - if (optional && !RLMCoerceToNil(value)) { - return YES; - } - if (array) { - if (auto rlmArray = asRLMArray(value)) { - return checkArrayType(rlmArray, type, optional, objectClassName); - } - if (id enumeration = RLMAsFastEnumeration(value)) { - // check each element for compliance - for (id el in enumeration) { - if (!RLMValidateValue(el, type, optional, false, objectClassName)) { - return NO; - } - } - return YES; - } - if (!value || value == NSNull.null) { - return YES; - } - return NO; - } - - switch (type) { - case RLMPropertyTypeString: - return [value isKindOfClass:[NSString class]]; - case RLMPropertyTypeBool: - if ([value isKindOfClass:[NSNumber class]]) { - return numberIsBool(value); - } - return NO; - case RLMPropertyTypeDate: - return [value isKindOfClass:[NSDate class]]; - case RLMPropertyTypeInt: - if (NSNumber *number = RLMDynamicCast(value)) { - return numberIsInteger(number); - } - return NO; - case RLMPropertyTypeFloat: - if (NSNumber *number = RLMDynamicCast(value)) { - return numberIsFloat(number); - } - return NO; - case RLMPropertyTypeDouble: - if (NSNumber *number = RLMDynamicCast(value)) { - return numberIsDouble(number); - } - return NO; - case RLMPropertyTypeData: - return [value isKindOfClass:[NSData class]]; - case RLMPropertyTypeAny: - return NO; - case RLMPropertyTypeLinkingObjects: - return YES; - case RLMPropertyTypeObject: { - // only NSNull, nil, or objects which derive from RLMObject and match the given - // object class are valid - RLMObjectBase *objBase = RLMDynamicCast(value); - return objBase && [objBase->_objectSchema.className isEqualToString:objectClassName]; - } - } - @throw RLMException(@"Invalid RLMPropertyType specified"); -} - -void RLMThrowTypeError(__unsafe_unretained id const obj, - __unsafe_unretained RLMObjectSchema *const objectSchema, - __unsafe_unretained RLMProperty *const prop) { - @throw RLMException(@"Invalid value '%@' of type '%@' for '%@%s'%s property '%@.%@'.", - obj, [obj class], - prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", - prop.array ? " array" : "", objectSchema.className, prop.name); -} - -void RLMValidateValueForProperty(__unsafe_unretained id const obj, - __unsafe_unretained RLMObjectSchema *const objectSchema, - __unsafe_unretained RLMProperty *const prop, - bool validateObjects) { - // This duplicates a lot of the checks in RLMIsObjectValidForProperty() - // for the sake of more specific error messages - if (prop.array) { - // nil is considered equivalent to an empty array for historical reasons - // since we don't support null arrays (only arrays containing null), - // it's not worth the BC break to change this - if (!obj || obj == NSNull.null) { - return; - } - id enumeration = RLMAsFastEnumeration(obj); - if (!enumeration) { - @throw RLMException(@"Invalid value (%@) for '%@%s' array property '%@.%@': value is not enumerable.", - obj, prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", - objectSchema.className, prop.name); - } - if (!validateObjects && prop.type == RLMPropertyTypeObject) { - return; - } - - if (RLMArray *array = asRLMArray(obj)) { - if (!checkArrayType(array, prop.type, prop.optional, prop.objectClassName)) { - @throw RLMException(@"RLMArray<%@%s> does not match expected type '%@%s' for property '%@.%@'.", - array.objectClassName ?: RLMTypeToString(array.type), array.optional ? "?" : "", - prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "", - objectSchema.className, prop.name); - } - return; - } - - for (id value in enumeration) { - if (!RLMValidateValue(value, prop.type, prop.optional, false, prop.objectClassName)) { - RLMThrowTypeError(value, objectSchema, prop); - } - } - return; - } - - // For create() we want to skip the validation logic for objects because - // we allow much fuzzier matching (any KVC-compatible object with at least - // all the non-defaulted fields), and all the logic for that lives in the - // object store rather than here - if (prop.type == RLMPropertyTypeObject && !validateObjects) { - return; - } - if (RLMIsObjectValidForProperty(obj, prop)) { - return; - } - - RLMThrowTypeError(obj, objectSchema, prop); -} - -BOOL RLMIsObjectValidForProperty(__unsafe_unretained id const obj, - __unsafe_unretained RLMProperty *const property) { - return RLMValidateValue(obj, property.type, property.optional, property.array, property.objectClassName); -} - -NSDictionary *RLMDefaultValuesForObjectSchema(__unsafe_unretained RLMObjectSchema *const objectSchema) { - if (!objectSchema.isSwiftClass) { - return [objectSchema.objectClass defaultPropertyValues]; - } - - NSMutableDictionary *defaults = nil; - if ([objectSchema.objectClass isSubclassOfClass:RLMObject.class]) { - defaults = [NSMutableDictionary dictionaryWithDictionary:[objectSchema.objectClass defaultPropertyValues]]; - } - else { - defaults = [NSMutableDictionary dictionary]; - } - RLMObject *defaultObject = [[objectSchema.objectClass alloc] init]; - for (RLMProperty *prop in objectSchema.properties) { - if (!defaults[prop.name] && defaultObject[prop.name]) { - defaults[prop.name] = defaultObject[prop.name]; - } - } - return defaults; -} - -static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) { - NSMutableDictionary *userInfo = @{RLMRealmVersionKey: REALM_COCOA_VERSION, - RLMRealmCoreVersionKey: @REALM_VERSION}.mutableCopy; - if (additionalUserInfo != nil) { - [userInfo addEntriesFromDictionary:additionalUserInfo]; - } - NSException *e = [NSException exceptionWithName:RLMExceptionName - reason:reason - userInfo:userInfo]; - return e; -} - -NSException *RLMException(NSString *fmt, ...) { - va_list args; - va_start(args, fmt); - NSException *e = RLMException([[NSString alloc] initWithFormat:fmt arguments:args], @{}); - va_end(args); - return e; -} - -NSException *RLMException(std::exception const& exception) { - return RLMException(@"%s", exception.what()); -} - -NSError *RLMMakeError(RLMError code, std::exception const& exception) { - return [NSError errorWithDomain:RLMErrorDomain - code:code - userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), - @"Error Code": @(code)}]; -} - -NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError& exception) { - return [NSError errorWithDomain:RLMErrorDomain - code:code - userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), - NSFilePathErrorKey: @(exception.get_path().c_str()), - @"Error Code": @(code)}]; -} - -NSError *RLMMakeError(RLMError code, const realm::RealmFileException& exception) { - NSString *underlying = @(exception.underlying().c_str()); - return [NSError errorWithDomain:RLMErrorDomain - code:code - userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), - NSFilePathErrorKey: @(exception.path().c_str()), - @"Error Code": @(code), - @"Underlying": underlying.length == 0 ? @"n/a" : underlying}]; -} - -NSError *RLMMakeError(std::system_error const& exception) { - int code = exception.code().value(); - BOOL isGenericCategoryError = (exception.code().category() == std::generic_category()); - NSString *category = @(exception.code().category().name()); - NSString *errorDomain = isGenericCategoryError ? NSPOSIXErrorDomain : RLMUnknownSystemErrorDomain; -#if REALM_ENABLE_SYNC - if (exception.code().category() == realm::sync::client_error_category()) { - if (exception.code().value() == static_cast(realm::sync::Client::Error::connect_timeout)) { - errorDomain = NSPOSIXErrorDomain; - code = ETIMEDOUT; - } - else { - errorDomain = RLMSyncErrorDomain; - } - } -#endif - - return [NSError errorWithDomain:errorDomain code:code - userInfo:@{NSLocalizedDescriptionKey: @(exception.what()), - @"Error Code": @(exception.code().value()), - @"Category": category}]; -} - -void RLMSetErrorOrThrow(NSError *error, NSError **outError) { - if (outError) { - *outError = error; - } - else { - NSString *msg = error.localizedDescription; - if (error.userInfo[NSFilePathErrorKey]) { - msg = [NSString stringWithFormat:@"%@: %@", error.userInfo[NSFilePathErrorKey], error.localizedDescription]; - } - @throw RLMException(msg, @{NSUnderlyingErrorKey: error}); - } -} - -BOOL RLMIsDebuggerAttached() -{ - int name[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID, - getpid() - }; - - struct kinfo_proc info; - size_t info_size = sizeof(info); - if (sysctl(name, sizeof(name)/sizeof(name[0]), &info, &info_size, NULL, 0) == -1) { - NSLog(@"sysctl() failed: %s", strerror(errno)); - return false; - } - - return (info.kp_proc.p_flag & P_TRACED) != 0; -} - -BOOL RLMIsRunningInPlayground() { - return [[NSBundle mainBundle].bundleIdentifier hasPrefix:@"com.apple.dt.playground."]; -} - -id RLMMixedToObjc(realm::Mixed const& mixed) { - switch (mixed.get_type()) { - case realm::type_String: - return RLMStringDataToNSString(mixed.get_string()); - case realm::type_Int: - return @(mixed.get_int()); - case realm::type_Float: - return @(mixed.get_float()); - case realm::type_Double: - return @(mixed.get_double()); - case realm::type_Bool: - return @(mixed.get_bool()); - case realm::type_Timestamp: - return RLMTimestampToNSDate(mixed.get_timestamp()); - case realm::type_Binary: - return RLMBinaryDataToNSData(mixed.get_binary()); - case realm::type_Link: - case realm::type_LinkList: - default: - @throw RLMException(@"Invalid data type for RLMPropertyTypeAny property."); - } -} - -NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier) { -#if TARGET_OS_TV - (void)bundleIdentifier; - // tvOS prohibits writing to the Documents directory, so we use the Library/Caches directory instead. - return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; -#elif TARGET_OS_IPHONE && !TARGET_OS_MACCATALYST - (void)bundleIdentifier; - // On iOS the Documents directory isn't user-visible, so put files there - return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; -#else - // On OS X it is, so put files in Application Support. If we aren't running - // in a sandbox, put it in a subdirectory based on the bundle identifier - // to avoid accidentally sharing files between applications - NSString *path = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0]; - if (![[NSProcessInfo processInfo] environment][@"APP_SANDBOX_CONTAINER_ID"]) { - if (!bundleIdentifier) { - bundleIdentifier = [NSBundle mainBundle].bundleIdentifier; - } - if (!bundleIdentifier) { - bundleIdentifier = [NSBundle mainBundle].executablePath.lastPathComponent; - } - - path = [path stringByAppendingPathComponent:bundleIdentifier]; - - // create directory - [[NSFileManager defaultManager] createDirectoryAtPath:path - withIntermediateDirectories:YES - attributes:nil - error:nil]; - } - return path; -#endif -} - -NSDateFormatter *RLMISO8601Formatter() { - // note: NSISO8601DateFormatter can't be used as it doesn't support milliseconds - NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; - dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; - dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - dateFormatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; - return dateFormatter; -} diff --git a/Lesson14/Pods/Realm/Realm/Realm.modulemap b/Lesson14/Pods/Realm/Realm/Realm.modulemap deleted file mode 100644 index 42845f6..0000000 --- a/Lesson14/Pods/Realm/Realm/Realm.modulemap +++ /dev/null @@ -1,31 +0,0 @@ -framework module Realm { - umbrella header "Realm.h" - - export * - module * { export * } - - explicit module Private { - header "RLMAccessor.h" - header "RLMArray_Private.h" - header "RLMCollection_Private.h" - header "RLMListBase.h" - header "RLMObject_Private.h" - header "RLMObjectBase_Dynamic.h" - header "RLMObjectBase_Private.h" - header "RLMObjectSchema_Private.h" - header "RLMObjectStore.h" - header "RLMOptionalBase.h" - header "RLMProperty_Private.h" - header "RLMRealm_Private.h" - header "RLMRealmConfiguration_Private.h" - header "RLMResults_Private.h" - header "RLMSchema_Private.h" - header "RLMSyncConfiguration_Private.h" - header "RLMSyncUtil_Private.h" - } - - explicit module Dynamic { - header "RLMRealm_Dynamic.h" - header "RLMObjectBase_Dynamic.h" - } -} diff --git a/Lesson14/Pods/Realm/build.sh b/Lesson14/Pods/Realm/build.sh deleted file mode 100755 index c3bb27a..0000000 --- a/Lesson14/Pods/Realm/build.sh +++ /dev/null @@ -1,1571 +0,0 @@ -#!/bin/bash - -################################################################################## -# Custom build tool for Realm Objective-C binding. -# -# (C) Copyright 2011-2015 by realm.io. -################################################################################## - -# Warning: pipefail is not a POSIX compatible option, but on macOS it works just fine. -# macOS uses a POSIX complain version of bash as /bin/sh, but apparently it does -# not strip away this feature. Also, this will fail if somebody forces the script -# to be run with zsh. -set -o pipefail -set -e - -source_root="$(dirname "$0")" - -# You can override the version of the core library -: ${REALM_BASE_URL:="https://static.realm.io/downloads"} # set it if you need to use a remote repo - -: ${REALM_CORE_VERSION:=$(sed -n 's/^REALM_CORE_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} # set to "current" to always use the current build - -: ${REALM_SYNC_VERSION:=$(sed -n 's/^REALM_SYNC_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} - -: ${REALM_OBJECT_SERVER_VERSION:=$(sed -n 's/^REALM_OBJECT_SERVER_VERSION=\(.*\)$/\1/p' ${source_root}/dependencies.list)} - -# You can override the xcmode used -: ${XCMODE:=xcodebuild} # must be one of: xcodebuild (default), xcpretty, xctool - -# Provide a fallback value for TMPDIR, relevant for Xcode Bots -: ${TMPDIR:=$(getconf DARWIN_USER_TEMP_DIR)} - -PATH=/usr/libexec:$PATH - -if ! [ -z "${JENKINS_HOME}" ]; then - XCPRETTY_PARAMS="--no-utf --report junit --output build/reports/junit.xml" - CODESIGN_PARAMS="CODE_SIGN_IDENTITY= CODE_SIGNING_REQUIRED=NO" -fi - -usage() { -cat < /dev/null -} - -###################################### -# Device Test Helper -###################################### - -test_devices() { - local serial_numbers=() - local awk_script=" - /^ +Vendor ID: / { is_apple = 0; } - /^ +Vendor ID: 0x05[aA][cC] / { is_apple = 1; } - /^ +Serial Number: / { - if (is_apple) { - match(\$0, /^ +Serial Number: /); - print substr(\$0, RLENGTH + 1); - } - } - " - local serial_numbers_text=$(/usr/sbin/system_profiler SPUSBDataType | /usr/bin/awk "$awk_script") - while read -r number; do - if [[ "$number" != "" ]]; then - serial_numbers+=("$number") - fi - done <<< "$serial_numbers_text" - if [[ ${#serial_numbers[@]} == 0 ]]; then - echo "At least one iOS/tvOS device must be connected to this computer to run device tests" - if [ -z "${JENKINS_HOME}" ]; then - # Don't fail if running locally and there's no device - exit 0 - fi - exit 1 - fi - local sdk="$1" - local scheme="$2" - local configuration="$3" - local failed=0 - for device in "${serial_numbers[@]}"; do - xc "-scheme '$scheme' -configuration $configuration -destination 'id=$device' -sdk $sdk test" || failed=1 - done - return $failed -} - -###################################### -# Docs -###################################### - -build_docs() { - local language="$1" - local version=$(sh build.sh get-version) - - local xcodebuild_arguments="--objc,Realm/Realm.h,--,-x,objective-c,-isysroot,$(xcrun --show-sdk-path),-I,$(pwd)" - local module="Realm" - local objc="--objc" - - if [[ "$language" == "swift" ]]; then - sh build.sh set-swift-version - xcodebuild_arguments="-scheme,RealmSwift" - module="RealmSwift" - objc="" - fi - - touch Realm/RLMPlatform.h # jazzy will fail if it can't find all public header files - jazzy \ - ${objc} \ - --clean \ - --author Realm \ - --author_url https://realm.io \ - --github_url https://github.com/realm/realm-cocoa \ - --github-file-prefix https://github.com/realm/realm-cocoa/tree/v${version} \ - --module-version ${version} \ - --xcodebuild-arguments ${xcodebuild_arguments} \ - --module ${module} \ - --root-url https://realm.io/docs/${language}/${version}/api/ \ - --output docs/${language}_output \ - --head "$(cat docs/custom_head.html)" - - rm Realm/RLMPlatform.h -} - -###################################### -# Input Validation -###################################### - -if [ "$#" -eq 0 -o "$#" -gt 3 ]; then - usage - exit 1 -fi - -###################################### -# Downloading -###################################### - -download_common() { - local download_type=$1 tries_left=3 version url error temp_dir temp_path tar_path - - if [ "$download_type" == "core" ]; then - version=$REALM_CORE_VERSION - url="${REALM_BASE_URL}/core/realm-core-${version}.tar.xz" - elif [ "$download_type" == "sync" ]; then - version=$REALM_SYNC_VERSION - url="${REALM_BASE_URL}/sync/realm-sync-cocoa-${version}.tar.xz" - else - echo "Unknown dowload_type: $download_type" - exit 1 - fi - - echo "Downloading dependency: ${download_type} ${version} from ${url}" - - if [ -z "$TMPDIR" ]; then - TMPDIR='/tmp' - fi - temp_dir=$(dirname "$TMPDIR/waste")/${download_type}_bin - mkdir -p "$temp_dir" - tar_path="${temp_dir}/${download_type}-${version}.tar.xz" - temp_path="${tar_path}.tmp" - - while [ 0 -lt $tries_left ] && [ ! -f "$tar_path" ]; do - if ! error=$(/usr/bin/curl --fail --silent --show-error --location "$url" --output "$temp_path" 2>&1); then - tries_left=$[$tries_left-1] - else - mv "$temp_path" "$tar_path" - fi - done - - if [ ! -f "$tar_path" ]; then - printf "Downloading ${download_type} failed:\n\t$url\n\t$error\n" - exit 1 - fi - - ( - cd "$temp_dir" - rm -rf "$download_type" - tar xf "$tar_path" --xz - mv core "${download_type}-${version}" - ) - - rm -rf "${download_type}-${version}" core - mv "${temp_dir}/${download_type}-${version}" . - ln -s "${download_type}-${version}" core -} - -download_core() { - download_common "core" -} - -download_sync() { - download_common "sync" -} - -###################################### -# Variables -###################################### - -COMMAND="$1" - -# Use Debug config if command ends with -debug, otherwise default to Release -case "$COMMAND" in - *-debug) - COMMAND="${COMMAND%-debug}" - CONFIGURATION="Debug" - ;; -esac -export CONFIGURATION=${CONFIGURATION:-Release} - -# Pre-choose Xcode and Swift versions for those operations that do not set them -REALM_XCODE_VERSION=${xcode_version:-$REALM_XCODE_VERSION} -REALM_SWIFT_VERSION=${swift_version:-$REALM_SWIFT_VERSION} -source "${source_root}/scripts/swift-version.sh" -set_xcode_and_swift_versions - -###################################### -# Commands -###################################### - -case "$COMMAND" in - - ###################################### - # Clean - ###################################### - "clean") - find . -type d -name build -exec rm -r "{}" + - exit 0 - ;; - - ###################################### - # Core - ###################################### - "download-core") - if [ "$REALM_CORE_VERSION" = "current" ]; then - echo "Using version of core already in core/ directory" - exit 0 - fi - if [ -d core -a -d ../realm-core -a ! -L core ]; then - # Allow newer versions than expected for local builds as testing - # with unreleased versions is one of the reasons to use a local build - if ! $(grep -i "${REALM_CORE_VERSION} Release notes" core/release_notes.txt >/dev/null); then - echo "Local build of core is out of date." - exit 1 - else - echo "The core library seems to be up to date." - fi - elif ! [ -L core ]; then - echo "core is not a symlink. Deleting..." - rm -rf core - download_core - # With a prebuilt version we only want to check the first non-empty - # line so that checking out an older commit will download the - # appropriate version of core if the already-present version is too new - elif ! $(grep -m 1 . core/release_notes.txt | grep -i "${REALM_CORE_VERSION} RELEASE NOTES" >/dev/null); then - download_core - else - echo "The core library seems to be up to date." - fi - exit 0 - ;; - - ###################################### - # Sync - ###################################### - "download-sync") - if [ "$REALM_SYNC_VERSION" = "current" ]; then - echo "Using version of core already in core/ directory" - exit 0 - fi - if [ -d core -a -d ../realm-core -a -d ../realm-sync -a ! -L core ]; then - echo "Using version of core already in core/ directory" - elif ! [ -L core ]; then - echo "core is not a symlink. Deleting..." - rm -rf core - download_sync - elif [[ "$(cat core/version.txt)" != "$REALM_SYNC_VERSION" ]]; then - download_sync - else - echo "The core library seems to be up to date." - fi - exit 0 - ;; - - ###################################### - # Swift versioning - ###################################### - "set-swift-version") - version=${2:-$REALM_SWIFT_VERSION} - - SWIFT_VERSION_FILE="RealmSwift/SwiftVersion.swift" - CONTENTS="let swiftLanguageVersion = \"$version\"" - if [ ! -f "$SWIFT_VERSION_FILE" ] || ! grep -q "$CONTENTS" "$SWIFT_VERSION_FILE"; then - echo "$CONTENTS" > "$SWIFT_VERSION_FILE" - fi - - exit 0 - ;; - - "prelaunch-simulator") - sh ${source_root}/scripts/reset-simulators.sh - ;; - - ###################################### - # Building - ###################################### - "build") - sh build.sh ios-static - sh build.sh ios-dynamic - sh build.sh ios-swift - sh build.sh watchos - sh build.sh watchos-swift - sh build.sh tvos - sh build.sh tvos-swift - sh build.sh osx - sh build.sh osx-swift - exit 0 - ;; - - "ios-static") - build_combined 'Realm iOS static' Realm iphoneos iphonesimulator "-static" - exit 0 - ;; - - "ios-dynamic") - build_combined Realm Realm iphoneos iphonesimulator - exit 0 - ;; - - "ios-swift") - sh build.sh ios-dynamic - build_combined RealmSwift RealmSwift iphoneos iphonesimulator '' "/swift-$REALM_XCODE_VERSION" - copy_realm_framework ios - exit 0 - ;; - - "watchos") - build_combined Realm Realm watchos watchsimulator - exit 0 - ;; - - "watchos-swift") - sh build.sh watchos - build_combined RealmSwift RealmSwift watchos watchsimulator '' "/swift-$REALM_XCODE_VERSION" - copy_realm_framework watchos - exit 0 - ;; - - "tvos") - build_combined Realm Realm appletvos appletvsimulator - exit 0 - ;; - - "tvos-swift") - sh build.sh tvos - build_combined RealmSwift RealmSwift appletvos appletvsimulator '' "/swift-$REALM_XCODE_VERSION" - copy_realm_framework tvos - exit 0 - ;; - - "osx") - xc "-scheme Realm -configuration $CONFIGURATION" - clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/Realm.framework" "build/osx" "Realm.framework" - exit 0 - ;; - - "osx-swift") - sh build.sh osx - xc "-scheme 'RealmSwift' -configuration $CONFIGURATION build" - destination="build/osx/swift-$REALM_XCODE_VERSION" - clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/RealmSwift.framework" "$destination" "RealmSwift.framework" - rm -rf "$destination/Realm.framework" - cp -R build/osx/Realm.framework "$destination" - exit 0 - ;; - - "catalyst") - if (( $(xcode_version_major) < 11 )); then - echo 'Building for Catalyst requires Xcode 11' - exit 1 - fi - - xc "-scheme Realm -configuration $CONFIGURATION \ - REALM_CATALYST_FLAGS='-target x86_64-apple-ios13.0-macabi' \ - REALM_PLATFORM_SUFFIX='maccatalyst' \ - IS_MACCATALYST=YES" - clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/Realm.framework" "build/catalyst" "Realm.framework" - ;; - - "catalyst-swift") - if (( $(xcode_version_major) < 11 )); then - echo 'Building for Catalyst requires Xcode 11' - exit 1 - fi - - sh build.sh catalyst - # FIXME: change this to just "-destination variant='Mac Catalyst'" once the CI machines are running 10.15 - xc "-scheme 'RealmSwift' -configuration $CONFIGURATION build \ - REALM_CATALYST_FLAGS='-target x86_64-apple-ios13.0-macabi' \ - REALM_PLATFORM_SUFFIX='maccatalyst' \ - SWIFT_DEPLOYMENT_TARGET='13.0-macabi' \ - SWIFT_PLATFORM_TARGET_PREFIX='ios' \ - IS_MACCATALYST=YES" - destination="build/catalyst/swift-$REALM_XCODE_VERSION" - clean_retrieve "build/DerivedData/Realm/Build/Products/$CONFIGURATION/RealmSwift.framework" "$destination" "RealmSwift.framework" - rm -rf "$destination/Realm.framework" - cp -R build/catalyst/Realm.framework "$destination" - ;; - - "xcframework") - if (( $(xcode_version_major) < 11 )); then - echo 'Building a xcframework requires Xcode 11' - exit 1 - fi - - export REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS BUILD_LIBRARY_FOR_DISTRIBUTION=YES REALM_OBJC_MACH_O_TYPE=staticlib" - - # Build all of the requested frameworks - shift - PLATFORMS="${*:-osx ios watchos tvos catalyst}" - for platform in $PLATFORMS; do - sh build.sh $platform-swift - done - - # Assemble them into xcframeworks - rm -rf build/*.xcframework - find build/DerivedData/Realm/Build/Products -name 'Realm.framework' \ - | grep -v '\-static' \ - | sed 's/.*/-framework &/' \ - | xargs xcodebuild -create-xcframework -output build/Realm.xcframework - find build/DerivedData/Realm/Build/Products -name 'RealmSwift.framework' \ - | sed 's/.*/-framework &/' \ - | xargs xcodebuild -create-xcframework -output build/RealmSwift.xcframework - - # strip-frameworks.sh isn't needed with xcframeworks since we don't - # lipo together device/simulator libs - find build/Realm.xcframework -name 'strip-frameworks.sh' -delete - find build/RealmSwift.xcframework -name 'strip-frameworks.sh' -delete - - # swiftinterface files currently have incorrect name resolution which - # results in the RealmSwift.Realm class name clashing with the Realm - # module name. Work around this by renaming the Realm module to - # RealmObjc. This is safe to do with a pre-built library because the - # module name is unrelated to what symbols are exported by an obj-c - # library, and we're statically linking the obj-c library into the - # swift library so it doesn't need to be loaded at runtime. - cd build - cp -R Realm.xcframework RealmObjc.xcframework - find RealmObjc.xcframework -name 'Realm.framework' \ - -execdir mv {} RealmObjc.framework \; || true 2> /dev/null - find RealmObjc.xcframework -name '*.h' \ - -exec sed -i '' 's/Realm\//RealmObjc\//' {} \; - find RealmObjc.xcframework -name 'module.modulemap' \ - -exec sed -i '' 's/module Realm/module RealmObjc/' {} \; - sed -i '' 's/Realm.framework/RealmObjc.framework/' RealmObjc.xcframework/Info.plist - - find RealmSwift.xcframework -name '*.swiftinterface' \ - -exec sed -i '' 's/import Realm/import RealmObjc/' {} \; - find RealmSwift.xcframework -name '*.swiftinterface' \ - -exec sed -i '' 's/Realm.RLM/RealmObjc.RLM/g' {} \; - - # Realm is statically linked into RealmSwift so we no longer actually - # need the obj-c static library, and just need the framework shell. - # Remove everything but placeholder.o so that there's still a library - # to link against that just doesn't define any symbols. - find RealmObjc.xcframework -name 'Realm' | while read file; do - ( - cd $(dirname $file) - if readlink Realm > /dev/null; then - ln -sf Versions/Current/RealmObjc Realm - elif lipo -info Realm | grep -q 'Non-fat'; then - ar -t Realm | grep -v placeholder | tr '\n' '\0' | xargs -0 ar -d Realm >/dev/null 2>&1 - ranlib Realm >/dev/null 2>&1 - else - for arch in $(lipo -info Realm | cut -f3 -d':'); do - lipo Realm -thin $arch -output tmp.a - ar -t tmp.a | grep -v placeholder | tr '\n' '\0' | xargs -0 ar -d tmp.a >/dev/null 2>&1 - ranlib tmp.a >/dev/null 2>&1 - lipo Realm -replace $arch tmp.a -output Realm - rm tmp.a - done - fi - mv Realm RealmObjc - ) - done - - # We built Realm.framework as a static framework so that we could link - # it into RealmSwift.framework and not have to deal with the runtime - # implications of renaming the shared library, but we want the end - # result to be that Realm.xcframework is a dynamic framework. Our build - # system isn't really set up to build both static and dynamic versions - # of it, so instead just turn each of the static libraries in - # Realm.xcframework into a shared library. - cd Realm.xcframework - i=0 - while plist_get Info.plist "AvailableLibraries:$i" > /dev/null; do - arch_dir_name="$(plist_get Info.plist "AvailableLibraries:$i:LibraryIdentifier")" - platform="$(plist_get Info.plist "AvailableLibraries:$i:SupportedPlatform")" - variant="$(plist_get Info.plist "AvailableLibraries:$i:SupportedPlatformVariant" 2> /dev/null || echo 'os')" - deployment_target_name="$platform" - install_name='@rpath/Realm.framework/Realm' - bitcode_flag='-fembed-bitcode' - if [ "$variant" = 'simulator' ]; then - bitcode_flag='' - fi - case "$platform" in - "macos") sdk='macosx'; install_name='@rpath/Realm.framework/Versions/A/Realm'; bitcode_flag='';; - "ios") sdk="iphone$variant"; deployment_target_name='iphoneos';; - "watchos") sdk="watch$variant";; - "tvos") sdk="appletv$variant";; - esac - deployment_target=$(grep -i "$deployment_target_name.*_DEPLOYMENT_TARGET" ../../Configuration/Base.xcconfig \ - | sed 's/.*= \(.*\);/\1/') - architectures="" - j=0 - while plist_get Info.plist "AvailableLibraries:$i:SupportedArchitectures:$j" > /dev/null; do - architectures="${architectures} -arch $(plist_get Info.plist "AvailableLibraries:$i:SupportedArchitectures:$j")" - j=$(($j + 1)) - done - - ( - cd $arch_dir_name/Realm.framework - realm_lib=$(readlink Realm || echo 'Realm') - # feature_token.cpp.o depends on PKey, which isn't actually - # present in the macOS build of the sync library. This normally - # works fine because we never reference any symbols from - # feature_token.cpp.o so it doesn't get pulled in at all, but - # -all_load makes every object file in the input get linked - # into the shared library. - ar -d $realm_lib feature_token.cpp.o 2> /dev/null || true - clang++ -shared $architectures \ - -target ${platform}${deployment_target} \ - -isysroot $(xcrun --sdk ${sdk} --show-sdk-path) \ - -install_name "$install_name" \ - -compatibility_version 1 -current_version 1 \ - -fapplication-extension \ - $bitcode_flag \ - -Wl,-all_load \ - -Wl,-unexported_symbol,'__Z*' \ - -o realm.dylib \ - Realm -lz - mv realm.dylib $realm_lib - ) - - i=$(($i + 1)) - done - - exit 0 - ;; - - ###################################### - # Analysis - ###################################### - - "analyze-osx") - xc "-scheme Realm -configuration $CONFIGURATION analyze" - exit 0 - ;; - - ###################################### - # Testing - ###################################### - "test") - set +e # Run both sets of tests even if the first fails - failed=0 - sh build.sh test-ios-static || failed=1 - sh build.sh test-ios-dynamic || failed=1 - sh build.sh test-ios-swift || failed=1 - sh build.sh test-ios-devices || failed=1 - sh build.sh test-tvos-devices || failed=1 - sh build.sh test-osx || failed=1 - sh build.sh test-osx-swift || failed=1 - if (( $(xcode_version_major) >= 11 )); then - sh build.sh test-catalyst || failed=1 - sh build.sh test-catalyst-swift || failed=1 - fi - exit $failed - ;; - - "test-all") - set +e - failed=0 - sh build.sh test || failed=1 - sh build.sh test-debug || failed=1 - exit $failed - ;; - - "test-ios-static") - test_ios_static "name=iPhone 8" - exit 0 - ;; - - "test-ios-dynamic") - xc "-scheme Realm -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 8' build-for-testing" - xc "-scheme Realm -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 8' test" - exit 0 - ;; - - "test-ios-swift") - xc "-scheme RealmSwift -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 8' build-for-testing" - xc "-scheme RealmSwift -configuration $CONFIGURATION -sdk iphonesimulator -destination 'name=iPhone 8' test" - exit 0 - ;; - - "test-ios-devices") - failed=0 - trap "failed=1" ERR - sh build.sh test-ios-devices-objc - sh build.sh test-ios-devices-swift - exit $failed - ;; - - "test-ios-devices-objc") - test_devices iphoneos "Realm" "$CONFIGURATION" - exit $? - ;; - - "test-ios-devices-swift") - test_devices iphoneos "RealmSwift" "$CONFIGURATION" - exit $? - ;; - - "test-tvos") - destination="Apple TV" - xctest "-scheme Realm -configuration $CONFIGURATION -sdk appletvsimulator -destination 'name=$destination'" - exit $? - ;; - - "test-tvos-swift") - destination="Apple TV" - xctest "-scheme RealmSwift -configuration $CONFIGURATION -sdk appletvsimulator -destination 'name=$destination'" - exit $? - ;; - - "test-tvos-devices") - test_devices appletvos TestHost "$CONFIGURATION" - ;; - - "test-osx") - COVERAGE_PARAMS="" - if [[ "$CONFIGURATION" == "Debug" ]]; then - COVERAGE_PARAMS="GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES" - fi - xctest "-scheme Realm -configuration $CONFIGURATION $COVERAGE_PARAMS" - exit 0 - ;; - - "test-osx-swift") - xctest "-scheme RealmSwift -configuration $CONFIGURATION" - exit 0 - ;; - - "test-osx-object-server") - xctest "-scheme 'Object Server Tests' -configuration $CONFIGURATION -sdk macosx" - exit 0 - ;; - - test-swiftpm*) - SANITIZER=$(echo $COMMAND | cut -d - -f 3) - if [ -n "$SANITIZER" ]; then - SANITIZER="--sanitize $SANITIZER" - export ASAN_OPTIONS='check_initialization_order=true:detect_stack_use_after_return=true' - fi - xcrun swift test --configuration $(echo $CONFIGURATION | tr "[:upper:]" "[:lower:]") $SANITIZER - exit 0 - ;; - - "test-catalyst") - export REALM_SDKROOT=iphoneos - xc "-scheme Realm -configuration $CONFIGURATION -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY='' build-for-testing" - xc "-scheme Realm -configuration $CONFIGURATION -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY='' test" - exit 0 - ;; - - "test-catalyst-swift") - export REALM_SDKROOT=iphoneos - xc "-scheme RealmSwift -configuration $CONFIGURATION -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY='' build-for-testing" - xc "-scheme RealmSwift -configuration $CONFIGURATION -destination 'platform=macOS,variant=Mac Catalyst' CODE_SIGN_IDENTITY='' test" - exit 0 - ;; - - ###################################### - # Full verification - ###################################### - "verify") - sh build.sh verify-cocoapods - sh build.sh verify-docs - sh build.sh verify-osx - sh build.sh verify-osx-debug - sh build.sh verify-osx-swift - sh build.sh verify-osx-swift-debug - sh build.sh verify-ios-static - sh build.sh verify-ios-static-debug - sh build.sh verify-ios-dynamic - sh build.sh verify-ios-dynamic-debug - sh build.sh verify-ios-swift - sh build.sh verify-ios-swift-debug - sh build.sh verify-ios-device-objc - sh build.sh verify-ios-device-swift - sh build.sh verify-watchos - sh build.sh verify-tvos - sh build.sh verify-tvos-debug - sh build.sh verify-tvos-device - sh build.sh verify-swiftlint - sh build.sh verify-swiftpm - sh build.sh verify-osx-object-server - if (( $(xcode_version_major) >= 11 )); then - sh build.sh verify-catalyst - sh build.sh verify-catalyst-swift - fi - ;; - - "verify-cocoapods") - if [[ -d .git ]]; then - # Verify the current branch, unless one was already specified in the sha environment variable. - if [[ -z $sha ]]; then - export sha=$(git rev-parse --abbrev-ref HEAD) - fi - - if [[ $(git log -1 @{push}..) != "" ]] || ! git diff-index --quiet HEAD; then - echo "WARNING: verify-cocoapods will test the latest revision of $sha found on GitHub." - echo " Any unpushed local changes will not be tested." - echo "" - sleep 1 - fi - fi - - sh build.sh verify-cocoapods-ios - sh build.sh verify-cocoapods-ios-dynamic - sh build.sh verify-cocoapods-osx - sh build.sh verify-cocoapods-watchos - - # https://github.com/CocoaPods/CocoaPods/issues/7708 - export EXPANDED_CODE_SIGN_IDENTITY='' - cd examples/installation - sh build.sh test-ios-objc-cocoapods - sh build.sh test-ios-objc-cocoapods-dynamic - sh build.sh test-ios-swift-cocoapods - sh build.sh test-osx-objc-cocoapods - sh build.sh test-osx-swift-cocoapods - sh build.sh test-watchos-objc-cocoapods - sh build.sh test-watchos-swift-cocoapods - ;; - - verify-cocoapods-ios-dynamic) - PLATFORM=$(echo $COMMAND | cut -d - -f 3) - # https://github.com/CocoaPods/CocoaPods/issues/7708 - export EXPANDED_CODE_SIGN_IDENTITY='' - cd examples/installation - sh build.sh test-ios-objc-cocoapods-dynamic - ;; - - verify-cocoapods-*) - PLATFORM=$(echo $COMMAND | cut -d - -f 3) - # https://github.com/CocoaPods/CocoaPods/issues/7708 - export EXPANDED_CODE_SIGN_IDENTITY='' - cd examples/installation - sh build.sh test-$PLATFORM-objc-cocoapods - sh build.sh test-$PLATFORM-swift-cocoapods - ;; - - "verify-osx-encryption") - REALM_ENCRYPT_ALL=YES sh build.sh test-osx - exit 0 - ;; - - "verify-osx") - sh build.sh test-osx - sh build.sh examples-osx - - ( - cd examples/osx/objc/build/DerivedData/RealmExamples/Build/Products/$CONFIGURATION - DYLD_FRAMEWORK_PATH=. ./JSONImport >/dev/null - ) - exit 0 - ;; - - "verify-osx-swift") - sh build.sh test-osx-swift - exit 0 - ;; - - "verify-ios-static") - REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/ios/objc/RealmExamples.xcworkspace" sh build.sh test-ios-static - sh build.sh examples-ios - ;; - - "verify-ios-dynamic") - sh build.sh test-ios-dynamic - ;; - - "verify-ios-swift") - REALM_EXTRA_BUILD_ARGUMENTS="$REALM_EXTRA_BUILD_ARGUMENTS -workspace examples/ios/swift/RealmExamples.xcworkspace" sh build.sh test-ios-swift - sh build.sh examples-ios-swift - ;; - - "verify-ios-device-objc") - sh build.sh test-ios-devices-objc - exit 0 - ;; - - "verify-ios-device-swift") - sh build.sh test-ios-devices-swift - exit 0 - ;; - - "verify-docs") - sh build.sh docs - for lang in swift objc; do - undocumented="docs/${lang}_output/undocumented.json" - if ruby -rjson -e "j = JSON.parse(File.read('docs/${lang}_output/undocumented.json')); exit j['warnings'].length != 0"; then - echo "Undocumented Realm $lang declarations:" - cat "$undocumented" - exit 1 - fi - done - exit 0 - ;; - - "verify-watchos") - sh build.sh watchos-swift - exit 0 - ;; - - "verify-tvos") - sh build.sh test-tvos - sh build.sh examples-tvos - exit 0 - ;; - - "verify-tvos-swift") - sh build.sh test-tvos-swift - sh build.sh examples-tvos-swift - exit 0 - ;; - - "verify-tvos-device") - sh build.sh test-tvos-devices - exit 0 - ;; - - "verify-swiftlint") - swiftlint lint --strict - exit 0 - ;; - - verify-swiftpm*) - sh build.sh test-$(echo $COMMAND | cut -d - -f 2-) - exit 0 - ;; - - "verify-osx-object-server") - sh build.sh test-osx-object-server - exit 0 - ;; - - "verify-catalyst") - sh build.sh test-catalyst - exit 0 - ;; - - "verify-catalyst-swift") - sh build.sh test-catalyst-swift - exit 0 - ;; - - ###################################### - # Docs - ###################################### - "docs") - build_docs objc - build_docs swift - exit 0 - ;; - - ###################################### - # Examples - ###################################### - "examples") - sh build.sh clean - sh build.sh examples-ios - sh build.sh examples-ios-swift - sh build.sh examples-osx - sh build.sh examples-tvos - sh build.sh examples-tvos-swift - exit 0 - ;; - - "examples-ios") - sh build.sh prelaunch-simulator - workspace="examples/ios/objc/RealmExamples.xcworkspace" - pod install --project-directory="$workspace/.." --no-repo-update - xc "-workspace $workspace -scheme Simple -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme TableView -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Migration -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Backlink -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme GroupedTableView -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme RACTableView -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Encryption -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Draw -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - - if [ ! -z "${JENKINS_HOME}" ]; then - xc "-workspace $workspace -scheme Extension -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - fi - - exit 0 - ;; - - "examples-ios-swift") - sh build.sh prelaunch-simulator - workspace="examples/ios/swift/RealmExamples.xcworkspace" - if [[ ! -d "$workspace" ]]; then - workspace="${workspace/swift/swift-$REALM_XCODE_VERSION}" - fi - - xc "-workspace $workspace -scheme Simple -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme TableView -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Migration -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Encryption -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme Backlink -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme GroupedTableView -configuration $CONFIGURATION -destination 'name=iPhone 8' build ${CODESIGN_PARAMS}" - exit 0 - ;; - - "examples-osx") - xc "-workspace examples/osx/objc/RealmExamples.xcworkspace -scheme JSONImport -configuration ${CONFIGURATION} build ${CODESIGN_PARAMS}" - ;; - - "examples-tvos") - workspace="examples/tvos/objc/RealmExamples.xcworkspace" - destination="Apple TV" - - xc "-workspace $workspace -scheme DownloadCache -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme PreloadedData -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" - exit 0 - ;; - - "examples-tvos-swift") - workspace="examples/tvos/swift/RealmExamples.xcworkspace" - if [[ ! -d "$workspace" ]]; then - workspace="${workspace/swift/swift-$REALM_XCODE_VERSION}" - fi - - destination="Apple TV" - xc "-workspace $workspace -scheme DownloadCache -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" - xc "-workspace $workspace -scheme PreloadedData -configuration $CONFIGURATION -destination 'name=$destination' build ${CODESIGN_PARAMS}" - exit 0 - ;; - - ###################################### - # Versioning - ###################################### - "get-version") - echo "$(plist_get 'Realm/Realm-Info.plist' 'CFBundleShortVersionString')" - exit 0 - ;; - - "set-version") - realm_version="$2" - version_files="Realm/Realm-Info.plist" - - if [ -z "$realm_version" ]; then - echo "You must specify a version." - exit 1 - fi - # The bundle version can contain only three groups of digits separated by periods, - # so strip off any -beta.x tag from the end of the version string. - bundle_version=$(echo "$realm_version" | cut -d - -f 1) - for version_file in $version_files; do - PlistBuddy -c "Set :CFBundleVersion $bundle_version" "$version_file" - PlistBuddy -c "Set :CFBundleShortVersionString $realm_version" "$version_file" - done - sed -i '' "s/^VERSION=.*/VERSION=$realm_version/" dependencies.list - sed -i '' "s/^let coreVersionStr =.*/let coreVersionStr = \"$REALM_CORE_VERSION\"/" Package.swift - sed -i '' "s/^let cocoaVersionStr =.*/let cocoaVersionStr = \"$realm_version\"/" Package.swift - exit 0 - ;; - - ###################################### - # Bitcode Detection - ###################################### - - "binary-has-bitcode") - # Disable pipefail as grep -q will make otool fail due to exiting - # before reading all the output - set +o pipefail - - BINARY="$2" - if otool -l "$BINARY" | grep -q "segname __LLVM"; then - exit 0 - fi - # Work around rdar://21826157 by checking for bitcode in thin binaries - - # Get architectures for binary - archs="$(lipo -info "$BINARY" | rev | cut -d ':' -f1 | rev)" - - archs_array=( $archs ) - if [[ ${#archs_array[@]} -lt 2 ]]; then - echo 'Error: Built library is not a fat binary' - exit 1 # Early exit if not a fat binary - fi - - TEMPDIR=$(mktemp -d $TMPDIR/realm-bitcode-check.XXXX) - - for arch in $archs; do - lipo -thin "$arch" "$BINARY" -output "$TEMPDIR/$arch" - if otool -l "$TEMPDIR/$arch" | grep -q "segname __LLVM"; then - exit 0 - fi - done - echo 'Error: Built library does not contain bitcode' - exit 1 - ;; - - ###################################### - # CocoaPods - ###################################### - "cocoapods-setup") - if [ ! -d core ]; then - sh build.sh download-sync - rm core - mv sync-* core - mv core/librealm-ios.a core/librealmcore-ios.a - mv core/librealm-macosx.a core/librealmcore-macosx.a - mv core/librealm-tvos.a core/librealmcore-tvos.a - mv core/librealm-watchos.a core/librealmcore-watchos.a - fi - - if [[ "$2" != "swift" ]]; then - if [ ! -d Realm/ObjectStore/src ]; then - cat >&2 < Realm/RLMPlatform.h - if [ -n "$COCOAPODS_VERSION" ]; then - # This variable is set for the prepare_command available - # from the 1.0 prereleases, which requires a different - # header layout within the header_mappings_dir. - cp Realm/*.h include - else - # For CocoaPods < 1.0, we need to scope the headers within - # the header_mappings_dir by another subdirectory to avoid - # Clang from complaining about non-modular headers. - mkdir -p include/Realm - cp Realm/*.h include/Realm - fi - else - sh build.sh set-swift-version - fi - ;; - - ###################################### - # Continuous Integration - ###################################### - - "ci-pr") - mkdir -p build/reports - export REALM_DISABLE_ANALYTICS=1 - export REALM_DISABLE_UPDATE_CHECKER=1 - # FIXME: Re-enable once CI can properly unlock the keychain - export REALM_DISABLE_METADATA_ENCRYPTION=1 - - # strip off the ios|tvos version specifier, e.g. the last part of: `ios-device-objc-ios8` - if [[ "$target" =~ ^((ios|tvos)-device(-(objc|swift))?)(-(ios|tvos)[[:digit:]]+)?$ ]]; then - export target=${BASH_REMATCH[1]} - fi - - if [ "$target" = "docs" ]; then - sh build.sh set-swift-version - sh build.sh verify-docs - elif [ "$target" = "swiftlint" ]; then - sh build.sh verify-swiftlint - else - export sha=$GITHUB_PR_SOURCE_BRANCH - export CONFIGURATION=$configuration - export REALM_EXTRA_BUILD_ARGUMENTS='GCC_GENERATE_DEBUGGING_SYMBOLS=NO -allowProvisioningUpdates' - if [[ ${target} != *"osx"* ]];then - sh build.sh prelaunch-simulator - fi - - source $(brew --prefix nvm)/nvm.sh --no-use - export REALM_NODE_PATH="$(nvm which 8)" - - # Reset CoreSimulator.log - mkdir -p ~/Library/Logs/CoreSimulator - echo > ~/Library/Logs/CoreSimulator/CoreSimulator.log - - if [ -d ~/Library/Developer/CoreSimulator/Devices/ ]; then - # Verify that no Realm files still exist - ! find ~/Library/Developer/CoreSimulator/Devices/ -name '*.realm' | grep -q . - fi - - failed=0 - sh build.sh verify-$target 2>&1 | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 - if [ "$failed" = "1" ] && cat build/build.log | grep -E 'DTXProxyChannel|DTXChannel|out of date and needs to be rebuilt|operation never finished bootstrapping'; then - echo "Known Xcode error detected. Running job again." - if cat build/build.log | grep -E 'out of date and needs to be rebuilt'; then - rm -rf build/DerivedData - fi - failed=0 - sh build.sh verify-$target | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 - elif [ "$failed" = "1" ] && tail ~/Library/Logs/CoreSimulator/CoreSimulator.log | grep -E "Operation not supported|Failed to lookup com.apple.coreservices.lsuseractivity.simulatorsupport"; then - echo "Known Xcode error detected. Running job again." - failed=0 - sh build.sh verify-$target | tee build/build.log | xcpretty -r junit -o build/reports/junit.xml || failed=1 - fi - if [ "$failed" = "1" ]; then - echo "\n\n***\nbuild/build.log\n***\n\n" && cat build/build.log || true - echo "\n\n***\nCoreSimulator.log\n***\n\n" && cat ~/Library/Logs/CoreSimulator/CoreSimulator.log - exit 1 - fi - fi - - if [ "$target" = "osx" ] && [ "$configuration" = "Debug" ]; then - gcovr -r . -f ".*Realm.*" -e ".*Tests.*" -e ".*core.*" --xml > build/reports/coverage-report.xml - WS=$(pwd | sed "s/\//\\\\\//g") - sed -i ".bak" "s/\./${WS}/" build/reports/coverage-report.xml - fi - ;; - - ###################################### - # Release packaging - ###################################### - - "package-examples") - ./scripts/package_examples.rb - zip --symlinks -r realm-examples.zip examples -x "examples/installation/*" - ;; - - "package-test-examples-objc") - if ! VERSION=$(echo realm-objc-*.zip | egrep -o '\d*\.\d*\.\d*-[a-z]*(\.\d*)?'); then - VERSION=$(echo realm-objc-*.zip | egrep -o '\d*\.\d*\.\d*') - fi - OBJC="realm-objc-${VERSION}" - unzip ${OBJC}.zip - - cp $0 ${OBJC} - cp -r ${source_root}/scripts ${OBJC} - cd ${OBJC} - sh build.sh examples-ios - sh build.sh examples-tvos - sh build.sh examples-osx - cd .. - rm -rf ${OBJC} - ;; - - "package-test-examples-swift") - if ! VERSION=$(echo realm-swift-*.zip | egrep -o '\d*\.\d*\.\d*-[a-z]*(\.\d*)?'); then - VERSION=$(echo realm-swift-*.zip | egrep -o '\d*\.\d*\.\d*') - fi - SWIFT="realm-swift-${VERSION}" - unzip ${SWIFT}.zip - - cp $0 ${SWIFT} - cp -r ${source_root}/scripts ${SWIFT} - cd ${SWIFT} - sh build.sh examples-ios-swift - sh build.sh examples-tvos-swift - cd .. - rm -rf ${SWIFT} - ;; - - "package-ios-static") - sh build.sh prelaunch-simulator - sh build.sh ios-static - - cd build/ios-static - zip --symlinks -r realm-framework-ios-static.zip Realm.framework - ;; - - "package") - PLATFORM="$2" - REALM_SWIFT_VERSION= - - set_xcode_and_swift_versions - - if [[ "$PLATFORM" = "catalyst" ]] && (( $(xcode_version_major) < 11 )); then - mkdir -p build/catalyst/swift-$REALM_XCODE_VERSION - else - sh build.sh prelaunch-simulator - sh build.sh $PLATFORM-swift - fi - - cd build/$PLATFORM - zip --symlinks -r realm-framework-$PLATFORM-$REALM_XCODE_VERSION.zip swift-$REALM_XCODE_VERSION - ;; - - "package-release") - LANG="$2" - TEMPDIR=$(mktemp -d $TMPDIR/realm-release-package-${LANG}.XXXX) - - VERSION=$(sh build.sh get-version) - - FOLDER=${TEMPDIR}/realm-${LANG}-${VERSION} - - mkdir -p ${FOLDER}/osx ${FOLDER}/ios ${FOLDER}/watchos ${FOLDER}/tvos - - if [[ "${LANG}" == "objc" ]]; then - mkdir -p ${FOLDER}/ios/static - mkdir -p ${FOLDER}/ios/dynamic - mkdir -p ${FOLDER}/Swift - - unzip ${WORKSPACE}/realm-framework-ios-static.zip -d ${FOLDER}/ios/static - for platform in osx ios watchos tvos catalyst; do - unzip ${WORKSPACE}/realm-framework-${platform}-${REALM_XCODE_VERSION}.zip -d ${FOLDER}/${platform} - mv ${FOLDER}/${platform}/swift-*/Realm.framework ${FOLDER}/${platform} - rm -r ${FOLDER}/${platform}/swift-* - done - - mv ${FOLDER}/ios/Realm.framework ${FOLDER}/ios/dynamic - else - for platform in osx ios watchos tvos catalyst; do - find ${WORKSPACE} -name "realm-framework-$platform-*.zip" \ - -maxdepth 1 \ - -exec unzip {} -d ${FOLDER}/${platform} \; - done - fi - - ( - cd ${WORKSPACE} - cp -R plugin ${FOLDER} - cp LICENSE ${FOLDER}/LICENSE.txt - if [[ "${LANG}" == "objc" ]]; then - cp Realm/Swift/RLMSupport.swift ${FOLDER}/Swift/ - fi - ) - - ( - cd ${FOLDER} - unzip ${WORKSPACE}/realm-examples.zip - cd examples - if [[ "${LANG}" == "objc" ]]; then - rm -rf ios/swift-* tvos/swift-* - else - rm -rf ios/objc ios/rubymotion osx tvos/objc - fi - ) - - cat > ${FOLDER}/docs.webloc < - - - - URL - https://realm.io/docs/${LANG}/${VERSION} - - -EOF - - ( - cd ${TEMPDIR} - zip --symlinks -r realm-${LANG}-${VERSION}.zip realm-${LANG}-${VERSION} - mv realm-${LANG}-${VERSION}.zip ${WORKSPACE} - ) - ;; - - "test-package-release") - # Generate a release package locally for testing purposes - # Real releases should always be done via Jenkins - if [ -z "${WORKSPACE}" ]; then - echo 'WORKSPACE must be set to a directory to assemble the release in' - exit 1 - fi - if [ -d "${WORKSPACE}" ]; then - echo 'WORKSPACE directory should not already exist' - exit 1 - fi - - REALM_SOURCE="$(pwd)" - mkdir -p "$WORKSPACE" - WORKSPACE="$(cd "$WORKSPACE" && pwd)" - export WORKSPACE - cd $WORKSPACE - git clone --recursive $REALM_SOURCE realm-cocoa - cd realm-cocoa - - echo 'Packaging iOS' - sh build.sh package-ios-static - cp build/ios-static/realm-framework-ios-static.zip . - sh build.sh package ios - cp build/ios/realm-framework-ios-$REALM_XCODE_VERSION.zip . - - echo 'Packaging macOS' - sh build.sh package osx - cp build/osx/realm-framework-osx-$REALM_XCODE_VERSION.zip . - - echo 'Packaging watchOS' - sh build.sh package watchos - cp build/watchos/realm-framework-watchos-$REALM_XCODE_VERSION.zip . - - echo 'Packaging tvOS' - sh build.sh package tvos - cp build/tvos/realm-framework-tvos-$REALM_XCODE_VERSION.zip . - - echo 'Packaging Catalyst' - sh build.sh package catalyst - cp build/catalyst/realm-framework-catalyst-$REALM_XCODE_VERSION.zip . - - echo 'Packaging examples' - sh build.sh package-examples - - echo 'Building final release packages' - export WORKSPACE="${WORKSPACE}/realm-cocoa" - sh build.sh package-release objc - sh build.sh package-release swift - - echo 'Testing packaged examples' - sh build.sh package-test-examples-objc - sh build.sh package-test-examples-swift - ;; - - "github-release") - if [ -z "${GITHUB_ACCESS_TOKEN}" ]; then - echo 'GITHUB_ACCESS_TOKEN must be set to create GitHub releases' - exit 1 - fi - ./scripts/github_release.rb - ;; - - "add-empty-changelog") - empty_section=$(cat < ([#????](https://github.com/realm/realm-js/issues/????), since v?.?.?) -* None. - - - -### Compatibility -* File format: Generates Realms with format v9 (Reads and upgrades all previous formats) -* Realm Object Server: 3.21.0 or later. -* APIs are backwards compatible with all previous releases in the 4.x.y series. -* Carthage release for Swift is built with Xcode 11.3. - -### Internal -Upgraded realm-core from ? to ? -Upgraded realm-sync from ? to ? - -EOS) - changelog=$(cat CHANGELOG.md) - echo "$empty_section" > CHANGELOG.md - echo >> CHANGELOG.md - echo "$changelog" >> CHANGELOG.md - ;; - - *) - echo "Unknown command '$COMMAND'" - usage - exit 1 - ;; -esac diff --git a/Lesson14/Pods/Realm/core/librealmcore-ios.a b/Lesson14/Pods/Realm/core/librealmcore-ios.a deleted file mode 100644 index 0f80c66..0000000 Binary files a/Lesson14/Pods/Realm/core/librealmcore-ios.a and /dev/null differ diff --git a/Lesson14/Pods/Realm/include/NSError+RLMSync.h b/Lesson14/Pods/Realm/include/NSError+RLMSync.h deleted file mode 100644 index 797db58..0000000 --- a/Lesson14/Pods/Realm/include/NSError+RLMSync.h +++ /dev/null @@ -1,46 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMSyncErrorActionToken; - -/// NSError category extension providing methods to get data out of Realm's -/// "client reset" error. -@interface NSError (RLMSync) - -/** - Given an appropriate Realm Object Server error, return the token that - can be passed into `+[RLMSyncSession immediatelyHandleError:]` to - immediately perform error clean-up work, or nil if the error isn't of - a type that provides a token. - */ -- (nullable RLMSyncErrorActionToken *)rlmSync_errorActionToken NS_REFINED_FOR_SWIFT; - -/** - Given a Realm Object Server client reset error, return the path where the - backup copy of the Realm will be placed once the client reset process is - complete. - */ -- (nullable NSString *)rlmSync_clientResetBackedUpRealmPath NS_SWIFT_UNAVAILABLE(""); - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMAccessor.h b/Lesson14/Pods/Realm/include/RLMAccessor.h deleted file mode 100644 index bcf5dfb..0000000 --- a/Lesson14/Pods/Realm/include/RLMAccessor.h +++ /dev/null @@ -1,53 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -@class RLMObjectSchema, RLMProperty, RLMObjectBase; - -NS_ASSUME_NONNULL_BEGIN - -// -// Accessors Class Creation/Caching -// - -// get accessor classes for an object class - generates classes if not cached -Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name); -Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema); - -// -// Dynamic getters/setters -// -FOUNDATION_EXTERN void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id __nullable val); -FOUNDATION_EXTERN id __nullable RLMDynamicGet(RLMObjectBase *obj, RLMProperty *prop); -FOUNDATION_EXTERN id __nullable RLMDynamicGetByName(RLMObjectBase *obj, NSString *propName); - -// by property/column -void RLMDynamicSet(RLMObjectBase *obj, RLMProperty *prop, id val); - -// -// Class modification -// - -// Replace className method for the given class -void RLMReplaceClassNameMethod(Class accessorClass, NSString *className); - -// Replace sharedSchema method for the given class -void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema * __nullable schema); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMAccessor.hpp b/Lesson14/Pods/Realm/include/RLMAccessor.hpp deleted file mode 100644 index 88884e2..0000000 --- a/Lesson14/Pods/Realm/include/RLMAccessor.hpp +++ /dev/null @@ -1,117 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "RLMAccessor.h" - -#import "object_accessor.hpp" - -#import "RLMUtil.hpp" - -@class RLMRealm; -class RLMClassInfo; -class RLMObservationInfo; - -// realm::util::Optional doesn't work because Objective-C types can't -// be members of unions with ARC, so this covers the subset of Optional that we -// actually need. -struct RLMOptionalId { - id value; - RLMOptionalId(id value) : value(value) { } - explicit operator bool() const noexcept { return value; } - id operator*() const noexcept { return value; } -}; - -class RLMAccessorContext { -public: - // Accessor context interface - RLMAccessorContext(RLMAccessorContext& parent, realm::Property const& property); - - id box(realm::List&&); - id box(realm::Results&&); - id box(realm::Object&&); - id box(realm::RowExpr); - - id box(bool v) { return @(v); } - id box(double v) { return @(v); } - id box(float v) { return @(v); } - id box(long long v) { return @(v); } - id box(realm::StringData v) { return RLMStringDataToNSString(v) ?: NSNull.null; } - id box(realm::BinaryData v) { return RLMBinaryDataToNSData(v) ?: NSNull.null; } - id box(realm::Timestamp v) { return RLMTimestampToNSDate(v) ?: NSNull.null; } - id box(realm::Mixed v) { return RLMMixedToObjc(v); } - - id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } - id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } - id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } - id box(realm::util::Optional v) { return v ? @(*v) : NSNull.null; } - - void will_change(realm::Row const&, realm::Property const&); - void will_change(realm::Object& obj, realm::Property const& prop) { will_change(obj.row(), prop); } - void did_change(); - - RLMOptionalId value_for_property(id dict, realm::Property const&, size_t prop_index); - RLMOptionalId default_value_for_property(realm::ObjectSchema const&, - realm::Property const& prop); - - bool is_same_list(realm::List const& list, id v) const noexcept; - - template - void enumerate_list(__unsafe_unretained const id v, Func&& func) { - id enumerable = RLMAsFastEnumeration(v) ?: v; - for (id value in enumerable) { - func(value); - } - } - - template - T unbox(id v, realm::CreatePolicy = realm::CreatePolicy::Skip, size_t = 0); - - bool is_null(id v) { return v == NSNull.null; } - id null_value() { return NSNull.null; } - id no_value() { return nil; } - bool allow_missing(id v) { return [v isKindOfClass:[NSArray class]]; } - - std::string print(id obj) { return [obj description].UTF8String; } - - // Internal API - RLMAccessorContext(RLMObjectBase *parentObject, const realm::Property *property = nullptr); - RLMAccessorContext(RLMClassInfo& info, bool promote=true); - - // The property currently being accessed; needed for KVO things for boxing - // List and Results - RLMProperty *currentProperty; - -private: - __unsafe_unretained RLMRealm *const _realm; - RLMClassInfo& _info; - // If true, promote unmanaged RLMObjects passed to box() with create=true - // rather than copying them - bool _promote_existing = true; - // Parent object of the thing currently being processed, for KVO purposes - __unsafe_unretained RLMObjectBase *const _parentObject = nil; - - // Cached default values dictionary to avoid having to call the class method - // for every property - NSDictionary *_defaultValues; - - RLMObservationInfo *_observationInfo = nullptr; - NSString *_kvoPropertyName = nil; - - id defaultValue(NSString *key); - id propertyValue(id obj, size_t propIndex, __unsafe_unretained RLMProperty *const prop); -}; diff --git a/Lesson14/Pods/Realm/include/RLMAnalytics.hpp b/Lesson14/Pods/Realm/include/RLMAnalytics.hpp deleted file mode 100644 index ccb4ea2..0000000 --- a/Lesson14/Pods/Realm/include/RLMAnalytics.hpp +++ /dev/null @@ -1,55 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -// Asynchronously submits build information to Realm if running in an iOS -// simulator or on OS X if a debugger is attached. Does nothing if running on an -// iOS / watchOS device or if a debugger is *not* attached. -// -// To be clear: this does *not* run when your app is in production or on -// your end-user’s devices; it will only run in the simulator or when a debugger -// is attached. -// -// Why are we doing this? In short, because it helps us build a better product -// for you. None of the data personally identifies you, your employer or your -// app, but it *will* help us understand what language you use, what iOS -// versions you target, etc. Having this info will help prioritizing our time, -// adding new features and deprecating old features. Collecting an anonymized -// bundle & anonymized MAC is the only way for us to count actual usage of the -// other metrics accurately. If we don’t have a way to deduplicate the info -// reported, it will be useless, as a single developer building their Swift app -// 10 times would report 10 times more than a single Objective-C developer that -// only builds once, making the data all but useless. -// No one likes sharing data unless it’s necessary, we get it, and we’ve -// debated adding this for a long long time. Since Realm is a free product -// without an email signup, we feel this is a necessary step so we can collect -// relevant data to build a better product for you. If you truly, absolutely -// feel compelled to not send this data back to Realm, then you can set an env -// variable named REALM_DISABLE_ANALYTICS. Since Realm is free we believe -// letting these analytics run is a small price to pay for the product & support -// we give you. -// -// Currently the following information is reported: -// - What version of Realm is being used, and from which language (obj-c or Swift). -// - What version of OS X it's running on (in case Xcode aggressively drops -// support for older versions again, we need to know what we need to support). -// - The minimum iOS/OS X version that the application is targeting (again, to -// help us decide what versions we need to support). -// - An anonymous MAC address and bundle ID to aggregate the other information on. -// - What version of Swift is being used (if applicable). - -void RLMSendAnalytics(); diff --git a/Lesson14/Pods/Realm/include/RLMArray.h b/Lesson14/Pods/Realm/include/RLMArray.h deleted file mode 100644 index 3ef38eb..0000000 --- a/Lesson14/Pods/Realm/include/RLMArray.h +++ /dev/null @@ -1,440 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMObject, RLMResults; - -/** - `RLMArray` is the container type in Realm used to define to-many relationships. - - Unlike an `NSArray`, `RLMArray`s hold a single type, specified by the `objectClassName` property. - This is referred to in these docs as the “type” of the array. - - When declaring an `RLMArray` property, the type must be marked as conforming to a - protocol by the same name as the objects it should contain (see the - `RLM_ARRAY_TYPE` macro). In addition, the property can be declared using Objective-C - generics for better compile-time type safety. - - RLM_ARRAY_TYPE(ObjectType) - ... - @property RLMArray *arrayOfObjectTypes; - - `RLMArray`s can be queried with the same predicates as `RLMObject` and `RLMResult`s. - - `RLMArray`s cannot be created directly. `RLMArray` properties on `RLMObject`s are - lazily created when accessed, or can be obtained by querying a Realm. - - ### Key-Value Observing - - `RLMArray` supports array key-value observing on `RLMArray` properties on `RLMObject` - subclasses, and the `invalidated` property on `RLMArray` instances themselves is - key-value observing compliant when the `RLMArray` is attached to a managed - `RLMObject` (`RLMArray`s on unmanaged `RLMObject`s will never become invalidated). - - Because `RLMArray`s are attached to the object which they are a property of, they - do not require using the mutable collection proxy objects from - `-mutableArrayValueForKey:` or KVC-compatible mutation methods on the containing - object. Instead, you can call the mutation methods on the `RLMArray` directly. - */ - -@interface RLMArray : NSObject - -#pragma mark - Properties - -/** - The number of objects in the array. - */ -@property (nonatomic, readonly, assign) NSUInteger count; - -/** - The type of the objects in the array. - */ -@property (nonatomic, readonly, assign) RLMPropertyType type; - -/** - Indicates whether the objects in the collection can be `nil`. - */ -@property (nonatomic, readonly, getter = isOptional) BOOL optional; - -/** - The class name of the objects contained in the array. - - Will be `nil` if `type` is not RLMPropertyTypeObject. - */ -@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; - -/** - The Realm which manages the array. Returns `nil` for unmanaged arrays. - */ -@property (nonatomic, readonly, nullable) RLMRealm *realm; - -/** - Indicates if the array can no longer be accessed. - */ -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - -#pragma mark - Accessing Objects from an Array - -/** - Returns the object at the index specified. - - @param index The index to look up. - - @return An object of the type contained in the array. - */ -- (RLMObjectType)objectAtIndex:(NSUInteger)index; - -/** - Returns the first object in the array. - - Returns `nil` if called on an empty array. - - @return An object of the type contained in the array. - */ -- (nullable RLMObjectType)firstObject; - -/** - Returns the last object in the array. - - Returns `nil` if called on an empty array. - - @return An object of the type contained in the array. - */ -- (nullable RLMObjectType)lastObject; - - - -#pragma mark - Adding, Removing, and Replacing Objects in an Array - -/** - Adds an object to the end of the array. - - @warning This method may only be called during a write transaction. - - @param object An object of the type contained in the array. - */ -- (void)addObject:(RLMObjectType)object; - -/** - Adds an array of objects to the end of the array. - - @warning This method may only be called during a write transaction. - - @param objects An enumerable object such as `NSArray` or `RLMResults` which contains objects of the - same class as the array. - */ -- (void)addObjects:(id)objects; - -/** - Inserts an object at the given index. - - Throws an exception if the index exceeds the bounds of the array. - - @warning This method may only be called during a write transaction. - - @param anObject An object of the type contained in the array. - @param index The index at which to insert the object. - */ -- (void)insertObject:(RLMObjectType)anObject atIndex:(NSUInteger)index; - -/** - Removes an object at the given index. - - Throws an exception if the index exceeds the bounds of the array. - - @warning This method may only be called during a write transaction. - - @param index The array index identifying the object to be removed. - */ -- (void)removeObjectAtIndex:(NSUInteger)index; - -/** - Removes the last object in the array. - - This is a no-op if the array is already empty. - - @warning This method may only be called during a write transaction. -*/ -- (void)removeLastObject; - -/** - Removes all objects from the array. - - @warning This method may only be called during a write transaction. - */ -- (void)removeAllObjects; - -/** - Replaces an object at the given index with a new object. - - Throws an exception if the index exceeds the bounds of the array. - - @warning This method may only be called during a write transaction. - - @param index The index of the object to be replaced. - @param anObject An object (of the same type as returned from the `objectClassName` selector). - */ -- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(RLMObjectType)anObject; - -/** - Moves the object at the given source index to the given destination index. - - Throws an exception if the index exceeds the bounds of the array. - - @warning This method may only be called during a write transaction. - - @param sourceIndex The index of the object to be moved. - @param destinationIndex The index to which the object at `sourceIndex` should be moved. - */ -- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex; - -/** - Exchanges the objects in the array at given indices. - - Throws an exception if either index exceeds the bounds of the array. - - @warning This method may only be called during a write transaction. - - @param index1 The index of the object which should replace the object at index `index2`. - @param index2 The index of the object which should replace the object at index `index1`. - */ -- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2; - -#pragma mark - Querying an Array - -/** - Returns the index of an object in the array. - - Returns `NSNotFound` if the object is not found in the array. - - @param object An object (of the same type as returned from the `objectClassName` selector). - */ -- (NSUInteger)indexOfObject:(RLMObjectType)object; - -/** - Returns the index of the first object in the array matching the predicate. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return The index of the object, or `NSNotFound` if the object is not found in the array. - */ -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns the index of the first object in the array matching the predicate. - - @param predicate The predicate with which to filter the objects. - - @return The index of the object, or `NSNotFound` if the object is not found in the array. - */ -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; - -/** - Returns all the objects matching the given predicate in the array. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return An `RLMResults` of objects that match the given predicate. - */ -- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns all the objects matching the given predicate in the array. - - @param predicate The predicate with which to filter the objects. - - @return An `RLMResults` of objects that match the given predicate - */ -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; - -/** - Returns a sorted `RLMResults` from the array. - - @param keyPath The key path to sort by. - @param ascending The direction to sort in. - - @return An `RLMResults` sorted by the specified key path. - */ -- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; - -/** - Returns a sorted `RLMResults` from the array. - - @param properties An array of `RLMSortDescriptor`s to sort by. - - @return An `RLMResults` sorted by the specified properties. - */ -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; - -/// :nodoc: -- (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index; - -/// :nodoc: -- (void)setObject:(RLMObjectType)newValue atIndexedSubscript:(NSUInteger)index; - -#pragma mark - Notifications - -/** - Registers a block to be called each time the array changes. - - The block will be asynchronously called with the initial array, and then - called again after each write transaction which changes any of the objects in - the array, which objects are in the results, or the order of the objects in the - array. - - The `changes` parameter will be `nil` the first time the block is called. - For each call after that, it will contain information about - which rows in the array were added, removed or modified. If a write transaction - did not modify any objects in the array, the block is not called at all. - See the `RLMCollectionChange` documentation for information on how the changes - are reported and an example of updating a `UITableView`. - - If an error occurs the block will be called with `nil` for the results - parameter and a non-`nil` error. Currently the only errors that can occur are - when opening the Realm on the background worker thread. - - Notifications are delivered via the standard run loop, and so can't be - delivered while the run loop is blocked by other activity. When - notifications can't be delivered instantly, multiple notifications may be - coalesced into a single notification. This can include the notification - with the initial results. For example, the following code performs a write - transaction immediately after adding the notification block, so there is no - opportunity for the initial notification to be delivered first. As a - result, the initial notification will reflect the state of the Realm after - the write transaction. - - Person *person = [[Person allObjectsInRealm:realm] firstObject]; - NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0 - self.token = [person.dogs addNotificationBlock(RLMArray *dogs, - RLMCollectionChange *changes, - NSError *error) { - // Only fired once for the example - NSLog(@"dogs.count: %zu", dogs.count) // => 1 - }]; - [realm transactionWithBlock:^{ - Dog *dog = [[Dog alloc] init]; - dog.name = @"Rex"; - [person.dogs addObject:dog]; - }]; - // end of run loop execution context - - You must retain the returned token for as long as you want updates to continue - to be sent to the block. To stop receiving updates, call `-invalidate` on the token. - - @warning This method cannot be called during a write transaction, or when the - containing Realm is read-only. - @warning This method may only be called on a managed array. - - @param block The block to be called each time the array changes. - @return A token which must be held for as long as you want updates to be delivered. - */ -- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMArray *__nullable array, - RLMCollectionChange *__nullable changes, - NSError *__nullable error))block __attribute__((warn_unused_result)); - -#pragma mark - Aggregating Property Values - -/** - Returns the minimum (lowest) value of the given property among all the objects in the array. - - NSNumber *min = [object.arrayProperty minOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose minimum value is desired. Only properties of - types `int`, `float`, `double`, and `NSDate` are supported. - - @return The minimum value of the property, or `nil` if the array is empty. - */ -- (nullable id)minOfProperty:(NSString *)property; - -/** - Returns the maximum (highest) value of the given property among all the objects in the array. - - NSNumber *max = [object.arrayProperty maxOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose maximum value is desired. Only properties of - types `int`, `float`, `double`, and `NSDate` are supported. - - @return The maximum value of the property, or `nil` if the array is empty. - */ -- (nullable id)maxOfProperty:(NSString *)property; - -/** - Returns the sum of the values of a given property over all the objects in the array. - - NSNumber *sum = [object.arrayProperty sumOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose values should be summed. Only properties of - types `int`, `float`, and `double` are supported. - - @return The sum of the given property. - */ -- (NSNumber *)sumOfProperty:(NSString *)property; - -/** - Returns the average value of a given property over the objects in the array. - - NSNumber *average = [object.arrayProperty averageOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose average value should be calculated. Only - properties of types `int`, `float`, and `double` are supported. - - @return The average value of the given property, or `nil` if the array is empty. - */ -- (nullable NSNumber *)averageOfProperty:(NSString *)property; - - -#pragma mark - Unavailable Methods - -/** - `-[RLMArray init]` is not available because `RLMArray`s cannot be created directly. - `RLMArray` properties on `RLMObject`s are lazily created when accessed. - */ -- (instancetype)init __attribute__((unavailable("RLMArrays cannot be created directly"))); - -/** - `+[RLMArray new]` is not available because `RLMArray`s cannot be created directly. - `RLMArray` properties on `RLMObject`s are lazily created when accessed. - */ -+ (instancetype)new __attribute__((unavailable("RLMArrays cannot be created directly"))); - -@end - -/// :nodoc: -@interface RLMArray (Swift) -// for use only in Swift class definitions -- (instancetype)initWithObjectClassName:(NSString *)objectClassName; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMArray_Private.h b/Lesson14/Pods/Realm/include/RLMArray_Private.h deleted file mode 100644 index 02b908a..0000000 --- a/Lesson14/Pods/Realm/include/RLMArray_Private.h +++ /dev/null @@ -1,32 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMArray () -- (instancetype)initWithObjectClassName:(NSString *)objectClassName; -- (instancetype)initWithObjectType:(RLMPropertyType)type optional:(BOOL)optional; -- (NSString *)descriptionWithMaxDepth:(NSUInteger)depth; -@end - -void RLMArrayValidateMatchingObjectType(RLMArray *array, id value); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMArray_Private.hpp b/Lesson14/Pods/Realm/include/RLMArray_Private.hpp deleted file mode 100644 index 9626a16..0000000 --- a/Lesson14/Pods/Realm/include/RLMArray_Private.hpp +++ /dev/null @@ -1,72 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMArray_Private.h" - -#import "RLMCollection_Private.hpp" - -#import "RLMResults_Private.hpp" - -#import -#import - -namespace realm { - class Results; -} - -@class RLMObjectBase, RLMObjectSchema, RLMProperty; -class RLMClassInfo; -class RLMObservationInfo; - -@interface RLMArray () { -@protected - NSString *_objectClassName; - RLMPropertyType _type; - BOOL _optional; -@public - // The name of the property which this RLMArray represents - NSString *_key; - __weak RLMObjectBase *_parentObject; -} -@end - -@interface RLMManagedArray : RLMArray -- (instancetype)initWithParent:(RLMObjectBase *)parentObject property:(RLMProperty *)property; -- (RLMManagedArray *)initWithList:(realm::List)list - parentInfo:(RLMClassInfo *)parentInfo - property:(__unsafe_unretained RLMProperty *const)property; - -- (bool)isBackedByList:(realm::List const&)list; - -// deletes all objects in the RLMArray from their containing realms -- (void)deleteObjectsFromRealm; -@end - -void RLMValidateArrayObservationKey(NSString *keyPath, RLMArray *array); - -// Initialize the observation info for an array if needed -void RLMEnsureArrayObservationInfo(std::unique_ptr& info, - NSString *keyPath, RLMArray *array, id observed); - - -// -// RLMResults private methods -// -@interface RLMResults () -- (void)deleteObjectsFromRealm; -@end diff --git a/Lesson14/Pods/Realm/include/RLMClassInfo.hpp b/Lesson14/Pods/Realm/include/RLMClassInfo.hpp deleted file mode 100644 index 7d1d23e..0000000 --- a/Lesson14/Pods/Realm/include/RLMClassInfo.hpp +++ /dev/null @@ -1,113 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 -#import -#import - -namespace realm { - class ObjectSchema; - class Schema; - class Table; - struct Property; -} - -class RLMObservationInfo; -@class RLMRealm, RLMSchema, RLMObjectSchema, RLMProperty; - -NS_ASSUME_NONNULL_BEGIN - -namespace std { -// Add specializations so that NSString can be used as the key for hash containers -template<> struct hash { - size_t operator()(__unsafe_unretained NSString *const str) const { - return [str hash]; - } -}; -template<> struct equal_to { - bool operator()(__unsafe_unretained NSString * lhs, __unsafe_unretained NSString *rhs) const { - return [lhs isEqualToString:rhs]; - } -}; -} - -// The per-RLMRealm object schema information which stores the cached table -// reference, handles table column lookups, and tracks observed objects -class RLMClassInfo { -public: - RLMClassInfo(RLMRealm *, RLMObjectSchema *, const realm::ObjectSchema *); - - __unsafe_unretained RLMRealm *const realm; - __unsafe_unretained RLMObjectSchema *const rlmObjectSchema; - const realm::ObjectSchema *const objectSchema; - - // Storage for the functionality in RLMObservation for handling indirect - // changes to KVO-observed things - std::vector observedObjects; - - // Get the table for this object type. Will return nullptr only if it's a - // read-only Realm that is missing the table entirely. - realm::Table *_Nullable table() const; - - // Get the RLMProperty for a given table column, or `nil` if it is a column - // not used by the current schema - RLMProperty *_Nullable propertyForTableColumn(NSUInteger) const noexcept; - - // Get the RLMProperty that's used as the primary key, or `nil` if there is - // no primary key for the current schema - RLMProperty *_Nullable propertyForPrimaryKey() const noexcept; - - // Get the table column for the given property. The property must be a valid - // persisted property. - NSUInteger tableColumn(NSString *propertyName) const; - NSUInteger tableColumn(RLMProperty *property) const; - - // Get the info for the target of the link at the given property index. - RLMClassInfo &linkTargetType(size_t propertyIndex); - - // Get the info for the target of the given property - RLMClassInfo &linkTargetType(realm::Property const& property); - - void releaseTable() { m_table = nullptr; } - -private: - mutable realm::Table *_Nullable m_table = nullptr; - std::vector m_linkTargets; -}; - -// A per-RLMRealm object schema map which stores RLMClassInfo keyed on the name -class RLMSchemaInfo { - using impl = std::unordered_map; -public: - RLMSchemaInfo() = default; - RLMSchemaInfo(RLMRealm *realm); - - RLMSchemaInfo clone(realm::Schema const& source_schema, RLMRealm *target_realm); - - // Look up by name, throwing if it's not present - RLMClassInfo& operator[](NSString *name); - - impl::iterator begin() noexcept; - impl::iterator end() noexcept; - impl::const_iterator begin() const noexcept; - impl::const_iterator end() const noexcept; -private: - std::unordered_map m_objects; -}; - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMCollection.h b/Lesson14/Pods/Realm/include/RLMCollection.h deleted file mode 100644 index 8d8ca49..0000000 --- a/Lesson14/Pods/Realm/include/RLMCollection.h +++ /dev/null @@ -1,401 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@class RLMRealm, RLMResults, RLMSortDescriptor, RLMNotificationToken, RLMCollectionChange; -typedef RLM_CLOSED_ENUM(int32_t, RLMPropertyType); - -/** - A homogenous collection of Realm-managed objects. Examples of conforming types - include `RLMArray`, `RLMResults`, and `RLMLinkingObjects`. - */ -@protocol RLMCollection - -@required - -#pragma mark - Properties - -/** - The number of objects in the collection. - */ -@property (nonatomic, readonly, assign) NSUInteger count; - -/** - The type of the objects in the collection. - */ -@property (nonatomic, readonly, assign) RLMPropertyType type; - -/** - Indicates whether the objects in the collection can be `nil`. - */ -@property (nonatomic, readonly, getter = isOptional) BOOL optional; - -/** - The class name of the objects contained in the collection. - - Will be `nil` if `type` is not RLMPropertyTypeObject. - */ -@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; - -/** - The Realm which manages the collection, or `nil` for unmanaged collections. - */ -@property (nonatomic, readonly) RLMRealm *realm; - -#pragma mark - Accessing Objects from a Collection - -/** - Returns the object at the index specified. - - @param index The index to look up. - - @return An object of the type contained in the collection. - */ -- (id)objectAtIndex:(NSUInteger)index; - -/** - Returns the first object in the collection. - - Returns `nil` if called on an empty collection. - - @return An object of the type contained in the collection. - */ -- (nullable id)firstObject; - -/** - Returns the last object in the collection. - - Returns `nil` if called on an empty collection. - - @return An object of the type contained in the collection. - */ -- (nullable id)lastObject; - -#pragma mark - Querying a Collection - -/** - Returns the index of an object in the collection. - - Returns `NSNotFound` if the object is not found in the collection. - - @param object An object (of the same type as returned from the `objectClassName` selector). - */ -- (NSUInteger)indexOfObject:(id)object; - -/** - Returns the index of the first object in the collection matching the predicate. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return The index of the object, or `NSNotFound` if the object is not found in the collection. - */ -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns the index of the first object in the collection matching the predicate. - - @param predicate The predicate with which to filter the objects. - - @return The index of the object, or `NSNotFound` if the object is not found in the collection. - */ -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; - -/** - Returns all objects matching the given predicate in the collection. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return An `RLMResults` containing objects that match the given predicate. - */ -- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns all objects matching the given predicate in the collection. - - @param predicate The predicate with which to filter the objects. - - @return An `RLMResults` containing objects that match the given predicate. - */ -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; - -/** - Returns a sorted `RLMResults` from the collection. - - @param keyPath The keyPath to sort by. - @param ascending The direction to sort in. - - @return An `RLMResults` sorted by the specified key path. - */ -- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; - -/** - Returns a sorted `RLMResults` from the collection. - - @param properties An array of `RLMSortDescriptor`s to sort by. - - @return An `RLMResults` sorted by the specified properties. - */ -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; - -/// :nodoc: -- (id)objectAtIndexedSubscript:(NSUInteger)index; - -/** - Returns an `NSArray` containing the results of invoking `valueForKey:` using `key` on each of the collection's objects. - - @param key The name of the property. - - @return An `NSArray` containing results. - */ -- (nullable id)valueForKey:(NSString *)key; - -/** - Invokes `setValue:forKey:` on each of the collection's objects using the specified `value` and `key`. - - @warning This method may only be called during a write transaction. - - @param value The object value. - @param key The name of the property. - */ -- (void)setValue:(nullable id)value forKey:(NSString *)key; - -#pragma mark - Notifications - -/** - Registers a block to be called each time the collection changes. - - The block will be asynchronously called with the initial collection, and then - called again after each write transaction which changes either any of the - objects in the collection, or which objects are in the collection. - - The `change` parameter will be `nil` the first time the block is called. - For each call after that, it will contain information about - which rows in the collection were added, removed or modified. If a write transaction - did not modify any objects in this collection, the block is not called at all. - See the `RLMCollectionChange` documentation for information on how the changes - are reported and an example of updating a `UITableView`. - - If an error occurs the block will be called with `nil` for the collection - parameter and a non-`nil` error. Currently the only errors that can occur are - when opening the Realm on the background worker thread. - - At the time when the block is called, the collection object will be fully - evaluated and up-to-date, and as long as you do not perform a write transaction - on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will - never perform blocking work. - - Notifications are delivered via the standard run loop, and so can't be - delivered while the run loop is blocked by other activity. When - notifications can't be delivered instantly, multiple notifications may be - coalesced into a single notification. This can include the notification - with the initial collection. For example, the following code performs a write - transaction immediately after adding the notification block, so there is no - opportunity for the initial notification to be delivered first. As a - result, the initial notification will reflect the state of the Realm after - the write transaction. - - id collection = [Dog allObjects]; - NSLog(@"dogs.count: %zu", dogs.count); // => 0 - self.token = [collection addNotificationBlock:^(id dogs, - RLMCollectionChange *changes, - NSError *error) { - // Only fired once for the example - NSLog(@"dogs.count: %zu", dogs.count); // => 1 - }]; - [realm transactionWithBlock:^{ - Dog *dog = [[Dog alloc] init]; - dog.name = @"Rex"; - [realm addObject:dog]; - }]; - // end of run loop execution context - - You must retain the returned token for as long as you want updates to continue - to be sent to the block. To stop receiving updates, call `-invalidate` on the token. - - @warning This method cannot be called during a write transaction, or when the - containing Realm is read-only. - - @param block The block to be called each time the collection changes. - @return A token which must be held for as long as you want collection notifications to be delivered. - */ -- (RLMNotificationToken *)addNotificationBlock:(void (^)(id __nullable collection, - RLMCollectionChange *__nullable change, - NSError *__nullable error))block __attribute__((warn_unused_result)); - -#pragma mark - Aggregating Property Values - -/** - Returns the minimum (lowest) value of the given property among all the objects - in the collection. - - NSNumber *min = [results minOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose minimum value is desired. Only properties of - types `int`, `float`, `double`, and `NSDate` are supported. - - @return The minimum value of the property, or `nil` if the Results are empty. - */ -- (nullable id)minOfProperty:(NSString *)property; - -/** - Returns the maximum (highest) value of the given property among all the objects - in the collection. - - NSNumber *max = [results maxOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose maximum value is desired. Only properties of - types `int`, `float`, `double`, and `NSDate` are supported. - - @return The maximum value of the property, or `nil` if the Results are empty. - */ -- (nullable id)maxOfProperty:(NSString *)property; - -/** - Returns the sum of the values of a given property over all the objects in the collection. - - NSNumber *sum = [results sumOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose values should be summed. Only properties of - types `int`, `float`, and `double` are supported. - - @return The sum of the given property. - */ -- (NSNumber *)sumOfProperty:(NSString *)property; - -/** - Returns the average value of a given property over the objects in the collection. - - NSNumber *average = [results averageOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose average value should be calculated. Only - properties of types `int`, `float`, and `double` are supported. - - @return The average value of the given property, or `nil` if the Results are empty. - */ -- (nullable NSNumber *)averageOfProperty:(NSString *)property; - -@end - -/** - An `RLMSortDescriptor` stores a property name and a sort order for use with - `sortedResultsUsingDescriptors:`. It is similar to `NSSortDescriptor`, but supports - only the subset of functionality which can be efficiently run by Realm's query - engine. - - `RLMSortDescriptor` instances are immutable. - */ -@interface RLMSortDescriptor : NSObject - -#pragma mark - Properties - -/** - The key path which the sort descriptor orders results by. - */ -@property (nonatomic, readonly) NSString *keyPath; - -/** - Whether the descriptor sorts in ascending or descending order. - */ -@property (nonatomic, readonly) BOOL ascending; - -#pragma mark - Methods - -/** - Returns a new sort descriptor for the given key path and sort direction. - */ -+ (instancetype)sortDescriptorWithKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; - -/** - Returns a copy of the receiver with the sort direction reversed. - */ -- (instancetype)reversedSortDescriptor; - -@end - -/** - A `RLMCollectionChange` object encapsulates information about changes to collections - that are reported by Realm notifications. - - `RLMCollectionChange` is passed to the notification blocks registered with - `-addNotificationBlock` on `RLMArray` and `RLMResults`, and reports what rows in the - collection changed since the last time the notification block was called. - - The change information is available in two formats: a simple array of row - indices in the collection for each type of change, and an array of index paths - in a requested section suitable for passing directly to `UITableView`'s batch - update methods. A complete example of updating a `UITableView` named `tv`: - - [tv beginUpdates]; - [tv deleteRowsAtIndexPaths:[changes deletionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; - [tv insertRowsAtIndexPaths:[changes insertionsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; - [tv reloadRowsAtIndexPaths:[changes modificationsInSection:0] withRowAnimation:UITableViewRowAnimationAutomatic]; - [tv endUpdates]; - - All of the arrays in an `RLMCollectionChange` are always sorted in ascending order. - */ -@interface RLMCollectionChange : NSObject -/// The indices of objects in the previous version of the collection which have -/// been removed from this one. -@property (nonatomic, readonly) NSArray *deletions; - -/// The indices in the new version of the collection which were newly inserted. -@property (nonatomic, readonly) NSArray *insertions; - -/** - The indices in the new version of the collection which were modified. - - For `RLMResults`, this means that one or more of the properties of the object at - that index were modified (or an object linked to by that object was - modified). - - For `RLMArray`, the array itself being modified to contain a - different object at that index will also be reported as a modification. - */ -@property (nonatomic, readonly) NSArray *modifications; - -/// Returns the index paths of the deletion indices in the given section. -- (NSArray *)deletionsInSection:(NSUInteger)section; - -/// Returns the index paths of the insertion indices in the given section. -- (NSArray *)insertionsInSection:(NSUInteger)section; - -/// Returns the index paths of the modification indices in the given section. -- (NSArray *)modificationsInSection:(NSUInteger)section; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMCollection_Private.h b/Lesson14/Pods/Realm/include/RLMCollection_Private.h deleted file mode 100644 index eec5aea..0000000 --- a/Lesson14/Pods/Realm/include/RLMCollection_Private.h +++ /dev/null @@ -1,31 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import - -@protocol RLMFastEnumerable; - -NS_ASSUME_NONNULL_BEGIN - -void RLMCollectionSetValueForKey(id collection, NSString *key, id _Nullable value); -FOUNDATION_EXTERN NSString *RLMDescriptionWithMaxDepth(NSString *name, id collection, NSUInteger depth); -FOUNDATION_EXTERN id _Nullable (*_Nullable RLMSwiftAsFastEnumeration)(id); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMCollection_Private.hpp b/Lesson14/Pods/Realm/include/RLMCollection_Private.hpp deleted file mode 100644 index 2d13016..0000000 --- a/Lesson14/Pods/Realm/include/RLMCollection_Private.hpp +++ /dev/null @@ -1,84 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import - -namespace realm { - class List; - class Results; - class TableView; - struct CollectionChangeSet; - struct NotificationToken; -} -class RLMClassInfo; -@class RLMFastEnumerator; - -@protocol RLMFastEnumerable -@property (nonatomic, readonly) RLMRealm *realm; -@property (nonatomic, readonly) RLMClassInfo *objectInfo; -@property (nonatomic, readonly) NSUInteger count; - -- (realm::TableView)tableView; -- (RLMFastEnumerator *)fastEnumerator; -@end - -// An object which encapulates the shared logic for fast-enumerating RLMArray -// and RLMResults, and has a buffer to store strong references to the current -// set of enumerated items -@interface RLMFastEnumerator : NSObject -- (instancetype)initWithList:(realm::List&)list - collection:(id)collection - classInfo:(RLMClassInfo&)info; -- (instancetype)initWithResults:(realm::Results&)results - collection:(id)collection - classInfo:(RLMClassInfo&)info; - -// Detach this enumerator from the source collection. Must be called before the -// source collection is changed. -- (void)detach; - -- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - count:(NSUInteger)len; -@end -NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id collection); - -@interface RLMNotificationToken () -- (void)suppressNextNotification; -- (RLMRealm *)realm; -@end - -@interface RLMCancellationToken : RLMNotificationToken -- (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm; -@end - -@interface RLMCollectionChange () -- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices; -@end - -template -RLMNotificationToken *RLMAddNotificationBlock(id objcCollection, - Collection& collection, - void (^block)(id, RLMCollectionChange *, NSError *), - bool suppressInitialChange=false); - -template -NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, RLMClassInfo& info); - -std::vector> RLMSortDescriptorsToKeypathArray(NSArray *properties); diff --git a/Lesson14/Pods/Realm/include/RLMConstants.h b/Lesson14/Pods/Realm/include/RLMConstants.h deleted file mode 100644 index c4c1093..0000000 --- a/Lesson14/Pods/Realm/include/RLMConstants.h +++ /dev/null @@ -1,231 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -// For compatibility with Xcode 7, before extensible string enums were introduced, -#ifdef NS_EXTENSIBLE_STRING_ENUM -#define RLM_EXTENSIBLE_STRING_ENUM NS_EXTENSIBLE_STRING_ENUM -#define RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(_, extensible_string_enum) NS_SWIFT_NAME(extensible_string_enum) -#else -#define RLM_EXTENSIBLE_STRING_ENUM -#define RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(fully_qualified, _) NS_SWIFT_NAME(fully_qualified) -#endif - -// Swift 5 considers NS_ENUM to be "open", meaning there could be values present -// other than the defined cases (which allows adding more cases later without -// it being a breaking change), while older versions consider it "closed". -#ifdef NS_CLOSED_ENUM -#define RLM_CLOSED_ENUM NS_CLOSED_ENUM -#else -#define RLM_CLOSED_ENUM NS_ENUM -#endif - -#if __has_attribute(ns_error_domain) && (!defined(__cplusplus) || !__cplusplus || __cplusplus >= 201103L) -#define RLM_ERROR_ENUM(type, name, domain) \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wignored-attributes\"") \ - NS_ENUM(type, __attribute__((ns_error_domain(domain))) name) \ - _Pragma("clang diagnostic pop") -#else -#define RLM_ERROR_ENUM(type, name, domain) NS_ENUM(type, name) -#endif - - -#pragma mark - Enums - -/** - `RLMPropertyType` is an enumeration describing all property types supported in Realm models. - - For more information, see [Realm Models](https://realm.io/docs/objc/latest/#models). - */ -typedef RLM_CLOSED_ENUM(int32_t, RLMPropertyType) { - -#pragma mark - Primitive types - - /** Integers: `NSInteger`, `int`, `long`, `Int` (Swift) */ - RLMPropertyTypeInt = 0, - /** Booleans: `BOOL`, `bool`, `Bool` (Swift) */ - RLMPropertyTypeBool = 1, - /** Floating-point numbers: `float`, `Float` (Swift) */ - RLMPropertyTypeFloat = 5, - /** Double-precision floating-point numbers: `double`, `Double` (Swift) */ - RLMPropertyTypeDouble = 6, - -#pragma mark - Object types - - /** Strings: `NSString`, `String` (Swift) */ - RLMPropertyTypeString = 2, - /** Binary data: `NSData` */ - RLMPropertyTypeData = 3, - /** - Any object: `id`. - - This property type is no longer supported for new models. However, old files - with any-typed properties are still supported for migration purposes. - */ - RLMPropertyTypeAny = 9, - /** Dates: `NSDate` */ - RLMPropertyTypeDate = 4, - -#pragma mark - Linked object types - - /** Realm model objects. See [Realm Models](https://realm.io/docs/objc/latest/#models) for more information. */ - RLMPropertyTypeObject = 7, - /** Realm linking objects. See [Realm Models](https://realm.io/docs/objc/latest/#models) for more information. */ - RLMPropertyTypeLinkingObjects = 8, -}; - -/** An error domain identifying Realm-specific errors. */ -extern NSString * const RLMErrorDomain; - -/** An error domain identifying non-specific system errors. */ -extern NSString * const RLMUnknownSystemErrorDomain; - -/** - `RLMError` is an enumeration representing all recoverable errors. It is associated with the - Realm error domain specified in `RLMErrorDomain`. - */ -typedef RLM_ERROR_ENUM(NSInteger, RLMError, RLMErrorDomain) { - /** Denotes a general error that occurred when trying to open a Realm. */ - RLMErrorFail = 1, - - /** Denotes a file I/O error that occurred when trying to open a Realm. */ - RLMErrorFileAccess = 2, - - /** - Denotes a file permission error that ocurred when trying to open a Realm. - - This error can occur if the user does not have permission to open or create - the specified file in the specified access mode when opening a Realm. - */ - RLMErrorFilePermissionDenied = 3, - - /** Denotes an error where a file was to be written to disk, but another file with the same name already exists. */ - RLMErrorFileExists = 4, - - /** - Denotes an error that occurs if a file could not be found. - - This error may occur if a Realm file could not be found on disk when trying to open a - Realm as read-only, or if the directory part of the specified path was not found when - trying to write a copy. - */ - RLMErrorFileNotFound = 5, - - /** - Denotes an error that occurs if a file format upgrade is required to open the file, - but upgrades were explicitly disabled. - */ - RLMErrorFileFormatUpgradeRequired = 6, - - /** - Denotes an error that occurs if the database file is currently open in another - process which cannot share with the current process due to an - architecture mismatch. - - This error may occur if trying to share a Realm file between an i386 (32-bit) iOS - Simulator and the Realm Browser application. In this case, please use the 64-bit - version of the iOS Simulator. - */ - RLMErrorIncompatibleLockFile = 8, - - /** Denotes an error that occurs when there is insufficient available address space. */ - RLMErrorAddressSpaceExhausted = 9, - - /** Denotes an error that occurs if there is a schema version mismatch, so that a migration is required. */ - RLMErrorSchemaMismatch = 10, - - /** Denotes an error that occurs when attempting to open an incompatible synchronized Realm file. - - This error occurs when the Realm file was created with an older version of Realm and an automatic migration - to the current version is not possible. When such an error occurs, the original file is moved to a backup - location, and future attempts to open the synchronized Realm will result in a new file being created. - If you wish to migrate any data from the backup Realm, you can open it using the provided Realm configuration. - */ - RLMErrorIncompatibleSyncedFile = 11, - /** - Denotates an error where an operation was requested which cannot be performed on an open file. - */ - RLMErrorAlreadyOpen = 12, -}; - -#pragma mark - Constants - -#pragma mark - Notification Constants - -/** - A notification indicating that changes were made to a Realm. -*/ -typedef NSString * RLMNotification RLM_EXTENSIBLE_STRING_ENUM; - -/** - This notification is posted when a write transaction has been committed to a Realm on a different thread for - the same file. - - It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the notification has a chance - to run. - - Realms with autorefresh disabled should normally install a handler for this notification which calls - `-[RLMRealm refresh]` after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to - large Realm files. This is because an extra copy of the data must be kept for the stale Realm. - */ -extern RLMNotification const RLMRealmRefreshRequiredNotification -RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(RLMRealmRefreshRequiredNotification, RefreshRequired); - -/** - This notification is posted by a Realm when a write transaction has been - committed to a Realm on a different thread for the same file. - - It is not posted if `-[RLMRealm autorefresh]` is enabled, or if the Realm is - refreshed before the notification has a chance to run. - - Realms with autorefresh disabled should normally install a handler for this - notification which calls `-[RLMRealm refresh]` after doing some work. Refreshing - the Realm is optional, but not refreshing the Realm may lead to large Realm - files. This is because Realm must keep an extra copy of the data for the stale - Realm. - */ -extern RLMNotification const RLMRealmDidChangeNotification -RLM_EXTENSIBLE_STRING_ENUM_CASE_SWIFT_NAME(RLMRealmDidChangeNotification, DidChange); - -#pragma mark - Error keys - -/** Key to identify the associated backup Realm configuration in an error's `userInfo` dictionary */ -extern NSString * const RLMBackupRealmConfigurationErrorKey; - -#pragma mark - Other Constants - -/** The schema version used for uninitialized Realms */ -extern const uint64_t RLMNotVersioned; - -/** The corresponding value is the name of an exception thrown by Realm. */ -extern NSString * const RLMExceptionName; - -/** The corresponding value is a Realm file version. */ -extern NSString * const RLMRealmVersionKey; - -/** The corresponding key is the version of the underlying database engine. */ -extern NSString * const RLMRealmCoreVersionKey; - -/** The corresponding key is the Realm invalidated property name. */ -extern NSString * const RLMInvalidatedKey; - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMJSONModels.h b/Lesson14/Pods/Realm/include/RLMJSONModels.h deleted file mode 100644 index 82b8555..0000000 --- a/Lesson14/Pods/Realm/include/RLMJSONModels.h +++ /dev/null @@ -1,103 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 - -#import "RLMSyncUtil_Private.h" - -NS_ASSUME_NONNULL_BEGIN - -@class RLMTokenDataModel, RLMSyncUserAccountInfo; - -#pragma mark - RLMTokenModel - -@interface RLMTokenModel : NSObject RLM_SYNC_UNINITIALIZABLE - -@property (nonatomic, readonly) NSString *token; -@property (nonatomic, nullable, readonly) NSString *path; -@property (nonatomic, readonly) RLMTokenDataModel *tokenData; - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; - -@end - -#pragma mark - RLMTokenDataModel - -@interface RLMTokenDataModel : NSObject RLM_SYNC_UNINITIALIZABLE - -@property (nonatomic, readonly) NSString *identity; -@property (nonatomic, nullable, readonly) NSString *appID; -@property (nonatomic, nullable, readonly) NSString *path; -@property (nonatomic, readonly) NSTimeInterval expires; -@property (nonatomic, readonly) BOOL isAdmin; - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; - -@end - -#pragma mark - RLMAuthResponseModel - -/** - An internal class representing a valid JSON response to an auth request. - - ``` - { - "access_token": { ... } // (optional), - "refresh_token": { ... } // (optional) - } - ``` - */ -@interface RLMAuthResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE - -@property (nonatomic, readonly, nullable) RLMTokenModel *accessToken; -@property (nonatomic, readonly, nullable) RLMTokenModel *refreshToken; -@property (nonatomic, readonly, nullable) NSString *urlPrefix; - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary - requireAccessToken:(BOOL)requireAccessToken - requireRefreshToken:(BOOL)requireRefreshToken; - -@end - -#pragma mark - RLMUserInfoResponseModel - -@interface RLMUserResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE - -@property (nonatomic, readonly) NSString *identity; -@property (nonatomic, readonly) NSArray *accounts; -@property (nonatomic, readonly) NSDictionary *metadata; -@property (nonatomic, readonly) BOOL isAdmin; - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; - -@end - -#pragma mark - RLMSyncErrorResponseModel - -@interface RLMSyncErrorResponseModel : NSObject RLM_SYNC_UNINITIALIZABLE - -@property (nonatomic, readonly) NSInteger status; -@property (nonatomic, readonly) NSInteger code; -@property (nullable, nonatomic, readonly) NSString *title; -@property (nullable, nonatomic, readonly) NSString *hint; - -- (instancetype)initWithDictionary:(NSDictionary *)jsonDictionary; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMListBase.h b/Lesson14/Pods/Realm/include/RLMListBase.h deleted file mode 100644 index 7ed1988..0000000 --- a/Lesson14/Pods/Realm/include/RLMListBase.h +++ /dev/null @@ -1,42 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -@class RLMArray, RLMObjectBase, RLMResults, RLMProperty; - -NS_ASSUME_NONNULL_BEGIN - -// A base class for Swift generic Lists to make it possible to interact with -// them from obj-c -@interface RLMListBase : NSObject -@property (nonatomic, strong) RLMArray *_rlmArray; - -- (instancetype)init; -- (instancetype)initWithArray:(RLMArray *)array; -@end - -@interface RLMLinkingObjectsHandle : NSObject -- (instancetype)initWithObject:(RLMObjectBase *)object property:(RLMProperty *)property; - -@property (nonatomic, readonly) RLMResults *results; -@property (nonatomic, readonly) RLMObjectBase *parent; -@property (nonatomic, readonly) RLMProperty *property; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMMigration.h b/Lesson14/Pods/Realm/include/RLMMigration.h deleted file mode 100644 index e910c42..0000000 --- a/Lesson14/Pods/Realm/include/RLMMigration.h +++ /dev/null @@ -1,127 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMSchema; -@class RLMArray; -@class RLMObject; - -/** - A block type which provides both the old and new versions of an object in the Realm. Object - properties can only be accessed using keyed subscripting. - - @see `-[RLMMigration enumerateObjects:block:]` - - @param oldObject The object from the original Realm (read-only). - @param newObject The object from the migrated Realm (read-write). -*/ -typedef void (^RLMObjectMigrationBlock)(RLMObject * __nullable oldObject, RLMObject * __nullable newObject); - -/** - `RLMMigration` instances encapsulate information intended to facilitate a schema migration. - - A `RLMMigration` instance is passed into a user-defined `RLMMigrationBlock` block when updating - the version of a Realm. This instance provides access to the old and new database schemas, the - objects in the Realm, and provides functionality for modifying the Realm during the migration. - */ -@interface RLMMigration : NSObject - -#pragma mark - Properties - -/** - Returns the old `RLMSchema`. This is the schema which describes the Realm before the - migration is applied. - */ -@property (nonatomic, readonly) RLMSchema *oldSchema; - -/** - Returns the new `RLMSchema`. This is the schema which describes the Realm after the - migration is applied. - */ -@property (nonatomic, readonly) RLMSchema *newSchema; - - -#pragma mark - Altering Objects during a Migration - -/** - Enumerates all the objects of a given type in the Realm, providing both the old and new versions - of each object. Within the block, object properties can only be accessed using keyed subscripting. - - @param className The name of the `RLMObject` class to enumerate. - - @warning All objects returned are of a type specific to the current migration and should not be cast - to `className`. Instead, treat them as `RLMObject`s and use keyed subscripting to access - properties. - */ -- (void)enumerateObjects:(NSString *)className block:(__attribute__((noescape)) RLMObjectMigrationBlock)block; - -/** - Creates and returns an `RLMObject` instance of type `className` in the Realm being migrated. - - The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or - dictionary returned from the methods in `NSJSONSerialization`, or an array containing one element for each managed - property. An exception will be thrown if any required properties are not present and those properties were not defined - with default values. - - When passing in an `NSArray` as the `value` argument, all properties must be present, valid and in the same order as - the properties defined in the model. - - @param className The name of the `RLMObject` class to create. - @param value The value used to populate the object. - */ -- (RLMObject *)createObject:(NSString *)className withValue:(id)value; - -/** - Deletes an object from a Realm during a migration. - - It is permitted to call this method from within the block passed to `-[enumerateObjects:block:]`. - - @param object Object to be deleted from the Realm being migrated. - */ -- (void)deleteObject:(RLMObject *)object; - -/** - Deletes the data for the class with the given name. - - All objects of the given class will be deleted. If the `RLMObject` subclass no longer exists in your program, - any remaining metadata for the class will be removed from the Realm file. - - @param name The name of the `RLMObject` class to delete. - - @return A Boolean value indicating whether there was any data to delete. - */ -- (BOOL)deleteDataForClassName:(NSString *)name; - -/** - Renames a property of the given class from `oldName` to `newName`. - - @param className The name of the class whose property should be renamed. This class must be present - in both the old and new Realm schemas. - @param oldName The old name for the property to be renamed. There must not be a property with this name in the - class as defined by the new Realm schema. - @param newName The new name for the property to be renamed. There must not be a property with this name in the - class as defined by the old Realm schema. - */ -- (void)renamePropertyForClass:(NSString *)className oldName:(NSString *)oldName newName:(NSString *)newName; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMMigration_Private.h b/Lesson14/Pods/Realm/include/RLMMigration_Private.h deleted file mode 100644 index 99699e5..0000000 --- a/Lesson14/Pods/Realm/include/RLMMigration_Private.h +++ /dev/null @@ -1,40 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import -#import - -namespace realm { - class Schema; -} - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMMigration () - -@property (nonatomic, strong) RLMRealm *oldRealm; -@property (nonatomic, strong) RLMRealm *realm; - -- (instancetype)initWithRealm:(RLMRealm *)realm oldRealm:(RLMRealm *)oldRealm schema:(realm::Schema &)schema; - -- (void)execute:(RLMMigrationBlock)block; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMNetworkClient.h b/Lesson14/Pods/Realm/include/RLMNetworkClient.h deleted file mode 100644 index 7f86ff2..0000000 --- a/Lesson14/Pods/Realm/include/RLMNetworkClient.h +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMSyncUtil_Private.h" - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMNetworkRequestOptions : NSObject -@property (nonatomic, copy, nullable) NSString *authorizationHeaderName; -@property (nonatomic, copy, nullable) NSDictionary *customHeaders; -@property (nullable, nonatomic, copy) NSDictionary *pinnedCertificatePaths; -@end - -/// An abstract class representing a server endpoint. -@interface RLMSyncServerEndpoint : NSObject RLM_SYNC_UNINITIALIZABLE -+ (void)sendRequestToServer:(NSURL *)serverURL - JSON:(NSDictionary *)jsonDictionary - completion:(void (^)(NSError *))completionBlock; - -+ (void)sendRequestToServer:(NSURL *)serverURL - JSON:(NSDictionary *)jsonDictionary - timeout:(NSTimeInterval)timeout - completion:(void (^)(NSError *, NSDictionary *))completionBlock; -@end - -@interface RLMSyncAuthEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncChangePasswordEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncUpdateAccountEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncGetUserInfoEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end - -@interface RLMSyncGetPermissionsEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncGetPermissionOffersEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncApplyPermissionsEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncOfferPermissionsEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncAcceptPermissionOfferEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end -@interface RLMSyncInvalidatePermissionOfferEndpoint : RLMSyncServerEndpoint RLM_SYNC_UNINITIALIZABLE -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObject.h b/Lesson14/Pods/Realm/include/RLMObject.h deleted file mode 100644 index 23d99e5..0000000 --- a/Lesson14/Pods/Realm/include/RLMObject.h +++ /dev/null @@ -1,650 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@class RLMNotificationToken; -@class RLMObjectSchema; -@class RLMPropertyChange; -@class RLMPropertyDescriptor; -@class RLMRealm; -@class RLMResults; - -/** - `RLMObject` is a base class for model objects representing data stored in Realms. - - Define your model classes by subclassing `RLMObject` and adding properties to be managed. - Then instantiate and use your custom subclasses instead of using the `RLMObject` class directly. - - // Dog.h - @interface Dog : RLMObject - @property NSString *name; - @property BOOL adopted; - @end - - // Dog.m - @implementation Dog - @end //none needed - - ### Supported property types - - - `NSString` - - `NSInteger`, `int`, `long`, `float`, and `double` - - `BOOL` or `bool` - - `NSDate` - - `NSData` - - `NSNumber`, where `X` is one of `RLMInt`, `RLMFloat`, `RLMDouble` or `RLMBool`, for optional number properties - - `RLMObject` subclasses, to model many-to-one relationships. - - `RLMArray`, where `X` is an `RLMObject` subclass, to model many-to-many relationships. - - ### Querying - - You can initiate queries directly via the class methods: `allObjects`, `objectsWhere:`, and `objectsWithPredicate:`. - These methods allow you to easily query a custom subclass for instances of that class in the default Realm. - - To search in a Realm other than the default Realm, use the `allObjectsInRealm:`, `objectsInRealm:where:`, - and `objectsInRealm:withPredicate:` class methods. - - @see `RLMRealm` - - ### Relationships - - See our [Cocoa guide](https://realm.io/docs/objc/latest#relationships) for more details. - - ### Key-Value Observing - - All `RLMObject` properties (including properties you create in subclasses) are - [Key-Value Observing compliant](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html), - except for `realm` and `objectSchema`. - - Keep the following tips in mind when observing Realm objects: - - 1. Unlike `NSMutableArray` properties, `RLMArray` properties do not require - using the proxy object returned from `-mutableArrayValueForKey:`, or defining - KVC mutation methods on the containing class. You can simply call methods on - the `RLMArray` directly; any changes will be automatically observed by the containing - object. - 2. Unmanaged `RLMObject` instances cannot be added to a Realm while they have any - observed properties. - 3. Modifying managed `RLMObject`s within `-observeValueForKeyPath:ofObject:change:context:` - is not recommended. Properties may change even when the Realm is not in a write - transaction (for example, when `-[RLMRealm refresh]` is called after changes - are made on a different thread), and notifications sent prior to the change - being applied (when `NSKeyValueObservingOptionPrior` is used) may be sent at - times when you *cannot* begin a write transaction. - */ - -@interface RLMObject : RLMObjectBase - -#pragma mark - Creating & Initializing Objects - -/** - Creates an unmanaged instance of a Realm object. - - Call `addObject:` on an `RLMRealm` instance to add an unmanaged object into that Realm. - - @see `[RLMRealm addObject:]` - */ -- (instancetype)init NS_DESIGNATED_INITIALIZER; - - -/** - Creates an unmanaged instance of a Realm object. - - Pass in an `NSArray` or `NSDictionary` instance to set the values of the object's properties. - - Call `addObject:` on an `RLMRealm` instance to add an unmanaged object into that Realm. - - @see `[RLMRealm addObject:]` - */ -- (instancetype)initWithValue:(id)value; - - -/** - Returns the class name for a Realm object subclass. - - @warning Do not override. Realm relies on this method returning the exact class - name. - - @return The class name for the model class. - */ -+ (NSString *)className; - -/** - Creates an instance of a Realm object with a given value, and adds it to the default Realm. - - If nested objects are included in the argument, `createInDefaultRealmWithValue:` will be recursively called - on them. - - The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods in - `NSJSONSerialization`, or an array containing one element for each managed property. - - An exception will be thrown if any required properties are not present and those properties - were not defined with default values. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param value The value used to populate the object. - - @see `defaultPropertyValues` - */ -+ (instancetype)createInDefaultRealmWithValue:(id)value; - -/** - Creates an instance of a Realm object with a given value, and adds it to the specified Realm. - - If nested objects are included in the argument, `createInRealm:withValue:` will be recursively called - on them. - - The `value` argument can be a key-value coding compliant object, an array or dictionary returned from the methods in - `NSJSONSerialization`, or an array containing one element for each managed property. - - An exception will be thrown if any required properties are not present and those properties - were not defined with default values. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param realm The Realm which should manage the newly-created object. - @param value The value used to populate the object. - - @see `defaultPropertyValues` - */ -+ (instancetype)createInRealm:(RLMRealm *)realm withValue:(id)value; - -/** - Creates or updates a Realm object within the default Realm. - - This method may only be called on Realm object types with a primary key defined. If there is already - an object with the same primary key value in the default Realm, its values are updated and the object - is returned. Otherwise, this method creates and populates a new instance of the object in the default Realm. - - If nested objects are included in the argument, `createOrUpdateInDefaultRealmWithValue:` will be - recursively called on them if they have primary keys, `createInDefaultRealmWithValue:` if they do not. - - The `value` argument is used to populate the object. It can be a Realm object, a key-value coding - compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an - array containing one element for each managed property. - - If the object is being created, an exception will be thrown if any required properties - are not present and those properties were not defined with default values. - - If the `value` argument is a Realm object already managed by the default Realm, the - argument's type is the same as the receiver, and the objects have identical values for - their managed properties, this method does nothing. - - If the object is being updated, each property defined in its schema will be set by copying from - `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a - given property name (or getter name, if defined), that value will remain untouched. - Nullable properties on the object can be set to nil by using `NSNull` as the updated value. - Each property is set even if the existing value is the same as the new value being set, and - notifications will report them all being changed. See `createOrUpdateModifiedInDefaultRealmWithValue:` - for a version of this function which only sets the values which have changed. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param value The value used to populate the object. - - @see `defaultPropertyValues`, `primaryKey` - */ -+ (instancetype)createOrUpdateInDefaultRealmWithValue:(id)value; - -/** - Creates or updates a Realm object within the default Realm. - - This method may only be called on Realm object types with a primary key defined. If there is already - an object with the same primary key value in the default Realm, its values are updated and the object - is returned. Otherwise, this method creates and populates a new instance of the object in the default Realm. - - If nested objects are included in the argument, `createOrUpdateModifiedInDefaultRealmWithValue:` will be - recursively called on them if they have primary keys, `createInDefaultRealmWithValue:` if they do not. - - The `value` argument is used to populate the object. It can be a Realm object, a key-value coding - compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an - array containing one element for each managed property. - - If the object is being created, an exception will be thrown if any required properties - are not present and those properties were not defined with default values. - - If the `value` argument is a Realm object already managed by the default Realm, the - argument's type is the same as the receiver, and the objects have identical values for - their managed properties, this method does nothing. - - If the object is being updated, each property defined in its schema will be set by copying from - `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a - given property name (or getter name, if defined), that value will remain untouched. - Nullable properties on the object can be set to nil by using `NSNull` as the updated value. - Unlike `createOrUpdateInDefaultRealmWithValue:`, only properties which have changed in value are - set, and any change notifications produced by this call will report only which properies have - actually changed. - - Checking which properties have changed imposes a small amount of overhead, and so this method - may be slower when all or nearly all of the properties being set have changed. If most or all - of the properties being set have not changed, this method will be much faster than unconditionally - setting all of them, and will also reduce how much data has to be written to the Realm, saving - both i/o time and disk space. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param value The value used to populate the object. - - @see `defaultPropertyValues`, `primaryKey` - */ -+ (instancetype)createOrUpdateModifiedInDefaultRealmWithValue:(id)value; - -/** - Creates or updates an Realm object within a specified Realm. - - This method may only be called on Realm object types with a primary key defined. If there is already - an object with the same primary key value in the given Realm, its values are updated and the object - is returned. Otherwise this method creates and populates a new instance of this object in the given Realm. - - If nested objects are included in the argument, `createOrUpdateInRealm:withValue:` will be - recursively called on them if they have primary keys, `createInRealm:withValue:` if they do not. - - The `value` argument is used to populate the object. It can be a Realm object, a key-value coding - compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an - array containing one element for each managed property. - - If the object is being created, an exception will be thrown if any required properties - are not present and those properties were not defined with default values. - - If the `value` argument is a Realm object already managed by the given Realm, the - argument's type is the same as the receiver, and the objects have identical values for - their managed properties, this method does nothing. - - If the object is being updated, each property defined in its schema will be set by copying from - `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a - given property name (or getter name, if defined), that value will remain untouched. - Nullable properties on the object can be set to nil by using `NSNull` as the updated value. - Each property is set even if the existing value is the same as the new value being set, and - notifications will report them all being changed. See `createOrUpdateModifiedInRealm:withValue:` - for a version of this function which only sets the values which have changed. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param realm The Realm which should own the object. - @param value The value used to populate the object. - - @see `defaultPropertyValues`, `primaryKey` - */ -+ (instancetype)createOrUpdateInRealm:(RLMRealm *)realm withValue:(id)value; - -/** - Creates or updates an Realm object within a specified Realm. - - This method may only be called on Realm object types with a primary key defined. If there is already - an object with the same primary key value in the given Realm, its values are updated and the object - is returned. Otherwise this method creates and populates a new instance of this object in the given Realm. - - If nested objects are included in the argument, `createOrUpdateInRealm:withValue:` will be - recursively called on them if they have primary keys, `createInRealm:withValue:` if they do not. - - The `value` argument is used to populate the object. It can be a Realm object, a key-value coding - compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an - array containing one element for each managed property. - - If the object is being created, an exception will be thrown if any required properties - are not present and those properties were not defined with default values. - - If the `value` argument is a Realm object already managed by the given Realm, the - argument's type is the same as the receiver, and the objects have identical values for - their managed properties, this method does nothing. - - If the object is being updated, each property defined in its schema will be set by copying from - `value` using key-value coding. If the `value` argument does not respond to `valueForKey:` for a - given property name (or getter name, if defined), that value will remain untouched. - Nullable properties on the object can be set to nil by using `NSNull` as the updated value. - Unlike `createOrUpdateInRealm:withValue:`, only properties which have changed in value are - set, and any change notifications produced by this call will report only which properies have - actually changed. - - Checking which properties have changed imposes a small amount of overhead, and so this method - may be slower when all or nearly all of the properties being set have changed. If most or all - of the properties being set have not changed, this method will be much faster than unconditionally - setting all of them, and will also reduce how much data has to be written to the Realm, saving - both i/o time and disk space. - - If the `value` argument is an array, all properties must be present, valid and in the same - order as the properties defined in the model. - - @param realm The Realm which should own the object. - @param value The value used to populate the object. - - @see `defaultPropertyValues`, `primaryKey` - */ -+ (instancetype)createOrUpdateModifiedInRealm:(RLMRealm *)realm withValue:(id)value; - -#pragma mark - Properties - -/** - The Realm which manages the object, or `nil` if the object is unmanaged. - */ -@property (nonatomic, readonly, nullable) RLMRealm *realm; - -/** - The object schema which lists the managed properties for the object. - */ -@property (nonatomic, readonly) RLMObjectSchema *objectSchema; - -/** - Indicates if the object can no longer be accessed because it is now invalid. - - An object can no longer be accessed if the object has been deleted from the Realm that manages it, or - if `invalidate` is called on that Realm. - */ -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - - -#pragma mark - Customizing your Objects - -/** - Returns an array of property names for properties which should be indexed. - - Only string, integer, boolean, and `NSDate` properties are supported. - - @return An array of property names. - */ -+ (NSArray *)indexedProperties; - -/** - Override this method to specify the default values to be used for each property. - - @return A dictionary mapping property names to their default values. - */ -+ (nullable NSDictionary *)defaultPropertyValues; - -/** - Override this method to specify the name of a property to be used as the primary key. - - Only properties of types `RLMPropertyTypeString` and `RLMPropertyTypeInt` can be designated as the primary key. - Primary key properties enforce uniqueness for each value whenever the property is set, which incurs minor overhead. - Indexes are created automatically for primary key properties. - - @return The name of the property designated as the primary key. - */ -+ (nullable NSString *)primaryKey; - -/** - Override this method to specify the names of properties to ignore. These properties will not be managed by the Realm - that manages the object. - - @return An array of property names to ignore. - */ -+ (nullable NSArray *)ignoredProperties; - -/** - Override this method to specify the names of properties that are non-optional (i.e. cannot be assigned a `nil` value). - - By default, all properties of a type whose values can be set to `nil` are considered optional properties. - To require that an object in a Realm always store a non-`nil` value for a property, - add the name of the property to the array returned from this method. - - Properties of `RLMObject` type cannot be non-optional. Array and `NSNumber` properties - can be non-optional, but there is no reason to do so: arrays do not support storing nil, and - if you want a non-optional number you should instead use the primitive type. - - @return An array of property names that are required. - */ -+ (NSArray *)requiredProperties; - -/** - Override this method to provide information related to properties containing linking objects. - - Each property of type `RLMLinkingObjects` must have a key in the dictionary returned by this method consisting - of the property name. The corresponding value must be an instance of `RLMPropertyDescriptor` that describes the class - and property that the property is linked to. - - return @{ @"owners": [RLMPropertyDescriptor descriptorWithClass:Owner.class propertyName:@"dogs"] }; - - @return A dictionary mapping property names to `RLMPropertyDescriptor` instances. - */ -+ (NSDictionary *)linkingObjectsProperties; - - -#pragma mark - Getting & Querying Objects from the Default Realm - -/** - Returns all objects of this object type from the default Realm. - - @return An `RLMResults` containing all objects of this type in the default Realm. - */ -+ (RLMResults *)allObjects; - -/** - Returns all objects of this object type matching the given predicate from the default Realm. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return An `RLMResults` containing all objects of this type in the default Realm that match the given predicate. - */ -+ (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -+ (RLMResults<__kindof RLMObject *> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - - -/** - Returns all objects of this object type matching the given predicate from the default Realm. - - @param predicate The predicate with which to filter the objects. - - @return An `RLMResults` containing all objects of this type in the default Realm that match the given predicate. - */ -+ (RLMResults *)objectsWithPredicate:(nullable NSPredicate *)predicate; - -/** - Retrieves the single instance of this object type with the given primary key from the default Realm. - - Returns the object from the default Realm which has the given primary key, or - `nil` if the object does not exist. This is slightly faster than the otherwise - equivalent `[[SubclassName objectsWhere:@"primaryKeyPropertyName = %@", key] firstObject]`. - - This method requires that `primaryKey` be overridden on the receiving subclass. - - @return An object of this object type, or `nil` if an object with the given primary key does not exist. - @see `-primaryKey` - */ -+ (nullable instancetype)objectForPrimaryKey:(nullable id)primaryKey NS_SWIFT_NAME(object(forPrimaryKey:)); - - -#pragma mark - Querying Specific Realms - -/** - Returns all objects of this object type from the specified Realm. - - @param realm The Realm to query. - - @return An `RLMResults` containing all objects of this type in the specified Realm. - */ -+ (RLMResults *)allObjectsInRealm:(RLMRealm *)realm; - -/** - Returns all objects of this object type matching the given predicate from the specified Realm. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - @param realm The Realm to query. - - @return An `RLMResults` containing all objects of this type in the specified Realm that match the given predicate. - */ -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat, ...; - -/// :nodoc: -+ (RLMResults<__kindof RLMObject *> *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns all objects of this object type matching the given predicate from the specified Realm. - - @param predicate A predicate to use to filter the elements. - @param realm The Realm to query. - - @return An `RLMResults` containing all objects of this type in the specified Realm that match the given predicate. - */ -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm withPredicate:(nullable NSPredicate *)predicate; - -/** - Retrieves the single instance of this object type with the given primary key from the specified Realm. - - Returns the object from the specified Realm which has the given primary key, or - `nil` if the object does not exist. This is slightly faster than the otherwise - equivalent `[[SubclassName objectsInRealm:realm where:@"primaryKeyPropertyName = %@", key] firstObject]`. - - This method requires that `primaryKey` be overridden on the receiving subclass. - - @return An object of this object type, or `nil` if an object with the given primary key does not exist. - @see `-primaryKey` - */ -+ (nullable instancetype)objectInRealm:(RLMRealm *)realm forPrimaryKey:(nullable id)primaryKey NS_SWIFT_NAME(object(in:forPrimaryKey:)); - -#pragma mark - Notifications - -/** - A callback block for `RLMObject` notifications. - - If the object is deleted from the managing Realm, the block is called with - `deleted` set to `YES` and the other two arguments are `nil`. The block will - never be called again after this. - - If the object is modified, the block will be called with `deleted` set to - `NO`, a `nil` error, and an array of `RLMPropertyChange` objects which - indicate which properties of the objects were modified. - - If an error occurs, `deleted` will be `NO`, `changes` will be `nil`, and - `error` will include information about the error. The block will never be - called again after an error occurs. - */ -typedef void (^RLMObjectChangeBlock)(BOOL deleted, - NSArray *_Nullable changes, - NSError *_Nullable error); - -/** - Registers a block to be called each time the object changes. - - The block will be asynchronously called after each write transaction which - deletes the object or modifies any of the managed properties of the object, - including self-assignments that set a property to its existing value. - - For write transactions performed on different threads or in differen - processes, the block will be called when the managing Realm is - (auto)refreshed to a version including the changes, while for local write - transactions it will be called at some point in the future after the write - transaction is committed. - - Notifications are delivered via the standard run loop, and so can't be - delivered while the run loop is blocked by other activity. When notifications - can't be delivered instantly, multiple notifications may be coalesced into a - single notification. - - Unlike with `RLMArray` and `RLMResults`, there is no "initial" callback made - after you add a new notification block. - - Only objects which are managed by a Realm can be observed in this way. You - must retain the returned token for as long as you want updates to be sent to - the block. To stop receiving updates, call `-invalidate` on the token. - - It is safe to capture a strong reference to the observed object within the - callback block. There is no retain cycle due to that the callback is retained - by the returned token and not by the object itself. - - @warning This method cannot be called during a write transaction, when the - containing Realm is read-only, or on an unmanaged object. - - @param block The block to be called whenever a change occurs. - @return A token which must be held for as long as you want updates to be delivered. - */ -- (RLMNotificationToken *)addNotificationBlock:(RLMObjectChangeBlock)block; - -#pragma mark - Other Instance Methods - -/** - Returns YES if another Realm object instance points to the same object as the receiver in the Realm managing - the receiver. - - For object types with a primary, key, `isEqual:` is overridden to use the same logic as this - method (along with a corresponding implementation for `hash`). - - @param object The object to compare the receiver to. - - @return Whether the object represents the same object as the receiver. - */ -- (BOOL)isEqualToObject:(RLMObject *)object; - -#pragma mark - Dynamic Accessors - -/// :nodoc: -- (nullable id)objectForKeyedSubscript:(NSString *)key; - -/// :nodoc: -- (void)setObject:(nullable id)obj forKeyedSubscript:(NSString *)key; - -@end - -/** - Information about a specific property which changed in an `RLMObject` change notification. - */ -@interface RLMPropertyChange : NSObject - -/** - The name of the property which changed. - */ -@property (nonatomic, readonly, strong) NSString *name; - -/** - The value of the property before the change occurred. This will always be `nil` - if the change happened on the same thread as the notification and for `RLMArray` - properties. - - For object properties this will give the object which was previously linked to, - but that object will have its new values and not the values it had before the - changes. This means that `previousValue` may be a deleted object, and you will - need to check `invalidated` before accessing any of its properties. - */ -@property (nonatomic, readonly, strong, nullable) id previousValue; - -/** - The value of the property after the change occurred. This will always be `nil` - for `RLMArray` properties. - */ -@property (nonatomic, readonly, strong, nullable) id value; -@end - -#pragma mark - RLMArray Property Declaration - -/** - Properties on `RLMObject`s of type `RLMArray` must have an associated type. A type is associated - with an `RLMArray` property by defining a protocol for the object type that the array should contain. - To define the protocol for an object, you can use the macro RLM_ARRAY_TYPE: - - RLM_ARRAY_TYPE(ObjectType) - ... - @property RLMArray *arrayOfObjectTypes; - */ -#define RLM_ARRAY_TYPE(RLM_OBJECT_SUBCLASS)\ -@protocol RLM_OBJECT_SUBCLASS \ -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectBase.h b/Lesson14/Pods/Realm/include/RLMObjectBase.h deleted file mode 100644 index de40598..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectBase.h +++ /dev/null @@ -1,44 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMRealm; -@class RLMSchema; -@class RLMObjectSchema; - -/// :nodoc: -@interface RLMObjectBase : NSObject - -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - -- (instancetype)init NS_DESIGNATED_INITIALIZER; - -+ (NSString *)className; - -// Returns whether the class is included in the default set of classes managed by a Realm. -+ (BOOL)shouldIncludeInDefaultSchema; - -+ (nullable NSString *)_realmObjectName; -+ (nullable NSDictionary *)_realmColumnNames; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectBase_Dynamic.h b/Lesson14/Pods/Realm/include/RLMObjectBase_Dynamic.h deleted file mode 100644 index 55f64ef..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectBase_Dynamic.h +++ /dev/null @@ -1,82 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -@class RLMObjectSchema, RLMRealm; - -NS_ASSUME_NONNULL_BEGIN - -/** - Returns the Realm that manages the object, if one exists. - - @warning This function is useful only in specialized circumstances, for example, when building components - that integrate with Realm. If you are simply building an app on Realm, it is - recommended to retrieve the Realm that manages the object via `RLMObject`. - - @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. - - @return The Realm which manages this object. Returns `nil `for unmanaged objects. - */ -FOUNDATION_EXTERN RLMRealm * _Nullable RLMObjectBaseRealm(RLMObjectBase * _Nullable object); - -/** - Returns an `RLMObjectSchema` which describes the managed properties of the object. - - @warning This function is useful only in specialized circumstances, for example, when building components - that integrate with Realm. If you are simply building an app on Realm, it is - recommended to retrieve `objectSchema` via `RLMObject`. - - @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. - - @return The object schema which lists the managed properties for the object. - */ -FOUNDATION_EXTERN RLMObjectSchema * _Nullable RLMObjectBaseObjectSchema(RLMObjectBase * _Nullable object); - -/** - Returns the object corresponding to a key value. - - @warning This function is useful only in specialized circumstances, for example, when building components - that integrate with Realm. If you are simply building an app on Realm, it is - recommended to retrieve key values via `RLMObject`. - - @warning Will throw an `NSUndefinedKeyException` if `key` is not present on the object. - - @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. - @param key The name of the property. - - @return The object for the property requested. - */ -FOUNDATION_EXTERN id _Nullable RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase * _Nullable object, NSString *key); - -/** - Sets a value for a key on the object. - - @warning This function is useful only in specialized circumstances, for example, when building components - that integrate with Realm. If you are simply building an app on Realm, it is - recommended to set key values via `RLMObject`. - - @warning Will throw an `NSUndefinedKeyException` if `key` is not present on the object. - - @param object An `RLMObjectBase` obtained via a Swift `Object` or `RLMObject`. - @param key The name of the property. - @param obj The object to set as the value of the key. - */ -FOUNDATION_EXTERN void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase * _Nullable object, NSString *key, id _Nullable obj); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectBase_Private.h b/Lesson14/Pods/Realm/include/RLMObjectBase_Private.h deleted file mode 100644 index 74a54f1..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectBase_Private.h +++ /dev/null @@ -1,30 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 - -@class RLMArray; - -NS_ASSUME_NONNULL_BEGIN - -// RLMObjectBase private -@interface RLMObjectBase () -+ (void)initializeLinkedObjectSchemas; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectSchema.h b/Lesson14/Pods/Realm/include/RLMObjectSchema.h deleted file mode 100644 index 83a7d84..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectSchema.h +++ /dev/null @@ -1,72 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMProperty; - -/** - This class represents Realm model object schemas. - - When using Realm, `RLMObjectSchema` instances allow performing migrations and - introspecting the database's schema. - - Object schemas map to tables in the core database. - */ -@interface RLMObjectSchema : NSObject - -#pragma mark - Properties - -/** - An array of `RLMProperty` instances representing the managed properties of a class described by the schema. - - @see `RLMProperty` - */ -@property (nonatomic, readonly, copy) NSArray *properties; - -/** - The name of the class the schema describes. - */ -@property (nonatomic, readonly) NSString *className; - -/** - The property which serves as the primary key for the class the schema describes, if any. - */ -@property (nonatomic, readonly, nullable) RLMProperty *primaryKeyProperty; - -#pragma mark - Methods - -/** - Retrieves an `RLMProperty` object by the property name. - - @param propertyName The property's name. - - @return An `RLMProperty` object, or `nil` if there is no property with the given name. - */ -- (nullable RLMProperty *)objectForKeyedSubscript:(NSString *)propertyName; - -/** - Returns whether two `RLMObjectSchema` instances are equal. - */ -- (BOOL)isEqualToObjectSchema:(RLMObjectSchema *)objectSchema; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.h b/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.h deleted file mode 100644 index deca77d..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.h +++ /dev/null @@ -1,71 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import - -NS_ASSUME_NONNULL_BEGIN - -// RLMObjectSchema private -@interface RLMObjectSchema () { -@public - bool _isSwiftClass; -} - -/// The object type name reported to the object store and core. -@property (nonatomic, readonly) NSString *objectName; - -// writable redeclaration -@property (nonatomic, readwrite, copy) NSArray *properties; -@property (nonatomic, readwrite, assign) bool isSwiftClass; - -// class used for this object schema -@property (nonatomic, readwrite, assign) Class objectClass; -@property (nonatomic, readwrite, assign) Class accessorClass; -@property (nonatomic, readwrite, assign) Class unmanagedClass; - -@property (nonatomic, readwrite, nullable) RLMProperty *primaryKeyProperty; - -@property (nonatomic, copy) NSArray *computedProperties; -@property (nonatomic, readonly) NSArray *swiftGenericProperties; - -// returns a cached or new schema for a given object class -+ (instancetype)schemaForObjectClass:(Class)objectClass; -@end - -@interface RLMObjectSchema (Dynamic) -/** - This method is useful only in specialized circumstances, for example, when accessing objects - in a Realm produced externally. If you are simply building an app on Realm, it is not recommended - to use this method as an [RLMObjectSchema](RLMObjectSchema) is generated automatically for every [RLMObject](RLMObject) subclass. - - Initialize an RLMObjectSchema with classname, objectClass, and an array of properties - - @warning This method is useful only in specialized circumstances. - - @param objectClassName The name of the class used to refer to objects of this type. - @param objectClass The Objective-C class used when creating instances of this type. - @param properties An array of RLMProperty instances describing the managed properties for this type. - - @return An initialized instance of RLMObjectSchema. - */ -- (instancetype)initWithClassName:(NSString *)objectClassName objectClass:(Class)objectClass properties:(NSArray *)properties; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.hpp b/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.hpp deleted file mode 100644 index cb00dc8..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectSchema_Private.hpp +++ /dev/null @@ -1,32 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObjectSchema_Private.h" - -namespace realm { - class ObjectSchema; -} -@class RLMSchema; - -@interface RLMObjectSchema () -// create realm::ObjectSchema copy -- (realm::ObjectSchema)objectStoreCopy:(RLMSchema *)schema; - -// initialize with realm::ObjectSchema -+ (instancetype)objectSchemaForObjectStoreSchema:(realm::ObjectSchema const&)objectSchema; -@end diff --git a/Lesson14/Pods/Realm/include/RLMObjectStore.h b/Lesson14/Pods/Realm/include/RLMObjectStore.h deleted file mode 100644 index fb431d7..0000000 --- a/Lesson14/Pods/Realm/include/RLMObjectStore.h +++ /dev/null @@ -1,93 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#ifdef __cplusplus -extern "C" { -#endif - -@class RLMRealm, RLMSchema, RLMObjectBase, RLMResults, RLMProperty; - -typedef NS_ENUM(NSUInteger, RLMUpdatePolicy) { - RLMUpdatePolicyError = 1, - RLMUpdatePolicyUpdateChanged = 3, - RLMUpdatePolicyUpdateAll = 2, -}; - -NS_ASSUME_NONNULL_BEGIN - -void RLMVerifyHasPrimaryKey(Class cls); - -// -// Accessor Creation -// - -// create or get cached accessors for the given schema -void RLMRealmCreateAccessors(RLMSchema *schema); - - -// -// Adding, Removing, Getting Objects -// - -// add an object to the given realm -void RLMAddObjectToRealm(RLMObjectBase *object, RLMRealm *realm, RLMUpdatePolicy); - -// delete an object from its realm -void RLMDeleteObjectFromRealm(RLMObjectBase *object, RLMRealm *realm); - -// deletes all objects from a realm -void RLMDeleteAllObjectsFromRealm(RLMRealm *realm); - -// get objects of a given class -RLMResults *RLMGetObjects(RLMRealm *realm, NSString *objectClassName, NSPredicate * _Nullable predicate) -NS_RETURNS_RETAINED; - -// get an object with the given primary key -id _Nullable RLMGetObject(RLMRealm *realm, NSString *objectClassName, id _Nullable key) NS_RETURNS_RETAINED; - -// create object from array or dictionary -RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className, - id _Nullable value, RLMUpdatePolicy updatePolicy) -NS_RETURNS_RETAINED; - -// -// Accessor Creation -// - - -// switch List<> properties from being backed by unmanaged RLMArrays to RLMManagedArray -void RLMInitializeSwiftAccessorGenerics(RLMObjectBase *object); - -#ifdef __cplusplus -} - -namespace realm { - class Table; - template class BasicRowExpr; - using RowExpr = BasicRowExpr; -} -class RLMClassInfo; - -// Create accessors -RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, NSUInteger index) NS_RETURNS_RETAINED; -RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, realm::RowExpr row) NS_RETURNS_RETAINED; -#endif - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObject_Private.h b/Lesson14/Pods/Realm/include/RLMObject_Private.h deleted file mode 100644 index 430051a..0000000 --- a/Lesson14/Pods/Realm/include/RLMObject_Private.h +++ /dev/null @@ -1,72 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMProperty, RLMArray; -typedef NS_ENUM(int32_t, RLMPropertyType); - -FOUNDATION_EXTERN void RLMInitializeWithValue(RLMObjectBase *, id, RLMSchema *); - -// RLMObject accessor and read/write realm -@interface RLMObjectBase () { -@public - RLMRealm *_realm; - __unsafe_unretained RLMObjectSchema *_objectSchema; -} - -// shared schema for this class -+ (nullable RLMObjectSchema *)sharedSchema; - -+ (nullable NSArray *)_getPropertiesWithInstance:(id)obj; -+ (bool)_realmIgnoreClass; - -@end - -@interface RLMDynamicObject : RLMObject - -@end - -// Calls valueForKey: and re-raises NSUndefinedKeyExceptions -FOUNDATION_EXTERN id _Nullable RLMValidatedValueForProperty(id object, NSString *key, NSString *className); - -// Compare two RLObjectBases -FOUNDATION_EXTERN BOOL RLMObjectBaseAreEqual(RLMObjectBase * _Nullable o1, RLMObjectBase * _Nullable o2); - -typedef void (^RLMObjectNotificationCallback)(NSArray *_Nullable propertyNames, - NSArray *_Nullable oldValues, - NSArray *_Nullable newValues, - NSError *_Nullable error); -FOUNDATION_EXTERN RLMNotificationToken *RLMObjectAddNotificationBlock(RLMObjectBase *obj, RLMObjectNotificationCallback block); - -// Returns whether the class is a descendent of RLMObjectBase -FOUNDATION_EXTERN BOOL RLMIsObjectOrSubclass(Class klass); - -// Returns whether the class is an indirect descendant of RLMObjectBase -FOUNDATION_EXTERN BOOL RLMIsObjectSubclass(Class klass); - -FOUNDATION_EXTERN const NSUInteger RLMDescriptionMaxDepth; - -@interface RLMManagedPropertyAccessor : NSObject -+ (void)initializeObject:(void *)object parent:(RLMObjectBase *)parent property:(RLMProperty *)property; -+ (id)get:(void *)pointer; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMObject_Private.hpp b/Lesson14/Pods/Realm/include/RLMObject_Private.hpp deleted file mode 100644 index 3113961..0000000 --- a/Lesson14/Pods/Realm/include/RLMObject_Private.hpp +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMObject_Private.h" - -#import "RLMRealm_Private.hpp" -#import "RLMUtil.hpp" - -#import // required by row.hpp -#import - -class RLMObservationInfo; - -// RLMObject accessor and read/write realm -@interface RLMObjectBase () { - @public - realm::Row _row; - RLMObservationInfo *_observationInfo; - RLMClassInfo *_info; -} -@end - -id RLMCreateManagedAccessor(Class cls, RLMClassInfo *info) NS_RETURNS_RETAINED; - -// throw an exception if the object is invalidated or on the wrong thread -static inline void RLMVerifyAttached(__unsafe_unretained RLMObjectBase *const obj) { - if (!obj->_row.is_attached()) { - @throw RLMException(@"Object has been deleted or invalidated."); - } - [obj->_realm verifyThread]; -} - -// throw an exception if the object can't be modified for any reason -static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMObjectBase *const obj) { - // first verify is attached - RLMVerifyAttached(obj); - - if (!obj->_realm.inWriteTransaction) { - @throw RLMException(@"Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first."); - } -} diff --git a/Lesson14/Pods/Realm/include/RLMObservation.hpp b/Lesson14/Pods/Realm/include/RLMObservation.hpp deleted file mode 100644 index 0f5b215..0000000 --- a/Lesson14/Pods/Realm/include/RLMObservation.hpp +++ /dev/null @@ -1,153 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 - -#import "binding_context.hpp" - -#import -#import - -#import - -@class RLMObjectBase, RLMRealm, RLMSchema, RLMProperty, RLMObjectSchema; -class RLMClassInfo; -class RLMSchemaInfo; - -namespace realm { - class History; - class SharedGroup; -} - -// RLMObservationInfo stores all of the KVO-related data for RLMObjectBase and -// RLMArray. There is a one-to-one relationship between observed objects and -// RLMObservationInfo instances, so it could be folded into RLMObjectBase, and -// is a separate class mostly to avoid making all accessor objects far larger. -// -// RLMClassInfo stores a vector of pointers to the first observation info -// created for each row. If there are multiple observation infos for a single -// row (such as if there are multiple observed objects backed by a single row, -// or if both an object and an array property of that object are observed), -// they're stored in an intrusive doubly-linked-list in the `next` and `prev` -// members. This is done primarily to make it simpler and faster to loop over -// all of the observed objects for a single row, as that needs to be done for -// every change. -class RLMObservationInfo { -public: - RLMObservationInfo(id object); - RLMObservationInfo(RLMClassInfo &objectSchema, std::size_t row, id object); - ~RLMObservationInfo(); - - realm::Row const& getRow() const { - return row; - } - - NSString *columnName(size_t col) const noexcept; - - // Send willChange/didChange notifications to all observers for this object/row - // Sends the array versions if indexes is non-nil, normal versions otherwise - void willChange(NSString *key, NSKeyValueChange kind=NSKeyValueChangeSetting, NSIndexSet *indexes=nil) const; - void didChange(NSString *key, NSKeyValueChange kind=NSKeyValueChangeSetting, NSIndexSet *indexes=nil) const; - - bool isForRow(size_t ndx) const { - return row && row.get_index() == ndx; - } - - void recordObserver(realm::Row& row, RLMClassInfo *objectInfo, RLMObjectSchema *objectSchema, NSString *keyPath); - void removeObserver(); - bool hasObservers() const { return observerCount > 0; } - - // valueForKey: on observed object and array properties needs to return the - // same object each time for KVO to work at all. Doing this all the time - // requires some odd semantics to avoid reference cycles, so instead we do - // it only to the extent specifically required by KVO. In addition, we - // need to continue to return the same object even if this row is deleted, - // or deleting an object with active observers will explode horribly. - // Once prepareForInvalidation() is called, valueForKey() will always return - // the cached value for object and array properties without checking the - // backing row to verify it's up-to-date. - // - // prepareForInvalidation() must be called on the head of the linked list - // (i.e. on the object pointed to directly by the object schema) - id valueForKey(NSString *key); - - void prepareForInvalidation(); - -private: - // Doubly-linked-list of observed objects for the same row as this - RLMObservationInfo *next = nullptr; - RLMObservationInfo *prev = nullptr; - - // Row being observed - realm::Row row; - RLMClassInfo *objectSchema = nullptr; - - // Object doing the observing - __unsafe_unretained id object = nil; - - // valueForKey: hack - bool invalidated = false; - size_t observerCount = 0; - NSString *lastKey = nil; - __unsafe_unretained RLMProperty *lastProp = nil; - - // objects returned from valueForKey() to keep them alive in case observers - // are added and so that they can still be accessed after row is detached - NSMutableDictionary *cachedObjects; - - void setRow(realm::Table &table, size_t newRow); - - template - void forEach(F&& f) const { - // The user's observation handler may release their last reference to - // the object being observed, which will result in the RLMObservationInfo - // being destroyed. As a result, we need to retain the object which owns - // both `this` and the current info we're looking at. - __attribute__((objc_precise_lifetime)) id self = object, current; - for (auto info = prev; info; info = info->prev) { - current = info->object; - f(info->object); - } - for (auto info = this; info; info = info->next) { - current = info->object; - f(info->object); - } - } - - // Default move/copy constructors don't work due to the intrusive linked - // list and we don't need them - RLMObservationInfo(RLMObservationInfo const&) = delete; - RLMObservationInfo(RLMObservationInfo&&) = delete; - RLMObservationInfo& operator=(RLMObservationInfo const&) = delete; - RLMObservationInfo& operator=(RLMObservationInfo&&) = delete; -}; - -// Get the the observation info chain for the given row -// Will simply return info if it's non-null, and will search ojectSchema's array -// for a matching one otherwise, and return null if there are none -RLMObservationInfo *RLMGetObservationInfo(RLMObservationInfo *info, size_t row, RLMClassInfo& objectSchema); - -// delete all objects from a single table with change notifications -void RLMClearTable(RLMClassInfo &realm); - -// invoke the block, sending notifications for cascading deletes/link nullifications -void RLMTrackDeletions(RLMRealm *realm, dispatch_block_t block); - -std::vector RLMGetObservedRows(RLMSchemaInfo const& schema); -void RLMWillChange(std::vector const& observed, std::vector const& invalidated); -void RLMDidChange(std::vector const& observed, std::vector const& invalidated); diff --git a/Lesson14/Pods/Realm/include/RLMOptionalBase.h b/Lesson14/Pods/Realm/include/RLMOptionalBase.h deleted file mode 100644 index d5b2430..0000000 --- a/Lesson14/Pods/Realm/include/RLMOptionalBase.h +++ /dev/null @@ -1,36 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 -#import - -NS_ASSUME_NONNULL_BEGIN - -@class RLMObjectBase, RLMProperty; - -@interface RLMOptionalBase : NSProxy -- (instancetype)init; -@end - -FOUNDATION_EXTERN id _Nullable RLMGetOptional(RLMOptionalBase *); -FOUNDATION_EXTERN void RLMSetOptional(RLMOptionalBase *, id _Nullable); - -void RLMInitializeManagedOptional(RLMOptionalBase *, RLMObjectBase *parent, RLMProperty *prop); -void RLMInitializeUnmanagedOptional(RLMOptionalBase *, RLMObjectBase *parent, RLMProperty *prop); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMPlatform.h b/Lesson14/Pods/Realm/include/RLMPlatform.h deleted file mode 100644 index 8b13789..0000000 --- a/Lesson14/Pods/Realm/include/RLMPlatform.h +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Lesson14/Pods/Realm/include/RLMPredicateUtil.hpp b/Lesson14/Pods/Realm/include/RLMPredicateUtil.hpp deleted file mode 100644 index 71426de..0000000 --- a/Lesson14/Pods/Realm/include/RLMPredicateUtil.hpp +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 -#import - -using ExpressionVisitor = std::function; -NSPredicate *transformPredicate(NSPredicate *, ExpressionVisitor); diff --git a/Lesson14/Pods/Realm/include/RLMPrefix.h b/Lesson14/Pods/Realm/include/RLMPrefix.h deleted file mode 100644 index df08ce9..0000000 --- a/Lesson14/Pods/Realm/include/RLMPrefix.h +++ /dev/null @@ -1,35 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -#ifdef __OBJC__ -#import -#endif - -#ifdef __cplusplus -#import -#import -#import -#import -#import - -#import -#import -#import -#import -#import -#endif diff --git a/Lesson14/Pods/Realm/include/RLMProperty.h b/Lesson14/Pods/Realm/include/RLMProperty.h deleted file mode 100644 index a2bc894..0000000 --- a/Lesson14/Pods/Realm/include/RLMProperty.h +++ /dev/null @@ -1,126 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -/// :nodoc: -@protocol RLMInt @end -/// :nodoc: -@protocol RLMBool @end -/// :nodoc: -@protocol RLMDouble @end -/// :nodoc: -@protocol RLMFloat @end -/// :nodoc: -@protocol RLMString @end -/// :nodoc: -@protocol RLMDate @end -/// :nodoc: -@protocol RLMData @end - -/// :nodoc: -@interface NSNumber () -@end - -/** - `RLMProperty` instances represent properties managed by a Realm in the context - of an object schema. Such properties may be persisted to a Realm file or - computed from other data from the Realm. - - When using Realm, `RLMProperty` instances allow performing migrations and - introspecting the database's schema. - - These property instances map to columns in the core database. - */ -@interface RLMProperty : NSObject - -#pragma mark - Properties - -/** - The name of the property. - */ -@property (nonatomic, readonly) NSString *name; - -/** - The type of the property. - - @see `RLMPropertyType` - */ -@property (nonatomic, readonly) RLMPropertyType type; - -/** - Indicates whether this property is indexed. - - @see `RLMObject` - */ -@property (nonatomic, readonly) BOOL indexed; - -/** - For `RLMObject` and `RLMArray` properties, the name of the class of object stored in the property. - */ -@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; - -/** - For linking objects properties, the property name of the property the linking objects property is linked to. - */ -@property (nonatomic, readonly, copy, nullable) NSString *linkOriginPropertyName; - -/** - Indicates whether this property is optional. - */ -@property (nonatomic, readonly) BOOL optional; - -/** - Indicates whether this property is an array. - */ -@property (nonatomic, readonly) BOOL array; - -#pragma mark - Methods - -/** - Returns whether a given property object is equal to the receiver. - */ -- (BOOL)isEqualToProperty:(RLMProperty *)property; - -@end - - -/** - An `RLMPropertyDescriptor` instance represents a specific property on a given class. - */ -@interface RLMPropertyDescriptor : NSObject - -/** - Creates and returns a property descriptor. - - @param objectClass The class of this property descriptor. - @param propertyName The name of this property descriptor. - */ -+ (instancetype)descriptorWithClass:(Class)objectClass propertyName:(NSString *)propertyName; - -/// The class of the property. -@property (nonatomic, readonly) Class objectClass; - -/// The name of the property. -@property (nonatomic, readonly) NSString *propertyName; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMProperty_Private.h b/Lesson14/Pods/Realm/include/RLMProperty_Private.h deleted file mode 100644 index 5829f7e..0000000 --- a/Lesson14/Pods/Realm/include/RLMProperty_Private.h +++ /dev/null @@ -1,128 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import - -@class RLMObjectBase; - -NS_ASSUME_NONNULL_BEGIN - -BOOL RLMPropertyTypeIsComputed(RLMPropertyType propertyType); -FOUNDATION_EXTERN void RLMValidateSwiftPropertyName(NSString *name); - -// Translate an rlmtype to a string representation -static inline NSString *RLMTypeToString(RLMPropertyType type) { - switch (type) { - case RLMPropertyTypeString: - return @"string"; - case RLMPropertyTypeInt: - return @"int"; - case RLMPropertyTypeBool: - return @"bool"; - case RLMPropertyTypeDate: - return @"date"; - case RLMPropertyTypeData: - return @"data"; - case RLMPropertyTypeDouble: - return @"double"; - case RLMPropertyTypeFloat: - return @"float"; - case RLMPropertyTypeAny: - return @"any"; - case RLMPropertyTypeObject: - return @"object"; - case RLMPropertyTypeLinkingObjects: - return @"linking objects"; - } - return @"Unknown"; -} - -// private property interface -@interface RLMProperty () { -@public - RLMPropertyType _type; - Ivar _swiftIvar; -} - -- (instancetype)initWithName:(NSString *)name - indexed:(BOOL)indexed - linkPropertyDescriptor:(nullable RLMPropertyDescriptor *)linkPropertyDescriptor - property:(objc_property_t)property; - -- (instancetype)initSwiftPropertyWithName:(NSString *)name - indexed:(BOOL)indexed - linkPropertyDescriptor:(nullable RLMPropertyDescriptor *)linkPropertyDescriptor - property:(objc_property_t)property - instance:(RLMObjectBase *)objectInstance; - -- (void)updateAccessors; - -// private setters -@property (nonatomic, readwrite) NSString *name; -@property (nonatomic, readwrite, assign) RLMPropertyType type; -@property (nonatomic, readwrite) BOOL indexed; -@property (nonatomic, readwrite) BOOL optional; -@property (nonatomic, readwrite) BOOL array; -@property (nonatomic, copy, nullable) NSString *objectClassName; -@property (nonatomic, copy, nullable) NSString *linkOriginPropertyName; - -// private properties -@property (nonatomic, readwrite, nullable) NSString *columnName; -@property (nonatomic, assign) NSUInteger index; -@property (nonatomic, assign) BOOL isPrimary; -@property (nonatomic, assign, nullable) Ivar swiftIvar; -@property (nonatomic, assign, nullable) Class swiftAccessor; - -// getter and setter names -@property (nonatomic, copy) NSString *getterName; -@property (nonatomic, copy) NSString *setterName; -@property (nonatomic) SEL getterSel; -@property (nonatomic) SEL setterSel; - -- (RLMProperty *)copyWithNewName:(NSString *)name; - -@end - -@interface RLMProperty (Dynamic) -/** - This method is useful only in specialized circumstances, for example, in conjunction with - +[RLMObjectSchema initWithClassName:objectClass:properties:]. If you are simply building an - app on Realm, it is not recommened to use this method. - - Initialize an RLMProperty - - @warning This method is useful only in specialized circumstances. - - @param name The property name. - @param type The property type. - @param objectClassName The object type used for Object and Array types. - @param linkOriginPropertyName The property name of the origin of a link. Used for linking objects properties. - - @return An initialized instance of RLMProperty. - */ -- (instancetype)initWithName:(NSString *)name - type:(RLMPropertyType)type - objectClassName:(nullable NSString *)objectClassName - linkOriginPropertyName:(nullable NSString *)linkOriginPropertyName - indexed:(BOOL)indexed - optional:(BOOL)optional; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMProperty_Private.hpp b/Lesson14/Pods/Realm/include/RLMProperty_Private.hpp deleted file mode 100644 index cf8b17a..0000000 --- a/Lesson14/Pods/Realm/include/RLMProperty_Private.hpp +++ /dev/null @@ -1,33 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -namespace realm { - struct Property; -} - -@class RLMSchema; - -@interface RLMProperty () - -+ (instancetype)propertyForObjectStoreProperty:(const realm::Property&)property; - -- (realm::Property)objectStoreCopy:(RLMSchema *)schema; - -@end diff --git a/Lesson14/Pods/Realm/include/RLMQueryUtil.hpp b/Lesson14/Pods/Realm/include/RLMQueryUtil.hpp deleted file mode 100644 index 12df76e..0000000 --- a/Lesson14/Pods/Realm/include/RLMQueryUtil.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import - -namespace realm { - class Group; - class Query; - class SortDescriptor; -} - -@class RLMObjectSchema, RLMProperty, RLMSchema, RLMSortDescriptor; -class RLMClassInfo; - -extern NSString * const RLMPropertiesComparisonTypeMismatchException; -extern NSString * const RLMUnsupportedTypesFoundInPropertyComparisonException; - -realm::Query RLMPredicateToQuery(NSPredicate *predicate, RLMObjectSchema *objectSchema, - RLMSchema *schema, realm::Group &group); - -// return property - throw for invalid column name -RLMProperty *RLMValidatedProperty(RLMObjectSchema *objectSchema, NSString *columnName); diff --git a/Lesson14/Pods/Realm/include/RLMRealm+Sync.h b/Lesson14/Pods/Realm/include/RLMRealm+Sync.h deleted file mode 100644 index 42f1616..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealm+Sync.h +++ /dev/null @@ -1,47 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 - -#import "RLMRealm.h" - -@class RLMResults, RLMSyncSession; - -/** - A callback used to vend the results of a partial sync fetch. - */ -typedef void(^RLMPartialSyncFetchCallback)(RLMResults * _Nullable results, NSError * _Nullable error); - -NS_ASSUME_NONNULL_BEGIN - -/// -@interface RLMRealm (Sync) - -/// :nodoc: -- (void)subscribeToObjects:(Class)type where:(NSString *)query callback:(RLMPartialSyncFetchCallback)callback -__attribute__((unavailable("Use -[RLMResults subscribe]"))); - -/** - Get the RLMSyncSession used by this Realm. Will be nil if this is not a - synchronized Realm. -*/ -@property (nonatomic, nullable, readonly) RLMSyncSession *syncSession; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealm.h b/Lesson14/Pods/Realm/include/RLMRealm.h deleted file mode 100644 index cbc99ce..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealm.h +++ /dev/null @@ -1,796 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import "RLMConstants.h" - -@class RLMRealmConfiguration, RLMRealm, RLMObject, RLMSchema, RLMMigration, RLMNotificationToken, RLMThreadSafeReference, RLMAsyncOpenTask; -struct RLMRealmPrivileges; -struct RLMClassPrivileges; -struct RLMObjectPrivileges; - -/** - A callback block for opening Realms asynchronously. - - Returns the Realm if the open was successful, or an error otherwise. - */ -typedef void(^RLMAsyncOpenRealmCallback)(RLMRealm * _Nullable realm, NSError * _Nullable error); - -NS_ASSUME_NONNULL_BEGIN - -/** - An `RLMRealm` instance (also referred to as "a Realm") represents a Realm - database. - - Realms can either be stored on disk (see `+[RLMRealm realmWithURL:]`) or in - memory (see `RLMRealmConfiguration`). - - `RLMRealm` instances are cached internally, and constructing equivalent `RLMRealm` - objects (for example, by using the same path or identifier) multiple times on a single thread - within a single iteration of the run loop will normally return the same - `RLMRealm` object. - - If you specifically want to ensure an `RLMRealm` instance is - destroyed (for example, if you wish to open a Realm, check some property, and - then possibly delete the Realm file and re-open it), place the code which uses - the Realm within an `@autoreleasepool {}` and ensure you have no other - strong references to it. - - @warning `RLMRealm` instances are not thread safe and cannot be shared across - threads or dispatch queues. Trying to do so will cause an exception to be thrown. - You must call this method on each thread you want - to interact with the Realm on. For dispatch queues, this means that you must - call it in each block which is dispatched, as a queue is not guaranteed to run - all of its blocks on the same thread. - */ - -@interface RLMRealm : NSObject - -#pragma mark - Creating & Initializing a Realm - -/** - Obtains an instance of the default Realm. - - The default Realm is used by the `RLMObject` class methods - which do not take an `RLMRealm` parameter, but is otherwise not special. The - default Realm is persisted as *default.realm* under the *Documents* directory of - your Application on iOS, and in your application's *Application Support* - directory on OS X. - - The default Realm is created using the default `RLMRealmConfiguration`, which - can be changed via `+[RLMRealmConfiguration setDefaultConfiguration:]`. - - @return The default `RLMRealm` instance for the current thread. - */ -+ (instancetype)defaultRealm; - -/** - Obtains an `RLMRealm` instance with the given configuration. - - @param configuration A configuration object to use when creating the Realm. - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return An `RLMRealm` instance. - */ -+ (nullable instancetype)realmWithConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; - -/** - Obtains an `RLMRealm` instance persisted at a specified file URL. - - @param fileURL The local URL of the file the Realm should be saved at. - - @return An `RLMRealm` instance. - */ -+ (instancetype)realmWithURL:(NSURL *)fileURL; - -/** - Asynchronously open a Realm and deliver it to a block on the given queue. - - Opening a Realm asynchronously will perform all work needed to get the Realm to - a usable state (such as running potentially time-consuming migrations) on a - background thread before dispatching to the given queue. In addition, - synchronized Realms wait for all remote content available at the time the - operation began to be downloaded and available locally. - - @param configuration A configuration object to use when opening the Realm. - @param callbackQueue The dispatch queue on which the callback should be run. - @param callback A callback block. If the Realm was successfully opened, - it will be passed in as an argument. - Otherwise, an `NSError` describing what went wrong will be - passed to the block instead. - - @note The returned Realm is confined to the thread on which it was created. - Because GCD does not guarantee that queues will always use the same - thread, accessing the returned Realm outside the callback block (even if - accessed from `callbackQueue`) is unsafe. - */ -+ (RLMAsyncOpenTask *)asyncOpenWithConfiguration:(RLMRealmConfiguration *)configuration - callbackQueue:(dispatch_queue_t)callbackQueue - callback:(RLMAsyncOpenRealmCallback)callback; - -/** - The `RLMSchema` used by the Realm. - */ -@property (nonatomic, readonly) RLMSchema *schema; - -/** - Indicates if the Realm is currently engaged in a write transaction. - - @warning Do not simply check this property and then start a write transaction whenever an object needs to be - created, updated, or removed. Doing so might cause a large number of write transactions to be created, - degrading performance. Instead, always prefer performing multiple updates during a single transaction. - */ -@property (nonatomic, readonly) BOOL inWriteTransaction; - -/** - The `RLMRealmConfiguration` object that was used to create this `RLMRealm` instance. - */ -@property (nonatomic, readonly) RLMRealmConfiguration *configuration; - -/** - Indicates if this Realm contains any objects. - */ -@property (nonatomic, readonly) BOOL isEmpty; - -#pragma mark - File Management - -/** - Writes a compacted and optionally encrypted copy of the Realm to the given local URL. - - The destination file cannot already exist. - - Note that if this method is called from within a write transaction, the - *current* data is written, not the data from the point when the previous write - transaction was committed. - - @param fileURL Local URL to save the Realm to. - @param key Optional 64-byte encryption key to encrypt the new file with. - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return `YES` if the Realm was successfully written to disk, `NO` if an error occurred. - */ -- (BOOL)writeCopyToURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error; - -/** - Checks if the Realm file for the given configuration exists locally on disk. - - For non-synchronized, non-in-memory Realms, this is equivalent to - `-[NSFileManager.defaultManager fileExistsAtPath:config.path]`. For - synchronized Realms, it takes care of computing the actual path on disk based - on the server, virtual path, and user as is done when opening the Realm. - - @param config A Realm configuration to check the existence of. - @return YES if the Realm file for the given configuration exists on disk, NO otherwise. - */ -+ (BOOL)fileExistsForConfiguration:(RLMRealmConfiguration *)config; - -/** - Deletes the local Realm file and associated temporary files for the given configuration. - - This deletes the ".realm", ".note" and ".management" files which would be - created by opening the Realm with the given configuration. It does not delete - the ".lock" file (which contains no persisted data and is recreated from - scratch every time the Realm file is opened). - - The Realm must not be currently open on any thread or in another process. If - it is, this will return NO and report the error RLMErrorAlreadyOpen. Attempting to open - the Realm on another thread while the deletion is happening will block (and - then create a new Realm and open that afterwards). - - If the Realm already does not exist this will return `NO` and report the error NSFileNoSuchFileError; - - @param config A Realm configuration identifying the Realm to be deleted. - @return YES if any files were deleted, NO otherwise. - */ -+ (BOOL)deleteFilesForConfiguration:(RLMRealmConfiguration *)config error:(NSError **)error - __attribute__((swift_error(nonnull_error))); - -#pragma mark - Notifications - -/** - The type of a block to run whenever the data within the Realm is modified. - - @see `-[RLMRealm addNotificationBlock:]` - */ -typedef void (^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm); - -#pragma mark - Receiving Notification when a Realm Changes - -/** - Adds a notification handler for changes in this Realm, and returns a notification token. - - Notification handlers are called after each write transaction is committed, - either on the current thread or other threads. - - Handler blocks are called on the same thread that they were added on, and may - only be added on threads which are currently within a run loop. Unless you are - specifically creating and running a run loop on a background thread, this will - normally only be the main thread. - - The block has the following definition: - - typedef void(^RLMNotificationBlock)(RLMNotification notification, RLMRealm *realm); - - It receives the following parameters: - - - `NSString` \***notification**: The name of the incoming notification. See - `RLMRealmNotification` for information on what - notifications are sent. - - `RLMRealm` \***realm**: The Realm for which this notification occurred. - - @param block A block which is called to process Realm notifications. - - @return A token object which must be retained as long as you wish to continue - receiving change notifications. - */ -- (RLMNotificationToken *)addNotificationBlock:(RLMNotificationBlock)block __attribute__((warn_unused_result)); - -#pragma mark - Writing to a Realm - -/** - Begins a write transaction on the Realm. - - Only one write transaction can be open at a time for each Realm file. Write - transactions cannot be nested, and trying to begin a write transaction on a - Realm which is already in a write transaction will throw an exception. Calls to - `beginWriteTransaction` from `RLMRealm` instances for the same Realm file in - other threads or other processes will block until the current write transaction - completes or is cancelled. - - Before beginning the write transaction, `beginWriteTransaction` updates the - `RLMRealm` instance to the latest Realm version, as if `refresh` had been - called, and generates notifications if applicable. This has no effect if the - Realm was already up to date. - - It is rarely a good idea to have write transactions span multiple cycles of - the run loop, but if you do wish to do so you will need to ensure that the - Realm participating in the write transaction is kept alive until the write - transaction is committed. - */ -- (void)beginWriteTransaction; - -/** - Commits all write operations in the current write transaction, and ends the - transaction. - - After saving the changes, all notification blocks registered on this specific - `RLMRealm` instance are invoked synchronously. Notification blocks registered - on other threads or on collections are invoked asynchronously. If you do not - want to receive a specific notification for this write tranaction, see - `commitWriteTransactionWithoutNotifying:error:`. - - This method can fail if there is insufficient disk space available to save the - writes made, or due to unexpected i/o errors. This version of the method throws - an exception when errors occur. Use the version with a `NSError` out parameter - instead if you wish to handle errors. - - @warning This method may only be called during a write transaction. - */ -- (void)commitWriteTransaction NS_SWIFT_UNAVAILABLE(""); - -/** - Commits all write operations in the current write transaction, and ends the - transaction. - - After saving the changes, all notification blocks registered on this specific - `RLMRealm` instance are invoked synchronously. Notification blocks registered - on other threads or on collections are invoked asynchronously. If you do not - want to receive a specific notification for this write tranaction, see - `commitWriteTransactionWithoutNotifying:error:`. - - This method can fail if there is insufficient disk space available to save the - writes made, or due to unexpected i/o errors. - - @warning This method may only be called during a write transaction. - - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return Whether the transaction succeeded. - */ -- (BOOL)commitWriteTransaction:(NSError **)error; - -/** - Commits all write operations in the current write transaction, without - notifying specific notification blocks of the changes. - - After saving the changes, all notification blocks registered on this specific - `RLMRealm` instance are invoked synchronously. Notification blocks registered - on other threads or on collections are scheduled to be invoked asynchronously. - - You can skip notifiying specific notification blocks about the changes made - in this write transaction by passing in their associated notification tokens. - This is primarily useful when the write transaction is saving changes already - made in the UI and you do not want to have the notification block attempt to - re-apply the same changes. - - The tokens passed to this method must be for notifications for this specific - `RLMRealm` instance. Notifications for different threads cannot be skipped - using this method. - - This method can fail if there is insufficient disk space available to save the - writes made, or due to unexpected i/o errors. - - @warning This method may only be called during a write transaction. - - @param tokens An array of notification tokens which were returned from adding - callbacks which you do not want to be notified for the changes - made in this write transaction. - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return Whether the transaction succeeded. - */ -- (BOOL)commitWriteTransactionWithoutNotifying:(NSArray *)tokens error:(NSError **)error; - -/** - Reverts all writes made during the current write transaction and ends the transaction. - - This rolls back all objects in the Realm to the state they were in at the - beginning of the write transaction, and then ends the transaction. - - This restores the data for deleted objects, but does not revive invalidated - object instances. Any `RLMObject`s which were added to the Realm will be - invalidated rather than becoming unmanaged. - Given the following code: - - ObjectType *oldObject = [[ObjectType objectsWhere:@"..."] firstObject]; - ObjectType *newObject = [[ObjectType alloc] init]; - - [realm beginWriteTransaction]; - [realm addObject:newObject]; - [realm deleteObject:oldObject]; - [realm cancelWriteTransaction]; - - Both `oldObject` and `newObject` will return `YES` for `isInvalidated`, - but re-running the query which provided `oldObject` will once again return - the valid object. - - KVO observers on any objects which were modified during the transaction will - be notified about the change back to their initial values, but no other - notifcations are produced by a cancelled write transaction. - - @warning This method may only be called during a write transaction. - */ -- (void)cancelWriteTransaction; - -/** - Performs actions contained within the given block inside a write transaction. - - @see `[RLMRealm transactionWithoutNotifying:block:error:]` - */ -- (void)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block NS_SWIFT_UNAVAILABLE(""); - -/** - Performs actions contained within the given block inside a write transaction. - - @see `[RLMRealm transactionWithoutNotifying:block:error:]` - */ -- (BOOL)transactionWithBlock:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error; - -/** - Performs actions contained within the given block inside a write transaction. - - @see `[RLMRealm transactionWithoutNotifying:block:error:]` - */ -- (void)transactionWithoutNotifying:(NSArray *)tokens block:(__attribute__((noescape)) void(^)(void))block; - -/** - Performs actions contained within the given block inside a write transaction. - - Write transactions cannot be nested, and trying to execute a write transaction - on a Realm which is already participating in a write transaction will throw an - exception. Calls to `transactionWithBlock:` from `RLMRealm` instances in other - threads will block until the current write transaction completes. - - Before beginning the write transaction, `transactionWithBlock:` updates the - `RLMRealm` instance to the latest Realm version, as if `refresh` had been called, and - generates notifications if applicable. This has no effect if the Realm - was already up to date. - - You can skip notifiying specific notification blocks about the changes made - in this write transaction by passing in their associated notification tokens. - This is primarily useful when the write transaction is saving changes already - made in the UI and you do not want to have the notification block attempt to - re-apply the same changes. - - The tokens passed to this method must be for notifications for this specific - `RLMRealm` instance. Notifications for different threads cannot be skipped - using this method. - - @param tokens An array of notification tokens which were returned from adding - callbacks which you do not want to be notified for the changes - made in this write transaction. - @param block The block containing actions to perform. - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return Whether the transaction succeeded. - */ -- (BOOL)transactionWithoutNotifying:(NSArray *)tokens block:(__attribute__((noescape)) void(^)(void))block error:(NSError **)error; - -/** - Updates the Realm and outstanding objects managed by the Realm to point to the - most recent data. - - If the version of the Realm is actually changed, Realm and collection - notifications will be sent to reflect the changes. This may take some time, as - collection notifications are prepared on a background thread. As a result, - calling this method on the main thread is not advisable. - - @return Whether there were any updates for the Realm. Note that `YES` may be - returned even if no data actually changed. - */ -- (BOOL)refresh; - -/** - Set this property to `YES` to automatically update this Realm when changes - happen in other threads. - - If set to `YES` (the default), changes made on other threads will be reflected - in this Realm on the next cycle of the run loop after the changes are - committed. If set to `NO`, you must manually call `-refresh` on the Realm to - update it to get the latest data. - - Note that by default, background threads do not have an active run loop and you - will need to manually call `-refresh` in order to update to the latest version, - even if `autorefresh` is set to `YES`. - - Even with this property enabled, you can still call `-refresh` at any time to - update the Realm before the automatic refresh would occur. - - Write transactions will still always advance a Realm to the latest version and - produce local notifications on commit even if autorefresh is disabled. - - Disabling `autorefresh` on a Realm without any strong references to it will not - have any effect, and `autorefresh` will revert back to `YES` the next time the - Realm is created. This is normally irrelevant as it means that there is nothing - to refresh (as managed `RLMObject`s, `RLMArray`s, and `RLMResults` have strong - references to the Realm that manages them), but it means that setting - `RLMRealm.defaultRealm.autorefresh = NO` in - `application:didFinishLaunchingWithOptions:` and only later storing Realm - objects will not work. - - Defaults to `YES`. - */ -@property (nonatomic) BOOL autorefresh; - -/** - Invalidates all `RLMObject`s, `RLMResults`, `RLMLinkingObjects`, and `RLMArray`s managed by the Realm. - - A Realm holds a read lock on the version of the data accessed by it, so - that changes made to the Realm on different threads do not modify or delete the - data seen by this Realm. Calling this method releases the read lock, - allowing the space used on disk to be reused by later write transactions rather - than growing the file. This method should be called before performing long - blocking operations on a background thread on which you previously read data - from the Realm which you no longer need. - - All `RLMObject`, `RLMResults` and `RLMArray` instances obtained from this - `RLMRealm` instance on the current thread are invalidated. `RLMObject`s and `RLMArray`s - cannot be used. `RLMResults` will become empty. The Realm itself remains valid, - and a new read transaction is implicitly begun the next time data is read from the Realm. - - Calling this method multiple times in a row without reading any data from the - Realm, or before ever reading any data from the Realm, is a no-op. This method - may not be called on a read-only Realm. - */ -- (void)invalidate; - -#pragma mark - Accessing Objects - -/** - Returns the same object as the one referenced when the `RLMThreadSafeReference` was first created, - but resolved for the current Realm for this thread. Returns `nil` if this object was deleted after - the reference was created. - - @param reference The thread-safe reference to the thread-confined object to resolve in this Realm. - - @warning A `RLMThreadSafeReference` object must be resolved at most once. - Failing to resolve a `RLMThreadSafeReference` will result in the source version of the - Realm being pinned until the reference is deallocated. - An exception will be thrown if a reference is resolved more than once. - - @warning Cannot call within a write transaction. - - @note Will refresh this Realm if the source Realm was at a later version than this one. - - @see `+[RLMThreadSafeReference referenceWithThreadConfined:]` - */ -- (nullable id)resolveThreadSafeReference:(RLMThreadSafeReference *)reference -NS_REFINED_FOR_SWIFT; - -#pragma mark - Adding and Removing Objects from a Realm - -/** - Adds an object to the Realm. - - Once added, this object is considered to be managed by the Realm. It can be retrieved - using the `objectsWhere:` selectors on `RLMRealm` and on subclasses of `RLMObject`. - - When added, all child relationships referenced by this object will also be added to - the Realm if they are not already in it. - - If the object or any related objects are already being managed by a different Realm - an exception will be thrown. Use `-[RLMObject createInRealm:withObject:]` to insert a copy of a managed object - into a different Realm. - - The object to be added must be valid and cannot have been previously deleted - from a Realm (i.e. `isInvalidated` must be `NO`). - - @warning This method may only be called during a write transaction. - - @param object The object to be added to this Realm. - */ -- (void)addObject:(RLMObject *)object; - -/** - Adds all the objects in a collection to the Realm. - - This is the equivalent of calling `addObject:` for every object in a collection. - - @warning This method may only be called during a write transaction. - - @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, - containing Realm objects to be added to the Realm. - - @see `addObject:` - */ -- (void)addObjects:(id)objects; - -/** - Adds or updates an existing object into the Realm. - - The object provided must have a designated primary key. If no objects exist in the Realm - with the same primary key value, the object is inserted. Otherwise, the existing object is - updated with any changed values. - - As with `addObject:`, the object cannot already be managed by a different - Realm. Use `-[RLMObject createOrUpdateInRealm:withValue:]` to copy values to - a different Realm. - - If there is a property or KVC value on `object` whose value is nil, and it corresponds - to a nullable property on an existing object being updated, that nullable property will - be set to nil. - - @warning This method may only be called during a write transaction. - - @param object The object to be added or updated. - */ -- (void)addOrUpdateObject:(RLMObject *)object; - -/** - Adds or updates all the objects in a collection into the Realm. - - This is the equivalent of calling `addOrUpdateObject:` for every object in a collection. - - @warning This method may only be called during a write transaction. - - @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, - containing Realm objects to be added to or updated within the Realm. - - @see `addOrUpdateObject:` - */ -- (void)addOrUpdateObjects:(id)objects; - -/** - Deletes an object from the Realm. Once the object is deleted it is considered invalidated. - - @warning This method may only be called during a write transaction. - - @param object The object to be deleted. - */ -- (void)deleteObject:(RLMObject *)object; - -/** - Deletes one or more objects from the Realm. - - This is the equivalent of calling `deleteObject:` for every object in a collection. - - @warning This method may only be called during a write transaction. - - @param objects An enumerable collection such as `NSArray`, `RLMArray`, or `RLMResults`, - containing objects to be deleted from the Realm. - - @see `deleteObject:` - */ -- (void)deleteObjects:(id)objects; - -/** - Deletes all objects from the Realm. - - @warning This method may only be called during a write transaction. - - @see `deleteObject:` - */ -- (void)deleteAllObjects; - - -#pragma mark - Migrations - -/** - The type of a migration block used to migrate a Realm. - - @param migration A `RLMMigration` object used to perform the migration. The - migration object allows you to enumerate and alter any - existing objects which require migration. - - @param oldSchemaVersion The schema version of the Realm being migrated. - */ -typedef void (^RLMMigrationBlock)(RLMMigration *migration, uint64_t oldSchemaVersion); - -/** - Returns the schema version for a Realm at a given local URL. - - @param fileURL Local URL to a Realm file. - @param key 64-byte key used to encrypt the file, or `nil` if it is unencrypted. - @param error If an error occurs, upon return contains an `NSError` object - that describes the problem. If you are not interested in - possible errors, pass in `NULL`. - - @return The version of the Realm at `fileURL`, or `RLMNotVersioned` if the version cannot be read. - */ -+ (uint64_t)schemaVersionAtURL:(NSURL *)fileURL encryptionKey:(nullable NSData *)key error:(NSError **)error -NS_REFINED_FOR_SWIFT; - -/** - Performs the given Realm configuration's migration block on a Realm at the given path. - - This method is called automatically when opening a Realm for the first time and does - not need to be called explicitly. You can choose to call this method to control - exactly when and how migrations are performed. - - @param configuration The Realm configuration used to open and migrate the Realm. - @return The error that occurred while applying the migration, if any. - - @see RLMMigration - */ -+ (BOOL)performMigrationForConfiguration:(RLMRealmConfiguration *)configuration error:(NSError **)error; - -#pragma mark - Privileges - -/** - Returns the computed privileges which the current user has for this Realm. - - This combines all privileges granted on the Realm by all Roles which the - current User is a member of into the final privileges which will be enforced by - the server. - - The privilege calculation is done locally using cached data, and inherently may - be stale. It is possible that this method may indicate that an operation is - permitted but the server will still reject it if permission is revoked before - the changes have been integrated on the server. - - Non-synchronized Realms always have permission to perform all operations. - - @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. - @return The privileges which the current user has for the current Realm. - */ -- (struct RLMRealmPrivileges)privilegesForRealm; - -/** - Returns the computed privileges which the current user has for the given object. - - This combines all privileges granted on the object by all Roles which the - current User is a member of into the final privileges which will be enforced by - the server. - - The privilege calculation is done locally using cached data, and inherently may - be stale. It is possible that this method may indicate that an operation is - permitted but the server will still reject it if permission is revoked before - the changes have been integrated on the server. - - Non-synchronized Realms always have permission to perform all operations. - - The object must be a valid object managed by this Realm. Passing in an - invalidated object, an unmanaged object, or an object managed by a different - Realm will throw an exception. - - @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. - @return The privileges which the current user has for the given object. - */ -- (struct RLMObjectPrivileges)privilegesForObject:(RLMObject *)object; - -/** - Returns the computed privileges which the current user has for the given class. - - This combines all privileges granted on the class by all Roles which the - current User is a member of into the final privileges which will be enforced by - the server. - - The privilege calculation is done locally using cached data, and inherently may - be stale. It is possible that this method may indicate that an operation is - permitted but the server will still reject it if permission is revoked before - the changes have been integrated on the server. - - Non-synchronized Realms always have permission to perform all operations. - - @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. - @return The privileges which the current user has for the given object. - */ -- (struct RLMClassPrivileges)privilegesForClass:(Class)cls; - -/** - Returns the computed privileges which the current user has for the named class. - - This combines all privileges granted on the class by all Roles which the - current User is a member of into the final privileges which will be enforced by - the server. - - The privilege calculation is done locally using cached data, and inherently may - be stale. It is possible that this method may indicate that an operation is - permitted but the server will still reject it if permission is revoked before - the changes have been integrated on the server. - - Non-synchronized Realms always have permission to perform all operations. - - @warning This currently returns incorrect results for non-partially-synchronized read-only Realms. - @return The privileges which the current user has for the given object. - */ -- (struct RLMClassPrivileges)privilegesForClassNamed:(NSString *)className; - -#pragma mark - Unavailable Methods - -/** - RLMRealm instances are cached internally by Realm and cannot be created directly. - - Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or - `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm. - */ -- (instancetype)init __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:."))); - -/** - RLMRealm instances are cached internally by Realm and cannot be created directly. - - Use `+[RLMRealm defaultRealm]`, `+[RLMRealm realmWithConfiguration:error:]` or - `+[RLMRealm realmWithURL]` to obtain a reference to an RLMRealm. - */ -+ (instancetype)new __attribute__((unavailable("Use +defaultRealm, +realmWithConfiguration: or +realmWithURL:."))); - -/// :nodoc: -- (void)addOrUpdateObjectsFromArray:(id)array __attribute__((unavailable("Renamed to -addOrUpdateObjects:."))); - -@end - -// MARK: - RLMNotificationToken - -/** - A token which is returned from methods which subscribe to changes to a Realm. - - Change subscriptions in Realm return an `RLMNotificationToken` instance, - which can be used to unsubscribe from the changes. You must store a strong - reference to the token for as long as you want to continue to receive notifications. - When you wish to stop, call the `-invalidate` method. Notifications are also stopped if - the token is deallocated. - */ -@interface RLMNotificationToken : NSObject -/// Stops notifications for the change subscription that returned this token. -- (void)invalidate; - -/// Stops notifications for the change subscription that returned this token. -- (void)stop __attribute__((unavailable("Renamed to -invalidate."))) NS_REFINED_FOR_SWIFT; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealmConfiguration+Sync.h b/Lesson14/Pods/Realm/include/RLMRealmConfiguration+Sync.h deleted file mode 100644 index abd51bf..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealmConfiguration+Sync.h +++ /dev/null @@ -1,43 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMSyncUtil.h" - -@class RLMSyncConfiguration; - -/// Realm configuration options related to Sync. -@interface RLMRealmConfiguration (Sync) - -NS_ASSUME_NONNULL_BEGIN - -/** - A configuration object representing configuration state for Realms intended - to sync with a Realm Object Server. - - This property is mutually exclusive with both `inMemoryIdentifier` and `fileURL`; - setting any one of the three properties will automatically nil out the other two. - - @see `RLMSyncConfiguration` - */ -@property (nullable, nonatomic) RLMSyncConfiguration *syncConfiguration; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Lesson14/Pods/Realm/include/RLMRealmConfiguration.h b/Lesson14/Pods/Realm/include/RLMRealmConfiguration.h deleted file mode 100644 index 3ec8fd5..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealmConfiguration.h +++ /dev/null @@ -1,123 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - A block called when opening a Realm for the first time during the life - of a process to determine if it should be compacted before being returned - to the user. It is passed the total file size (data + free space) and the total - bytes used by data in the file. - - Return `YES` to indicate that an attempt to compact the file should be made. - The compaction will be skipped if another process is accessing it. - */ -typedef BOOL (^RLMShouldCompactOnLaunchBlock)(NSUInteger totalBytes, NSUInteger bytesUsed); - -/** - An `RLMRealmConfiguration` instance describes the different options used to - create an instance of a Realm. - - `RLMRealmConfiguration` instances are just plain `NSObject`s. Unlike `RLMRealm`s - and `RLMObject`s, they can be freely shared between threads as long as you do not - mutate them. - - Creating configuration objects for class subsets (by setting the - `objectClasses` property) can be expensive. Because of this, you will normally want to - cache and reuse a single configuration object for each distinct configuration rather than - creating a new object each time you open a Realm. - */ -@interface RLMRealmConfiguration : NSObject - -#pragma mark - Default Configuration - -/** - Returns the default configuration used to create Realms when no other - configuration is explicitly specified (i.e. `+[RLMRealm defaultRealm]`). - - @return The default Realm configuration. - */ -+ (instancetype)defaultConfiguration; - -/** - Sets the default configuration to the given `RLMRealmConfiguration`. - - @param configuration The new default Realm configuration. - */ -+ (void)setDefaultConfiguration:(RLMRealmConfiguration *)configuration; - -#pragma mark - Properties - -/// The local URL of the Realm file. Mutually exclusive with `inMemoryIdentifier` and `syncConfiguration`; -/// setting any one of the three properties will automatically nil out the other two. -@property (nonatomic, copy, nullable) NSURL *fileURL; - -/// A string used to identify a particular in-memory Realm. Mutually exclusive with `fileURL` and `syncConfiguration`; -/// setting any one of the three properties will automatically nil out the other two. -@property (nonatomic, copy, nullable) NSString *inMemoryIdentifier; - -/// A 64-byte key to use to encrypt the data, or `nil` if encryption is not enabled. -@property (nonatomic, copy, nullable) NSData *encryptionKey; - -/// Whether to open the Realm in read-only mode. -/// -/// This is required to be able to open Realm files which are not writeable or -/// are in a directory which is not writeable. This should only be used on files -/// which will not be modified by anyone while they are open, and not just to -/// get a read-only view of a file which may be written to by another thread or -/// process. Opening in read-only mode requires disabling Realm's reader/writer -/// coordination, so committing a write transaction from another process will -/// result in crashes. -@property (nonatomic) BOOL readOnly; - -/// The current schema version. -@property (nonatomic) uint64_t schemaVersion; - -/// The block which migrates the Realm to the current version. -@property (nonatomic, copy, nullable) RLMMigrationBlock migrationBlock; - -/** - Whether to recreate the Realm file with the provided schema if a migration is required. - This is the case when the stored schema differs from the provided schema or - the stored schema version differs from the version on this configuration. - Setting this property to `YES` deletes the file if a migration would otherwise be required or executed. - - @note Setting this property to `YES` doesn't disable file format migrations. - */ -@property (nonatomic) BOOL deleteRealmIfMigrationNeeded; - -/** - A block called when opening a Realm for the first time during the life - of a process to determine if it should be compacted before being returned - to the user. It is passed the total file size (data + free space) and the total - bytes used by data in the file. - - Return `YES` to indicate that an attempt to compact the file should be made. - The compaction will be skipped if another process is accessing it. - */ -@property (nonatomic, copy, nullable) RLMShouldCompactOnLaunchBlock shouldCompactOnLaunch; - -/// The classes managed by the Realm. -@property (nonatomic, copy, nullable) NSArray *objectClasses; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.h b/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.h deleted file mode 100644 index b3e4784..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.h +++ /dev/null @@ -1,45 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 - -@class RLMSchema; - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMRealmConfiguration () - -@property (nonatomic, readwrite) bool cache; -@property (nonatomic, readwrite) bool dynamic; -@property (nonatomic, readwrite) bool disableFormatUpgrade; -@property (nonatomic, copy, nullable) RLMSchema *customSchema; -@property (nonatomic, copy) NSString *pathOnDisk; - -// Get the default confiugration without copying it -+ (RLMRealmConfiguration *)rawDefaultConfiguration; - -+ (void)resetRealmConfigurationState; - -- (void)setCustomSchemaWithoutCopying:(nullable RLMSchema *)schema; -@end - -// Get a path in the platform-appropriate documents directory with the given filename -FOUNDATION_EXTERN NSString *RLMRealmPathForFile(NSString *fileName); -FOUNDATION_EXTERN NSString *RLMRealmPathForFileAndBundleIdentifier(NSString *fileName, NSString *mainBundleIdentifier); - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.hpp b/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.hpp deleted file mode 100644 index a89fb0f..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealmConfiguration_Private.hpp +++ /dev/null @@ -1,26 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMRealmConfiguration_Private.h" -#import "shared_realm.hpp" - -@interface RLMRealmConfiguration () -- (realm::Realm::Config&)config; - -@property (nonatomic) realm::SchemaMode schemaMode; -@end diff --git a/Lesson14/Pods/Realm/include/RLMRealmUtil.hpp b/Lesson14/Pods/Realm/include/RLMRealmUtil.hpp deleted file mode 100644 index 4960b9c..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealmUtil.hpp +++ /dev/null @@ -1,39 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import - -@class RLMRealm; - -namespace realm { - class BindingContext; -} - -// Add a Realm to the weak cache -void RLMCacheRealm(std::string const& path, RLMRealm *realm); -// Get a Realm for the given path which can be used on the current thread -RLMRealm *RLMGetThreadLocalCachedRealmForPath(std::string const& path); -// Get a Realm for the given path -RLMRealm *RLMGetAnyCachedRealmForPath(std::string const& path); -// Clear the weak cache of Realms -void RLMClearRealmCache(); -// Check if the current thread is currently within a running CFRunLoop -bool RLMIsInRunLoop(); - -std::unique_ptr RLMCreateBindingContext(RLMRealm *realm); diff --git a/Lesson14/Pods/Realm/include/RLMRealm_Dynamic.h b/Lesson14/Pods/Realm/include/RLMRealm_Dynamic.h deleted file mode 100644 index f796ed3..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealm_Dynamic.h +++ /dev/null @@ -1,118 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import -#import - -@class RLMResults; - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMRealm (Dynamic) - -#pragma mark - Getting Objects from a Realm - -/** - Returns all objects of a given type from the Realm. - - @warning This method is useful only in specialized circumstances, for example, when building components - that integrate with Realm. The preferred way to get objects of a single class is to use the class - methods on `RLMObject`. - - @param className The name of the `RLMObject` subclass to retrieve on (e.g. `MyClass.className`). - - @return An `RLMResults` containing all objects in the Realm of the given type. - - @see `+[RLMObject allObjects]` - */ -- (RLMResults *)allObjects:(NSString *)className; - -/** - Returns all objects matching the given predicate from the Realm. - - @warning This method is useful only in specialized circumstances, for example, when building components - that integrate with Realm. The preferred way to get objects of a single class is to use the class - methods on `RLMObject`. - - @param className The type of objects you are looking for (name of the class). - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return An `RLMResults` containing results matching the given predicate. - - @see `+[RLMObject objectsWhere:]` - */ -- (RLMResults *)objects:(NSString *)className where:(NSString *)predicateFormat, ...; - -/** - Returns all objects matching the given predicate from the Realm. - - @warning This method is useful only in specialized circumstances, for example, when building components - that integrate with Realm. The preferred way to get objects of a single class is to use the class - methods on `RLMObject`. - - @param className The type of objects you are looking for (name of the class). - @param predicate The predicate with which to filter the objects. - - @return An `RLMResults` containing results matching the given predicate. - - @see `+[RLMObject objectsWhere:]` - */ -- (RLMResults *)objects:(NSString *)className withPredicate:(NSPredicate *)predicate; - -/** - Returns the object of the given type with the given primary key from the Realm. - - @warning This method is useful only in specialized circumstances, for example, when building components - that integrate with Realm. The preferred way to get an object of a single class is to use the class - methods on `RLMObject`. - - @param className The class name for the object you are looking for. - @param primaryKey The primary key value for the object you are looking for. - - @return An object, or `nil` if an object with the given primary key does not exist. - - @see `+[RLMObject objectForPrimaryKey:]` - */ -- (nullable RLMObject *)objectWithClassName:(NSString *)className forPrimaryKey:(id)primaryKey; - -/** - Creates an `RLMObject` instance of type `className` in the Realm, and populates it using a given object. - - The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or - dictionary returned from the methods in `NSJSONSerialization`, or an array containing one element for each managed - property. An exception will be thrown if any required properties are not present and those properties were not defined - with default values. - - When passing in an array as the `value` argument, all properties must be present, valid and in the same order as the - properties defined in the model. - - @warning This method is useful only in specialized circumstances, for example, when building components - that integrate with Realm. If you are simply building an app on Realm, it is recommended to - use `[RLMObject createInDefaultRealmWithValue:]`. - - @param value The value used to populate the object. - - @return An `RLMObject` instance of type `className`. - */ --(RLMObject *)createObject:(NSString *)className withValue:(id)value; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealm_Private.h b/Lesson14/Pods/Realm/include/RLMRealm_Private.h deleted file mode 100644 index ae13f1e..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealm_Private.h +++ /dev/null @@ -1,57 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -@class RLMFastEnumerator, RLMSyncSubscription; - -NS_ASSUME_NONNULL_BEGIN - -// Disable syncing files to disk. Cannot be re-enabled. Use only for tests. -FOUNDATION_EXTERN void RLMDisableSyncToDisk(void); - -FOUNDATION_EXTERN NSData * _Nullable RLMRealmValidatedEncryptionKey(NSData *key); - -FOUNDATION_EXTERN RLMSyncSubscription *RLMCastToSyncSubscription(id obj); - -// Set the queue used for async open. For testing purposes only. -FOUNDATION_EXTERN void RLMSetAsyncOpenQueue(dispatch_queue_t queue); - -// Translate an in-flight exception resulting from an operation on a SharedGroup to -// an NSError or NSException (if error is nil) -void RLMRealmTranslateException(NSError **error); - -// RLMRealm private members -@interface RLMRealm () - -@property (nonatomic, readonly) BOOL dynamic; -@property (nonatomic, readwrite) RLMSchema *schema; - -+ (void)resetRealmState; - -- (void)registerEnumerator:(RLMFastEnumerator *)enumerator; -- (void)unregisterEnumerator:(RLMFastEnumerator *)enumerator; -- (void)detachAllEnumerators; - -- (void)sendNotifications:(RLMNotification)notification; -- (void)verifyThread; -- (void)verifyNotificationsAreSupported:(bool)isCollection; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMRealm_Private.hpp b/Lesson14/Pods/Realm/include/RLMRealm_Private.hpp deleted file mode 100644 index 9b596cd..0000000 --- a/Lesson14/Pods/Realm/include/RLMRealm_Private.hpp +++ /dev/null @@ -1,46 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 "RLMRealm_Private.h" - -#import "RLMClassInfo.hpp" -#import "object_schema.hpp" - -namespace realm { - class Group; - class Realm; -} -struct RLMResultsSetInfo { - realm::ObjectSchema osObjectSchema; - RLMObjectSchema *rlmObjectSchema; - RLMClassInfo info; - - RLMResultsSetInfo(__unsafe_unretained RLMRealm *const realm); - static RLMClassInfo& get(__unsafe_unretained RLMRealm *const realm); -}; - -@interface RLMRealm () { - @public - std::shared_ptr _realm; - RLMSchemaInfo _info; - std::unique_ptr _resultsSetInfo; -} - -// FIXME - group should not be exposed -@property (nonatomic, readonly) realm::Group &group; -@end diff --git a/Lesson14/Pods/Realm/include/RLMResults.h b/Lesson14/Pods/Realm/include/RLMResults.h deleted file mode 100644 index d8d1cf6..0000000 --- a/Lesson14/Pods/Realm/include/RLMResults.h +++ /dev/null @@ -1,351 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMObject; - -/** - `RLMResults` is an auto-updating container type in Realm returned from object - queries. It represents the results of the query in the form of a collection of objects. - - `RLMResults` can be queried using the same predicates as `RLMObject` and `RLMArray`, - and you can chain queries to further filter results. - - `RLMResults` always reflect the current state of the Realm on the current thread, - including during write transactions on the current thread. The one exception to - this is when using `for...in` fast enumeration, which will always enumerate - over the objects which matched the query when the enumeration is begun, even if - some of them are deleted or modified to be excluded by the filter during the - enumeration. - - `RLMResults` are lazily evaluated the first time they are accessed; they only - run queries when the result of the query is requested. This means that - chaining several temporary `RLMResults` to sort and filter your data does not - perform any extra work processing the intermediate state. - - Once the results have been evaluated or a notification block has been added, - the results are eagerly kept up-to-date, with the work done to keep them - up-to-date done on a background thread whenever possible. - - `RLMResults` cannot be directly instantiated. - */ -@interface RLMResults : NSObject - -#pragma mark - Properties - -/** - The number of objects in the results collection. - */ -@property (nonatomic, readonly, assign) NSUInteger count; - -/** - The type of the objects in the results collection. - */ -@property (nonatomic, readonly, assign) RLMPropertyType type; - -/** - Indicates whether the objects in the collection can be `nil`. - */ -@property (nonatomic, readwrite, getter = isOptional) BOOL optional; - -/** - The class name of the objects contained in the results collection. - - Will be `nil` if `type` is not RLMPropertyTypeObject. - */ -@property (nonatomic, readonly, copy, nullable) NSString *objectClassName; - -/** - The Realm which manages this results collection. - */ -@property (nonatomic, readonly) RLMRealm *realm; - -/** - Indicates if the results collection is no longer valid. - - The results collection becomes invalid if `invalidate` is called on the containing `realm`. - An invalidated results collection can be accessed, but will always be empty. - */ -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - -#pragma mark - Accessing Objects from an RLMResults - -/** - Returns the object at the index specified. - - @param index The index to look up. - - @return An object of the type contained in the results collection. - */ -- (RLMObjectType)objectAtIndex:(NSUInteger)index; - -/** - Returns the first object in the results collection. - - Returns `nil` if called on an empty results collection. - - @return An object of the type contained in the results collection. - */ -- (nullable RLMObjectType)firstObject; - -/** - Returns the last object in the results collection. - - Returns `nil` if called on an empty results collection. - - @return An object of the type contained in the results collection. - */ -- (nullable RLMObjectType)lastObject; - -#pragma mark - Querying Results - -/** - Returns the index of an object in the results collection. - - Returns `NSNotFound` if the object is not found in the results collection. - - @param object An object (of the same type as returned from the `objectClassName` selector). - */ -- (NSUInteger)indexOfObject:(RLMObjectType)object; - -/** - Returns the index of the first object in the results collection matching the predicate. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return The index of the object, or `NSNotFound` if the object is not found in the results collection. - */ -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns the index of the first object in the results collection matching the predicate. - - @param predicate The predicate with which to filter the objects. - - @return The index of the object, or `NSNotFound` if the object is not found in the results collection. - */ -- (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate; - -/** - Returns all the objects matching the given predicate in the results collection. - - @param predicateFormat A predicate format string, optionally followed by a variable number of arguments. - - @return An `RLMResults` of objects that match the given predicate. - */ -- (RLMResults *)objectsWhere:(NSString *)predicateFormat, ...; - -/// :nodoc: -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - -/** - Returns all the objects matching the given predicate in the results collection. - - @param predicate The predicate with which to filter the objects. - - @return An `RLMResults` of objects that match the given predicate. - */ -- (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate; - -/** - Returns a sorted `RLMResults` from an existing results collection. - - @param keyPath The key path to sort by. - @param ascending The direction to sort in. - - @return An `RLMResults` sorted by the specified key path. - */ -- (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending; - -/** - Returns a sorted `RLMResults` from an existing results collection. - - @param properties An array of `RLMSortDescriptor`s to sort by. - - @return An `RLMResults` sorted by the specified properties. - */ -- (RLMResults *)sortedResultsUsingDescriptors:(NSArray *)properties; - -/** - Returns a distinct `RLMResults` from an existing results collection. - - @param keyPaths The key paths used produce distinct results - - @return An `RLMResults` made distinct based on the specified key paths - */ -- (RLMResults *)distinctResultsUsingKeyPaths:(NSArray *)keyPaths; - -#pragma mark - Notifications - -/** - Registers a block to be called each time the results collection changes. - - The block will be asynchronously called with the initial results collection, - and then called again after each write transaction which changes either any - of the objects in the results, or which objects are in the results. - - The `change` parameter will be `nil` the first time the block is called. - For each call after that, it will contain information about - which rows in the results collection were added, removed or modified. If a - write transaction did not modify any objects in the results collection, - the block is not called at all. See the `RLMCollectionChange` documentation for - information on how the changes are reported and an example of updating a - `UITableView`. - - If an error occurs the block will be called with `nil` for the results - parameter and a non-`nil` error. Currently the only errors that can occur are - when opening the Realm on the background worker thread. - - At the time when the block is called, the `RLMResults` object will be fully - evaluated and up-to-date, and as long as you do not perform a write transaction - on the same thread or explicitly call `-[RLMRealm refresh]`, accessing it will - never perform blocking work. - - Notifications are delivered via the standard run loop, and so can't be - delivered while the run loop is blocked by other activity. When - notifications can't be delivered instantly, multiple notifications may be - coalesced into a single notification. This can include the notification - with the initial results. For example, the following code performs a write - transaction immediately after adding the notification block, so there is no - opportunity for the initial notification to be delivered first. As a - result, the initial notification will reflect the state of the Realm after - the write transaction. - - RLMResults *results = [Dog allObjects]; - NSLog(@"dogs.count: %zu", dogs.count); // => 0 - self.token = [results addNotificationBlock:^(RLMResults *dogs, - RLMCollectionChange *changes, - NSError *error) { - // Only fired once for the example - NSLog(@"dogs.count: %zu", dogs.count); // => 1 - }]; - [realm transactionWithBlock:^{ - Dog *dog = [[Dog alloc] init]; - dog.name = @"Rex"; - [realm addObject:dog]; - }]; - // end of run loop execution context - - You must retain the returned token for as long as you want updates to continue - to be sent to the block. To stop receiving updates, call `-invalidate` on the token. - - @warning This method cannot be called during a write transaction, or when the - containing Realm is read-only. - - @param block The block to be called whenever a change occurs. - @return A token which must be held for as long as you want updates to be delivered. - */ -- (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *__nullable results, - RLMCollectionChange *__nullable change, - NSError *__nullable error))block __attribute__((warn_unused_result)); - -#pragma mark - Aggregating Property Values - -/** - Returns the minimum (lowest) value of the given property among all the objects - represented by the results collection. - - NSNumber *min = [results minOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose minimum value is desired. Only properties of types `int`, `float`, `double`, and - `NSDate` are supported. - - @return The minimum value of the property, or `nil` if the Results are empty. - */ -- (nullable id)minOfProperty:(NSString *)property; - -/** - Returns the maximum (highest) value of the given property among all the objects represented by the results collection. - - NSNumber *max = [results maxOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose maximum value is desired. Only properties of - types `int`, `float`, `double`, and `NSDate` are supported. - - @return The maximum value of the property, or `nil` if the Results are empty. - */ -- (nullable id)maxOfProperty:(NSString *)property; - -/** - Returns the sum of the values of a given property over all the objects represented by the results collection. - - NSNumber *sum = [results sumOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose values should be summed. Only properties of - types `int`, `float`, and `double` are supported. - - @return The sum of the given property. - */ -- (NSNumber *)sumOfProperty:(NSString *)property; - -/** - Returns the average value of a given property over the objects represented by the results collection. - - NSNumber *average = [results averageOfProperty:@"age"]; - - @warning You cannot use this method on `RLMObject`, `RLMArray`, and `NSData` properties. - - @param property The property whose average value should be calculated. Only - properties of types `int`, `float`, and `double` are supported. - - @return The average value of the given property, or `nil` if the Results are empty. - */ -- (nullable NSNumber *)averageOfProperty:(NSString *)property; - -/// :nodoc: -- (RLMObjectType)objectAtIndexedSubscript:(NSUInteger)index; - -#pragma mark - Unavailable Methods - -/** - `-[RLMResults init]` is not available because `RLMResults` cannot be created directly. - `RLMResults` can be obtained by querying a Realm. - */ -- (instancetype)init __attribute__((unavailable("RLMResults cannot be created directly"))); - -/** - `+[RLMResults new]` is not available because `RLMResults` cannot be created directly. - `RLMResults` can be obtained by querying a Realm. - */ -+ (instancetype)new __attribute__((unavailable("RLMResults cannot be created directly"))); - -@end - -/** - `RLMLinkingObjects` is an auto-updating container type. It represents a collection of objects that link to its - parent object. - - For more information, please see the "Inverse Relationships" section in the - [documentation](https://realm.io/docs/objc/latest/#relationships). - */ -@interface RLMLinkingObjects : RLMResults -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMResults_Private.h b/Lesson14/Pods/Realm/include/RLMResults_Private.h deleted file mode 100644 index f74b4fd..0000000 --- a/Lesson14/Pods/Realm/include/RLMResults_Private.h +++ /dev/null @@ -1,32 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -@class RLMObjectSchema; - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMResults () -@property (nonatomic, readonly, getter=isAttached) BOOL attached; - -+ (instancetype)emptyDetachedResults; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMResults_Private.hpp b/Lesson14/Pods/Realm/include/RLMResults_Private.hpp deleted file mode 100644 index 57edc23..0000000 --- a/Lesson14/Pods/Realm/include/RLMResults_Private.hpp +++ /dev/null @@ -1,66 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 "RLMResults_Private.h" - -#import "results.hpp" - -class RLMClassInfo; - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMResults () { -@protected - realm::Results _results; -} - -/** - Initialize a 'raw' `RLMResults` using only an object store level Results. - This is only meant for applications where a results collection is being backed - by an object store object class that has no binding-level equivalent. The - consumer is responsible for bridging between the underlying objects and whatever - binding-level class is being vended out. - */ -- (instancetype)initWithResults:(realm::Results)results; - -- (instancetype)initWithObjectInfo:(RLMClassInfo&)info results:(realm::Results&&)results; -+ (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info results:(realm::Results&&)results; - -- (instancetype)subresultsWithResults:(realm::Results)results; -@end - -NS_ASSUME_NONNULL_END - -// Utility functions - -[[gnu::noinline]] -[[noreturn]] -void RLMThrowResultsError(NSString * _Nullable aggregateMethod); - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnullability-completeness" -template -static auto translateRLMResultsErrors(Function&& f, NSString *aggregateMethod=nil) { - try { - return f(); - } - catch (...) { - RLMThrowResultsError(aggregateMethod); - } -} -#pragma clang diagnostic pop diff --git a/Lesson14/Pods/Realm/include/RLMSchema.h b/Lesson14/Pods/Realm/include/RLMSchema.h deleted file mode 100644 index 30325e4..0000000 --- a/Lesson14/Pods/Realm/include/RLMSchema.h +++ /dev/null @@ -1,77 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMObjectSchema; - -/** - `RLMSchema` instances represent collections of model object schemas managed by a Realm. - - When using Realm, `RLMSchema` instances allow performing migrations and - introspecting the database's schema. - - Schemas map to collections of tables in the core database. - */ -@interface RLMSchema : NSObject - -#pragma mark - Properties - -/** - An `NSArray` containing `RLMObjectSchema`s for all object types in the Realm. - - This property is intended to be used during migrations for dynamic introspection. - - @see `RLMObjectSchema` - */ -@property (nonatomic, readonly, copy) NSArray *objectSchema; - -#pragma mark - Methods - -/** - Returns an `RLMObjectSchema` for the given class name in the schema. - - @param className The object class name. - @return An `RLMObjectSchema` for the given class in the schema. - - @see `RLMObjectSchema` - */ -- (nullable RLMObjectSchema *)schemaForClassName:(NSString *)className; - -/** - Looks up and returns an `RLMObjectSchema` for the given class name in the Realm. - - If there is no object of type `className` in the schema, an exception will be thrown. - - @param className The object class name. - @return An `RLMObjectSchema` for the given class in this Realm. - - @see `RLMObjectSchema` - */ -- (RLMObjectSchema *)objectForKeyedSubscript:(NSString *)className; - -/** - Returns whether two `RLMSchema` instances are equivalent. - */ -- (BOOL)isEqualToSchema:(RLMSchema *)schema; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSchema_Private.h b/Lesson14/Pods/Realm/include/RLMSchema_Private.h deleted file mode 100644 index 7ef4917..0000000 --- a/Lesson14/Pods/Realm/include/RLMSchema_Private.h +++ /dev/null @@ -1,58 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@class RLMRealm; - -// -// RLMSchema private interface -// -@interface RLMSchema () - -/** - Returns an `RLMSchema` containing only the given `RLMObject` subclasses. - - @param classes The classes to be included in the schema. - - @return An `RLMSchema` containing only the given classes. - */ -+ (instancetype)schemaWithObjectClasses:(NSArray *)classes; - -@property (nonatomic, readwrite, copy) NSArray *objectSchema; - -// schema based on runtime objects -+ (instancetype)sharedSchema; - -// schema based upon all currently registered object classes -+ (instancetype)partialSharedSchema; - -// private schema based upon all currently registered object classes. -// includes classes that are excluded from the default schema. -+ (instancetype)partialPrivateSharedSchema; - -// class for string -+ (nullable Class)classForString:(NSString *)className; - -+ (nullable RLMObjectSchema *)sharedSchemaForClass:(Class)cls; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSchema_Private.hpp b/Lesson14/Pods/Realm/include/RLMSchema_Private.hpp deleted file mode 100644 index 197ddee..0000000 --- a/Lesson14/Pods/Realm/include/RLMSchema_Private.hpp +++ /dev/null @@ -1,31 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 "RLMSchema_Private.h" - -#import - -namespace realm { - class Schema; - class ObjectSchema; -} - -@interface RLMSchema () -+ (instancetype)dynamicSchemaFromObjectStoreSchema:(realm::Schema const&)objectStoreSchema; -- (realm::Schema)objectStoreCopy; -@end diff --git a/Lesson14/Pods/Realm/include/RLMSwiftBridgingHeader.h b/Lesson14/Pods/Realm/include/RLMSwiftBridgingHeader.h deleted file mode 100644 index 4758043..0000000 --- a/Lesson14/Pods/Realm/include/RLMSwiftBridgingHeader.h +++ /dev/null @@ -1,49 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import - -@interface RLMRealm (Swift) -+ (void)resetRealmState; -@end - -@interface RLMArray (Swift) - -- (instancetype)initWithObjectClassName:(NSString *)objectClassName; - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - -@end - -@interface RLMResults (Swift) - -- (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args; -- (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; - -@end - -@interface RLMObjectBase (Swift) - -- (instancetype)initWithRealm:(RLMRealm *)realm schema:(RLMObjectSchema *)schema defaultValues:(BOOL)useDefaults; - -+ (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args; -+ (RLMResults *)objectsInRealm:(RLMRealm *)realm where:(NSString *)predicateFormat args:(va_list)args; - -@end diff --git a/Lesson14/Pods/Realm/include/RLMSwiftSupport.h b/Lesson14/Pods/Realm/include/RLMSwiftSupport.h deleted file mode 100644 index 6e45b65..0000000 --- a/Lesson14/Pods/Realm/include/RLMSwiftSupport.h +++ /dev/null @@ -1,30 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMSwiftSupport : NSObject - -+ (BOOL)isSwiftClassName:(NSString *)className; -+ (NSString *)demangleClassName:(NSString *)className; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncConfiguration.h b/Lesson14/Pods/Realm/include/RLMSyncConfiguration.h deleted file mode 100644 index 5a74db2..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncConfiguration.h +++ /dev/null @@ -1,114 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -@class RLMRealmConfiguration; -@class RLMSyncUser; - -NS_ASSUME_NONNULL_BEGIN - -/** - A configuration object representing configuration state for a Realm which is intended to sync with a Realm Object - Server. - */ -@interface RLMSyncConfiguration : NSObject - -/// The user to which the remote Realm belongs. -@property (nonatomic, readonly) RLMSyncUser *user; - -/** - The URL of the remote Realm upon the Realm Object Server. - - @warning The URL cannot end with `.realm`, `.realm.lock` or `.realm.management`. - */ -@property (nonatomic, readonly) NSURL *realmURL; - -/** - A local path to a file containing the trust anchors for SSL connections. - - Only the certificates stored in the PEM file (or any certificates signed by it, - if the file contains a CA cert) will be accepted when initiating a connection - to a server. This prevents certain certain kinds of man-in-the-middle (MITM) - attacks, and can also be used to trust a self-signed certificate which would - otherwise be untrusted. - - On macOS, the file may be in any of the formats supported by SecItemImport(), - including PEM and .cer (see SecExternalFormat for a complete list of possible - formats). On iOS and other platforms, only DER .cer files are supported. - */ -@property (nonatomic, nullable) NSURL *pinnedCertificateURL; - -/** - Whether SSL certificate validation is enabled for the connection associated - with this configuration value. SSL certificate validation is ON by default. - - @warning NEVER disable certificate validation for clients and servers in production. - */ -@property (nonatomic) BOOL enableSSLValidation; - -/// :nodoc: -@property (nonatomic) BOOL isPartial __attribute__((unavailable("Use 'fullSynchronization' instead."))); - -/** - Whether this Realm should be a fully synchronized Realm. - - Synchronized Realms comes in two flavors: Query-based and Fully synchronized. - A fully synchronized Realm will automatically synchronize the entire Realm in - the background while a query-based Realm will only synchronize the data being - subscribed to. Synchronized realms are by default query-based unless this - boolean is set. - */ -@property (nonatomic) BOOL fullSynchronization; - -/** - The prefix that is prepended to the path in the HTTP request that initiates a - sync connection. The value specified must match with the server's expectation. - Changing the value of `urlPrefix` should be matched with a corresponding - change of the server's configuration. - If no value is specified here then the default `/realm-sync` path is used. -*/ -@property (nonatomic, nullable, copy) NSString *urlPrefix; - -/** - Whether nonfatal connection errors should cancel async opens. - - By default, if a nonfatal connection error such as a connection timing out occurs, any currently pending asyncOpen operations will ignore the error and continue to retry until it succeeds. If this is set to true, the open will instead fail and report the error. - - FIXME: This should probably be true by default in the next major version. - */ -@property (nonatomic) bool cancelAsyncOpenOnNonFatalErrors; - -/// :nodoc: -- (instancetype)initWithUser:(RLMSyncUser *)user realmURL:(NSURL *)url __attribute__((unavailable("Use [RLMSyncUser configurationWithURL:] instead"))); - -/// :nodoc: -+ (RLMRealmConfiguration *)automaticConfiguration __attribute__((unavailable("Use [RLMSyncUser configuration] instead"))); - -/// :nodoc: -+ (RLMRealmConfiguration *)automaticConfigurationForUser:(RLMSyncUser *)user __attribute__((unavailable("Use [RLMSyncUser configuration] instead"))); - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); - -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.h b/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.h deleted file mode 100644 index 07bf0a2..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.h +++ /dev/null @@ -1,48 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import - -NS_ASSUME_NONNULL_BEGIN - -typedef RLM_CLOSED_ENUM(NSUInteger, RLMSyncStopPolicy) { - RLMSyncStopPolicyImmediately, - RLMSyncStopPolicyLiveIndefinitely, - RLMSyncStopPolicyAfterChangesUploaded, -}; - -@interface RLMSyncConfiguration () - -- (instancetype)initWithUser:(RLMSyncUser *)user - realmURL:(NSURL *)url - isPartial:(BOOL)isPartial - urlPrefix:(nullable NSString *)urlPrefix - stopPolicy:(RLMSyncStopPolicy)stopPolicy - enableSSLValidation:(BOOL)enableSSLValidation - certificatePath:(nullable NSURL *)certificatePath; - -@property (nonatomic, readwrite) RLMSyncStopPolicy stopPolicy; - -// Internal-only APIs -@property (nullable, nonatomic) NSURL *customFileURL; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.hpp b/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.hpp deleted file mode 100644 index 6314e4c..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncConfiguration_Private.hpp +++ /dev/null @@ -1,47 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncConfiguration_Private.h" - -#import -#import - -namespace realm { -class SyncSession; -struct SyncConfig; -struct SyncError; -using SyncSessionErrorHandler = void(std::shared_ptr, SyncError); -} - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMSyncConfiguration () - -- (instancetype)initWithUser:(RLMSyncUser *)user - realmURL:(NSURL *)url - customFileURL:(nullable NSURL *)customFileURL - isPartial:(BOOL)isPartial - stopPolicy:(RLMSyncStopPolicy)stopPolicy; - -- (instancetype)initWithRawConfig:(realm::SyncConfig)config; - -- (realm::SyncConfig&)rawConfiguration; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncCredentials.h b/Lesson14/Pods/Realm/include/RLMSyncCredentials.h deleted file mode 100644 index 6c99ce5..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncCredentials.h +++ /dev/null @@ -1,158 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMSyncUtil.h" - -NS_ASSUME_NONNULL_BEGIN - -/// A token representing an identity provider's credentials. -typedef NSString *RLMSyncCredentialsToken; - -/// A type representing the unique identifier of a Realm Object Server identity provider. -typedef NSString *RLMIdentityProvider RLM_EXTENSIBLE_STRING_ENUM; - -/// The debug identity provider, which accepts any token string and creates a user associated with that token if one -/// does not yet exist. Not enabled for Realm Object Server configured for production. -extern RLMIdentityProvider const RLMIdentityProviderDebug; - -/// The username/password identity provider. User accounts are handled by the Realm Object Server directly without the -/// involvement of a third-party identity provider. -extern RLMIdentityProvider const RLMIdentityProviderUsernamePassword; - -/// A Facebook account as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderFacebook; - -/// A Google account as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderGoogle; - -/// A CloudKit account as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderCloudKit; - -/// A JSON Web Token as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderJWT; - -/// An Anonymous account as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderAnonymous; - -/// A Nickname account as an identity provider. -extern RLMIdentityProvider const RLMIdentityProviderNickname __deprecated_msg("Use RLMIdentityProviderUsernamePassword instead"); - -/** - Opaque credentials representing a specific Realm Object Server user. - */ -@interface RLMSyncCredentials : NSObject - -/// An opaque credentials token containing information that uniquely identifies a Realm Object Server user. -@property (nonatomic, readonly) RLMSyncCredentialsToken token; - -/// The name of the identity provider which generated the credentials token. -@property (nonatomic, readonly) RLMIdentityProvider provider; - -/// A dictionary containing additional pertinent information. In most cases this is automatically configured. -@property (nonatomic, readonly) NSDictionary *userInfo; - -/** - Construct and return credentials from a Facebook account token. - */ -+ (instancetype)credentialsWithFacebookToken:(RLMSyncCredentialsToken)token; - -/** - Construct and return credentials from a Google account token. - */ -+ (instancetype)credentialsWithGoogleToken:(RLMSyncCredentialsToken)token; - -/** - Construct and return credentials from an CloudKit account token. - */ -+ (instancetype)credentialsWithCloudKitToken:(RLMSyncCredentialsToken)token; - -/** - Construct and return credentials from a Realm Object Server username and password. - */ -+ (instancetype)credentialsWithUsername:(NSString *)username - password:(NSString *)password - register:(BOOL)shouldRegister; - -/** - Construct and return credentials from a JSON Web Token. - */ -+ (instancetype)credentialsWithJWT:(NSString *)token; - -/** - Construct and return anonymous credentials - */ -+ (instancetype)anonymousCredentials; - -/** - Construct and return credentials from a nickname - */ -+ (instancetype)credentialsWithNickname:(NSString *)nickname isAdmin:(BOOL)isAdmin __deprecated_msg("Use +credentialsWithUsername instead"); - -/** - Construct and return special credentials representing a token that can - be directly used to open a Realm. The identity is used to uniquely identify - the user across application launches. - - @warning The custom user identity will be deprecated in a future release. - - @warning Do not specify a user identity that is the URL of an authentication - server. - - @warning When passing an access token credential into any of `RLMSyncUser`'s - login methods, you must always specify the same authentication server - URL, or none at all, every time you call the login method. - */ -+ (instancetype)credentialsWithAccessToken:(RLMServerToken)accessToken identity:(NSString *)identity; - -/** - Construct and return special credentials representing a token issued by an external entity - that will be used instead of a ROS refresh token. - - @discussion Unlike other types of credentials, CustomRefreshToken credentials do not - participate in the regular login flow, because they take place of the refresh tokens login produces. - Instead, the token will be used to authorize each server operation such as opening a Realm or - editing permissions. When the token expires the SyncUser object will still be valid, but server operations will - fail until the token is updated. - - @remark ROS must be configured to accept the external issuing identity as a refresh token validator. - - @warning The values of @c identity and @c isAdmin are used for client-side validation only. - The server will compute their values based on the token string and the token validator configuration, - but it's important for correct functioning that the values here match the server. - */ -+ (instancetype)credentialsWithCustomRefreshToken:(NSString *)token identity:(NSString *)identity isAdmin:(BOOL)isAdmin; - -/** - Construct and return credentials with a custom token string, identity provider string, and optional user info. In most - cases, the convenience initializers should be used instead. - */ -- (instancetype)initWithCustomToken:(RLMSyncCredentialsToken)token - provider:(RLMIdentityProvider)provider - userInfo:(nullable NSDictionary *)userInfo NS_DESIGNATED_INITIALIZER; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("RLMSyncCredentials cannot be created directly"))); - -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("RLMSyncCredentials cannot be created directly"))); - -NS_ASSUME_NONNULL_END - -@end diff --git a/Lesson14/Pods/Realm/include/RLMSyncManager.h b/Lesson14/Pods/Realm/include/RLMSyncManager.h deleted file mode 100644 index debb5d4..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncManager.h +++ /dev/null @@ -1,245 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMSyncUtil.h" - -@class RLMSyncSession, RLMSyncTimeoutOptions; - -NS_ASSUME_NONNULL_BEGIN - -/// An enum representing different levels of sync-related logging that can be configured. -typedef RLM_CLOSED_ENUM(NSUInteger, RLMSyncLogLevel) { - /// Nothing will ever be logged. - RLMSyncLogLevelOff, - /// Only fatal errors will be logged. - RLMSyncLogLevelFatal, - /// Only errors will be logged. - RLMSyncLogLevelError, - /// Warnings and errors will be logged. - RLMSyncLogLevelWarn, - /// Information about sync events will be logged. Fewer events will be logged in order to avoid overhead. - RLMSyncLogLevelInfo, - /// Information about sync events will be logged. More events will be logged than with `RLMSyncLogLevelInfo`. - RLMSyncLogLevelDetail, - /// Log information that can aid in debugging. - /// - /// - warning: Will incur a measurable performance impact. - RLMSyncLogLevelDebug, - /// Log information that can aid in debugging. More events will be logged than with `RLMSyncLogLevelDebug`. - /// - /// - warning: Will incur a measurable performance impact. - RLMSyncLogLevelTrace, - /// Log information that can aid in debugging. More events will be logged than with `RLMSyncLogLevelTrace`. - /// - /// - warning: Will incur a measurable performance impact. - RLMSyncLogLevelAll -}; - -/// A log callback function which can be set on RLMSyncManager. -/// -/// The log function may be called from multiple threads simultaneously, and is -/// responsible for performing its own synchronization if any is required. -typedef void (*RLMSyncLogFunction)(RLMSyncLogLevel level, NSString *message); - -/// A block type representing a block which can be used to report a sync-related error to the application. If the error -/// pertains to a specific session, that session will also be passed into the block. -typedef void(^RLMSyncErrorReportingBlock)(NSError *, RLMSyncSession * _Nullable); - -/** - A singleton manager which serves as a central point for sync-related configuration. - */ -@interface RLMSyncManager : NSObject - -/** - A block which can optionally be set to report sync-related errors to your application. - - Any error reported through this block will be of the `RLMSyncError` type, and marked - with the `RLMSyncErrorDomain` domain. - - Errors reported through this mechanism are fatal, with several exceptions. Please consult - `RLMSyncError` for information about the types of errors that can be reported through - the block, and for for suggestions on handling recoverable error codes. - - @see `RLMSyncError` - */ -@property (nullable, nonatomic, copy) RLMSyncErrorReportingBlock errorHandler; - -/** - A reverse-DNS string uniquely identifying this application. In most cases this - is automatically set by the SDK, and does not have to be explicitly configured. - */ -@property (nonatomic, copy) NSString *appID; - -/** - A string identifying this application which is included in the User-Agent - header of sync connections. By default, this will be the application's bundle - identifier. - - This property must be set prior to opening a synchronized Realm for the first - time. Any modifications made after opening a Realm will be ignored. - */ -@property (nonatomic, copy) NSString *userAgent; - -/** - The logging threshold which newly opened synced Realms will use. Defaults to - `RLMSyncLogLevelInfo`. - - By default logging strings are output to Apple System Logger. Set `logger` to - perform custom logging logic instead. - - @warning This property must be set before any synced Realms are opened. Setting it after - opening any synced Realm will do nothing. - */ -@property (nonatomic) RLMSyncLogLevel logLevel; - -/** - The function which will be invoked whenever the sync client has a log message. - - If nil, log strings are output to Apple System Logger instead. - - @warning This property must be set before any synced Realms are opened. Setting - it after opening any synced Realm will do nothing. - */ -@property (nonatomic, nullable) RLMSyncLogFunction logger; - -/** - The name of the HTTP header to send authorization data in when making requests to a Realm Object Server which has - been configured to expect a custom authorization header. - */ -@property (nullable, nonatomic, copy) NSString *authorizationHeaderName; - -/** - Extra HTTP headers to append to every request to a Realm Object Server. - - Modifying this property while sync sessions are active will result in all - sessions disconnecting and reconnecting using the new headers. - */ -@property (nullable, nonatomic, copy) NSDictionary *customRequestHeaders; - -/** - A map of hostname to file URL for pinned certificates to use for HTTPS requests. - - When initiating a HTTPS connection to a server, if this dictionary contains an - entry for the server's hostname, only the certificates stored in the file (or - any certificates signed by it, if the file contains a CA cert) will be accepted - when initiating a connection to a server. This prevents certain certain kinds - of man-in-the-middle (MITM) attacks, and can also be used to trust a self-signed - certificate which would otherwise be untrusted. - - On macOS, the certificate files may be in any of the formats supported by - SecItemImport(), including PEM and .cer (see SecExternalFormat for a complete - list of possible formats). On iOS and other platforms, only DER .cer files are - supported. - - For example, to pin example.com to a .cer file included in your bundle: - -
- RLMSyncManager.sharedManager.pinnedCertificatePaths = @{
-    @"example.com": [NSBundle.mainBundle pathForResource:@"example.com" ofType:@"cer"]
- };
- 
- */ -@property (nullable, nonatomic, copy) NSDictionary *pinnedCertificatePaths; - -/** - Options for the assorted types of connection timeouts for sync connections. - - If nil default values for all timeouts are used instead. - - @warning This property must be set before any synced Realms are opened. Setting - it after opening any synced Realm will do nothing. - */ -@property (nullable, nonatomic, copy) RLMSyncTimeoutOptions *timeoutOptions; - -/// The sole instance of the singleton. -+ (instancetype)sharedManager NS_REFINED_FOR_SWIFT; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("RLMSyncManager cannot be created directly"))); - -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("RLMSyncManager cannot be created directly"))); - -@end - -/** - Options for configuring timeouts and intervals in the sync client. - */ -@interface RLMSyncTimeoutOptions : NSObject -/// The maximum number of milliseconds to allow for a connection to -/// become fully established. This includes the time to resolve the -/// network address, the TCP connect operation, the SSL handshake, and -/// the WebSocket handshake. -/// -/// Defaults to 2 minutes. -@property (nonatomic) NSUInteger connectTimeout; - -/// The number of milliseconds to keep a connection open after all -/// sessions have been abandoned. -/// -/// After all synchronized Realms have been closed for a given server, the -/// connection is kept open until the linger time has expire to avoid the -/// overhead of reestablishing the connection when Realms are being closed and -/// reopened. -/// -/// Defaults to 30 seconds. -@property (nonatomic) NSUInteger connectionLingerTime; - -/// The number of milliseconds between each heartbeat ping message. -/// -/// The client periodically sends ping messages to the server to check if the -/// connection is still alive. Shorter periods make connection state change -/// notifications more responsive at the cost of battery life (as the antenna -/// will have to wake up more often). -/// -/// Defaults to 1 minute. -@property (nonatomic) NSUInteger pingKeepalivePeriod; - -/// How long in milliseconds to wait for a reponse to a heartbeat ping before -/// concluding that the connection has dropped. -/// -/// Shorter values will make connection state change notifications more -/// responsive as it will only change to `disconnected` after this much time has -/// elapsed, but overly short values may result in spurious disconnection -/// notifications when the server is simply taking a long time to respond. -/// -/// Defaults to 2 minutes. -@property (nonatomic) NSUInteger pongKeepaliveTimeout; - -/// The maximum amount of time, in milliseconds, since the loss of a -/// prior connection, for a new connection to be considered a "fast -/// reconnect". -/// -/// When a client first connects to the server, it defers uploading any local -/// changes until it has downloaded all changesets from the server. This -/// typically reduces the total amount of merging that has to be done, and is -/// particularly beneficial the first time that a specific client ever connects -/// to the server. -/// -/// When an existing client disconnects and then reconnects within the "fact -/// reconnect" time this is skipped and any local changes are uploaded -/// immediately without waiting for downloads, just as if the client was online -/// the whole time. -/// -/// Defaults to 1 minute. -@property (nonatomic) NSUInteger fastReconnectLimit; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncManager_Private.h b/Lesson14/Pods/Realm/include/RLMSyncManager_Private.h deleted file mode 100644 index 0284aee..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncManager_Private.h +++ /dev/null @@ -1,45 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMSyncUtil_Private.h" -#import "RLMNetworkClient.h" - -@class RLMSyncUser, RLMSyncConfiguration; - -// All private API methods are threadsafe and synchronized, unless denoted otherwise. Since they are expected to be -// called very infrequently, this should pose no issues. - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMSyncManager () - -@property (nullable, nonatomic, copy) RLMSyncBasicErrorReportingBlock sessionCompletionNotifier; - -- (void)_fireError:(NSError *)error; - -- (NSArray *)_allUsers; - -+ (void)resetForTesting; - -- (RLMNetworkRequestOptions *)networkRequestOptions; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Lesson14/Pods/Realm/include/RLMSyncPermission.h b/Lesson14/Pods/Realm/include/RLMSyncPermission.h deleted file mode 100644 index 96835cc..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncPermission.h +++ /dev/null @@ -1,527 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 -#import - -@protocol RLMPermission, RLMPermissionUser; -@class RLMPermission, RLMPermissionUser, RLMPermissionRole, - RLMArray, RLMLinkingObjects; - -NS_ASSUME_NONNULL_BEGIN - -/** - A permission which can be applied to a Realm, Class, or specific Object. - - Permissions are applied by adding the permission to the RLMRealmPermission singleton - object, the RLMClassPermission object for the desired class, or to a user-defined - RLMArray property on a specific Object instance. The meaning of each of - the properties of RLMPermission depend on what the permission is applied to, and so are - left undocumented here. See `RLMRealmPrivileges`, `RLMClassPrivileges`, and - `RLMObjectPrivileges` for details about what each of the properties mean when applied to - that type. - */ -@interface RLMPermission : RLMObject -/// The Role which this Permission applies to. All users within the Role are -/// granted the permissions specified by the fields below any -/// objects/classes/realms which use this Permission. -/// -/// This property cannot be modified once set. -@property (nonatomic) RLMPermissionRole *role; - -/// Whether the user can read the object to which this Permission is attached. -@property (nonatomic) bool canRead; -/// Whether the user can modify the object to which this Permission is attached. -@property (nonatomic) bool canUpdate; -/// Whether the user can delete the object to which this Permission is attached. -/// -/// This field is only applicable to Permissions attached to Objects, and not -/// to Realms or Classes. -@property (nonatomic) bool canDelete; -/// Whether the user can add or modify Permissions for the object which this -/// Permission is attached to. -@property (nonatomic) bool canSetPermissions; -/// Whether the user can subscribe to queries for this object type. -/// -/// This field is only applicable to Permissions attached to Classes, and not -/// to Realms or Objects. -@property (nonatomic) bool canQuery; -/// Whether the user can create new objects of the type this Permission is attached to. -/// -/// This field is only applicable to Permissions attached to Classes, and not -/// to Realms or Objects. -@property (nonatomic) bool canCreate; -/// Whether the user can modify the schema of the Realm which this -/// Permission is attached to. -/// -/// This field is only applicable to Permissions attached to Realms, and not -/// to Realms or Objects. -@property (nonatomic) bool canModifySchema; - -/** - Returns the Permission object for the named Role in the array, creating it if needed. - - This function should be used in preference to manually querying the array for - the applicable Permission as it ensures that there is exactly one Permission - for the given Role in the array, merging duplicates or creating and adding new - ones as needed. -*/ -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName inArray:(RLMArray *)array; - -/** - Returns the Permission object for the named Role on the Realm, creating it if needed. - - This function should be used in preference to manually querying for the - applicable Permission as it ensures that there is exactly one Permission for - the given Role on the Realm, merging duplicates or creating and adding new ones - as needed. -*/ -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onRealm:(RLMRealm *)realm; - -/** - Returns the Permission object for the named Role on the Class, creating it if needed. - - This function should be used in preference to manually querying for the - applicable Permission as it ensures that there is exactly one Permission for - the given Role on the Class, merging duplicates or creating and adding new ones - as needed. -*/ -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClass:(Class)cls realm:(RLMRealm *)realm; - -/** - Returns the Permission object for the named Role on the named class, creating it if needed. - - This function should be used in preference to manually querying for the - applicable Permission as it ensures that there is exactly one Permission for - the given Role on the Class, merging duplicates or creating and adding new ones - as needed. -*/ -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onClassNamed:(NSString *)className realm:(RLMRealm *)realm; - -/** - Returns the Permission object for the named Role on the object, creating it if needed. - - This function should be used in preference to manually querying for the - applicable Permission as it ensures that there is exactly one Permission for - the given Role on the Realm, merging duplicates or creating and adding new ones - as needed. - - The given object must have a RLMArray property defined on it. If - more than one such property is present, the first will be used. -*/ -+ (RLMPermission *)permissionForRoleNamed:(NSString *)roleName onObject:(RLMObject *)object; -@end - -/** - A Role within the permissions system. - - A Role consists of a name for the role and a list of users which are members of the role. - Roles are granted privileges on Realms, Classes and Objects, and in turn grant those - privileges to all users which are members of the role. - - A role named "everyone" is automatically created in new Realms, and all new users which - connect to the Realm are automatically added to it. Any other roles you wish to use are - managed as normal Realm objects. - */ -@interface RLMPermissionRole : RLMObject -/// The name of the Role -@property (nonatomic) NSString *name; -/// The users which belong to the role -@property (nonatomic) RLMArray *users; -@end - -/** - A representation of a sync user within the permissions system. - - RLMPermissionUser objects are created automatically for each sync user which connects to - a Realm, and can also be created manually if you wish to grant permissions to a user - which has not yet connected to this Realm. - */ -@interface RLMPermissionUser : RLMObject -/// The unique Realm Object Server user ID string identifying this user. This will have -/// the same value as `-[RLMSyncUser identity]`. -@property (nonatomic) NSString *identity; - -/// The user's private role. This will be initialized to a role named for the user's -/// identity that contains this user as its only member. -@property (nonatomic) RLMPermissionRole *role; - -/// Roles which this user belongs to. -@property (nonatomic, readonly) RLMLinkingObjects *roles; - -/// Get the user object in the given Realm, creating it if needed. -+ (RLMPermissionUser *)userInRealm:(RLMRealm *)realm withIdentity:(NSString *)identity; -@end - -/** - A singleton object which describes Realm-wide permissions. - - An object of this type is automatically created in the Realm for you, and more objects - cannot be created manually. Call `+[RLMRealmPermission objectInRealm:]` to obtain the - instance for a specific Realm. - - See `RLMRealmPrivileges` for the meaning of permissions applied to a Realm. - */ -@interface RLMRealmPermission : RLMObject -/// The permissions for the Realm. -@property (nonatomic) RLMArray *permissions; - -/// Retrieve the singleton object for the given Realm. This will return `nil` -/// for non-partial-sync Realms. -+ (nullable instancetype)objectInRealm:(RLMRealm *)realm; -@end - -/** - An object which describes class-wide permissions. - - An instance of this object is automatically created in the Realm for class in your schema, - and should not be created manually. Call `+[RLMClassPermission objectInRealm:forClassNamed:]` - or `+[RLMClassPermission objectInRealm:forClass:]` to obtain the existing instance, or - query `RLMClassPermission` as normal. - */ -@interface RLMClassPermission : RLMObject -/// The name of the class which these permissions apply to. -@property (nonatomic) NSString *name; -/// The permissions for this class. -@property (nonatomic) RLMArray *permissions; - -/// Retrieve the object for the named RLMObject subclass. This will return `nil` -/// for non-partial-sync Realms. -+ (nullable instancetype)objectInRealm:(RLMRealm *)realm forClassNamed:(NSString *)className; -/// Retrieve the object for the given RLMObject subclass. This will return `nil` -/// for non-partial-sync Realms. -+ (nullable instancetype)objectInRealm:(RLMRealm *)realm forClass:(Class)cls; -@end - -/** - A description of the actual privileges which apply to a Realm. - - This is a combination of all of the privileges granted to all of the Roles which the - current User is a member of, obtained by calling `-[RLMRealm privilegesForRealm]` on - the Realm. - - By default, all operations are permitted, and each privilege field indicates an operation - which may be forbidden. - */ -struct RLMRealmPrivileges { - /// If `false`, the current User is not permitted to see the Realm at all. This can - /// happen only if the Realm was created locally and has not yet been synchronized. - bool read : 1; - - /// If `false`, no modifications to the Realm are permitted. Write transactions can - /// be performed locally, but any changes made will be reverted by the server. - /// `setPermissions` and `modifySchema` will always be `false` when this is `false`. - bool update : 1; - - /// If `false`, no modifications to the permissions property of the RLMRealmPermissions - /// object for are permitted. Write transactions can be performed locally, but any - /// changes made will be reverted by the server. - /// - /// Note that if invalide privilege changes are made, `-[RLMRealm privilegesFor*:]` - /// will return results reflecting those invalid changes until synchronization occurs. - /// - /// Even if this field is `true`, note that the user will be unable to grant - /// privileges to a Role which they do not themselves have. - /// - /// Adding or removing Users from a Role is controlled by Update privileges on that - /// Role, and not by this value. - bool setPermissions : 1; - - /// If `false`, the user is not permitted to add new object types to the Realm or add - /// new properties to existing objec types. Defining new RLMObject subclasses (and not - /// excluding them from the schema with `-[RLMRealmConfiguration setObjectClasses:]`) - /// will result in the application crashing if the object types are not first added on - /// the server by a more privileged user. - bool modifySchema : 1; -}; - -/** - A description of the actual privileges which apply to a Class within a Realm. - - This is a combination of all of the privileges granted to all of the Roles which the - current User is a member of, obtained by calling `-[RLMRealm privilegesForClass:]` or - `-[RLMRealm privilegesForClassNamed:]` on the Realm. - - By default, all operations are permitted, and each privilege field indicates an operation - which may be forbidden. - */ -struct RLMClassPrivileges { - /// If `false`, the current User is not permitted to see objects of this type, and - /// attempting to query this class will always return empty results. - /// - /// Note that Read permissions are transitive, and so it may be possible to read an - /// object which the user does not directly have Read permissions for by following a - /// link to it from an object they do have Read permissions for. This does not apply - /// to any of the other permission types. - bool read : 1; - - /// If `false`, creating new objects of this type is not permitted. Write transactions - /// creating objects can be performed locally, but the objects will be deleted by the - /// server when synchronization occurs. - /// - /// For objects with Primary Keys, it may not be locally determinable if Create or - /// Update privileges are applicable. It may appear that you are creating a new object, - /// but an object with that Primary Key may already exist and simply not be visible to - /// you, in which case it is actually an Update operation. - bool create : 1; - - /// If `false`, no modifications to objects of this type are permitted. Write - /// transactions modifying the objects can be performed locally, but any changes made - /// will be reverted by the server. - /// - /// Deleting an object is considered a modification, and is governed by this privilege. - bool update : 1; - - /// If `false`, the User is not permitted to create new subscriptions for this class. - /// Local queries against the objects within the Realm will work, but new - /// subscriptions will never add objects to the Realm. - bool subscribe : 1; - - /// If `false`, no modifications to the permissions property of the RLMClassPermissions - /// object for this type are permitted. Write transactions can be performed locally, - /// but any changes made will be reverted by the server. - /// - /// Note that if invalid privilege changes are made, `-[RLMRealm privilegesFor*:]` - /// will return results reflecting those invalid changes until synchronization occurs. - /// - /// Even if this field is `true`, note that the user will be unable to grant - /// privileges to a Role which they do not themselves have. - bool setPermissions : 1; -}; - -/** - A description of the actual privileges which apply to a specific RLMObject. - - This is a combination of all of the privileges granted to all of the Roles which the - current User is a member of, obtained by calling `-[RLMRealm privilegesForObject:]` on - the Realm. - - By default, all operations are permitted, and each privilege field indicates an operation - which may be forbidden. - */ -struct RLMObjectPrivileges { - /// If `false`, the current User is not permitted to read this object directly. - /// - /// Objects which cannot be read by a user will appear in a Realm due to that read - /// permissions are transitive. All objects which a readable object links to are - /// themselves implicitly readable. If the link to an object with `read=false` is - /// removed, the object will be deleted from the local Realm. - bool read : 1; - - /// If `false`, modifying the fields of this type is not permitted. Write - /// transactions modifying the objects can be performed locally, but any changes made - /// will be reverted by the server. - /// - /// Note that even if this is `true`, the user may not be able to modify the - /// `RLMArray *` property of the object (if it exists), as that is - /// governed by `setPermissions`. - bool update : 1; - - /// If `false`, deleting this object is not permitted. Write transactions which delete - /// the object can be performed locally, but the server will restore it. - /// - /// It is possible to have `update` but not `delete` privileges, or vice versa. For - /// objects with primary keys, `delete` but not `update` is ill-advised, as an object - /// can be updated by deleting and recreating it. - bool del : 1; - - /// If `false`, modifying the privileges of this specific object is not permitted. - /// - /// Object-specific permissions are set by declaring a `RLMArray *` - /// property on the `RLMObject` subclass. Modifications to this property are - /// controlled by `setPermissions` rather than `update`. - /// - /// Even if this field is `true`, note that the user will be unable to grant - /// privileges to a Role which they do not themselves have. - bool setPermissions : 1; -}; - -/// :nodoc: -FOUNDATION_EXTERN id RLMPermissionForRole(RLMArray *array, id role); - -/** - Access levels which can be granted to Realm Mobile Platform users - for specific synchronized Realms, using the permissions APIs. - - Note that each access level guarantees all allowed actions provided - by less permissive access levels. Specifically, users with write - access to a Realm can always read from that Realm, and users with - administrative access can always read or write from the Realm. - */ -typedef RLM_CLOSED_ENUM(NSUInteger, RLMSyncAccessLevel) { - /// No access whatsoever. - RLMSyncAccessLevelNone = 0, - /** - User can only read the contents of the Realm. - - @warning Users who have read-only access to a Realm should open the - Realm using `+[RLMRealm asyncOpenWithConfiguration:callbackQueue:callback:]`. - Attempting to directly open the Realm is an error; in this - case the Realm must be deleted and re-opened. - */ - RLMSyncAccessLevelRead = 1, - /// User can read and write the contents of the Realm. - RLMSyncAccessLevelWrite = 2, - /// User can read, write, and administer the Realm, including - /// granting permissions to other users. - RLMSyncAccessLevelAdmin = 3, -}; - -/// Get a string representing a sync acces level -FOUNDATION_EXTERN NSString *RLMSyncAccessLevelToString(RLMSyncAccessLevel); - -/// Get a sync access level for the given string. -/// -/// Throws an exception if the string is not a valid access level. -FOUNDATION_EXTERN RLMSyncAccessLevel RLMSyncAccessLevelFromString(NSString *); - -/** - A value representing a permission granted to the specified user(s) to access the specified Realm(s). - - `RLMSyncPermission` is immutable and can be accessed from any thread. - - See https://realm.io/docs/realm-object-server/#permissions for general documentation. - */ -@interface RLMSyncPermission : NSObject - -/** - The Realm Object Server path to the Realm to which this permission applies (e.g. "/path/to/realm"). - - Specify "*" if this permission applies to all Realms managed by the server. - */ -@property (nonatomic, readonly) NSString *path; - -/** - The access level described by this permission. - */ -@property (nonatomic, readonly) RLMSyncAccessLevel accessLevel; - -/// Whether the access level allows the user to read from the Realm. -@property (nonatomic, readonly) BOOL mayRead; - -/// Whether the access level allows the user to write to the Realm. -@property (nonatomic, readonly) BOOL mayWrite; - -/// Whether the access level allows the user to administer the Realm. -@property (nonatomic, readonly) BOOL mayManage; - -/** - Create a new sync permission value, for use with permission APIs. - - @param path The Realm Object Server path to the Realm whose permission should be modified - (e.g. "/path/to/realm"). Pass "*" to apply to all Realms managed by the user. - @param identity The Realm Object Server identity of the user who should be granted access to - the Realm at `path`. - Pass "*" to apply to all users managed by the server. - @param accessLevel The access level to grant. - */ -- (instancetype)initWithRealmPath:(NSString *)path - identity:(NSString *)identity - accessLevel:(RLMSyncAccessLevel)accessLevel; - -/** - Create a new sync permission value, for use with permission APIs. - - @param path The Realm Object Server path to the Realm whose permission should be modified - (e.g. "/path/to/realm"). Pass "*" to apply to all Realms managed by the user. - @param username The username (often an email address) of the user who should be granted access - to the Realm at `path`. - @param accessLevel The access level to grant. - */ -- (instancetype)initWithRealmPath:(NSString *)path - username:(NSString *)username - accessLevel:(RLMSyncAccessLevel)accessLevel; - -/** - The identity of the user to whom this permission is granted, or "*" - if all users are granted this permission. Nil if the permission is - defined in terms of a key-value pair. - */ -@property (nullable, nonatomic, readonly) NSString *identity; - -/** - If the permission is defined in terms of a key-value pair, the key - describing the type of criterion used to determine what users the - permission applies to. Otherwise, nil. - */ -@property (nullable, nonatomic, readonly) NSString *key; - -/** - If the permission is defined in terms of a key-value pair, a string - describing the criterion value used to determine what users the - permission applies to. Otherwise, nil. - */ -@property (nullable, nonatomic, readonly) NSString *value; - -/** - When this permission was last updated. - */ -@property (nonatomic, readonly) NSDate *updatedAt; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("Use the designated initializer"))); - -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("Use the designated initializer"))); - -// MARK: - Migration assistance - -/// :nodoc: -@property (nullable, nonatomic, readonly) NSString *userId __attribute__((unavailable("Renamed to `identity`"))); - -/// :nodoc: -- (instancetype)initWithRealmPath:(NSString *)path - userID:(NSString *)identity - accessLevel:(RLMSyncAccessLevel)accessLevel -__attribute__((unavailable("Renamed to `-initWithRealmPath:identity:accessLevel:`"))); - -@end - -/** - A pending offer to grant permissions on a Realm path. - - This type is immutable and can be safely read from any thread. - - @see -[RLMSyncUser retrievePermissionOffersWithCallback:] - */ -@interface RLMSyncPermissionOffer : NSObject -/// The Realm Object Server path to the Realm to which this permission applies (e.g. "/path/to/realm"). -@property (nonatomic, readonly) NSString *realmPath; -/// The token which can be used to aceept or revoke this offer. -@property (nonatomic, readonly) NSString *token; -/// The date when this offer will expire, or nil for a non-expiring offer. -@property (nonatomic, nullable, readonly) NSDate *expiresAt; -/// The date when this offer was created. -@property (nonatomic, nullable, readonly) NSDate *createdAt; -/// The access level which this offer grants. -@property (nonatomic, readonly) RLMSyncAccessLevel accessLevel; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("Use the designated initializer"))); -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("Use the designated initializer"))); - -/// :nodoc: -- (instancetype)initWithRealmPath:(NSString *)path - token:(NSString *)token - expiresAt:(NSDate *)expiresAt - createdAt:(NSDate *)createdAt - accessLevel:(RLMSyncAccessLevel)accessLevel; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncSession.h b/Lesson14/Pods/Realm/include/RLMSyncSession.h deleted file mode 100644 index 3b26184..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncSession.h +++ /dev/null @@ -1,278 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMRealm.h" - -/** - The current state of the session represented by a session object. - */ -typedef NS_ENUM(NSUInteger, RLMSyncSessionState) { - /// The sync session is actively communicating or attempting to communicate - /// with the Realm Object Server. A session is considered Active even if - /// it is not currently connected. Check the connection state instead if you - /// wish to know if the connection is currently online. - RLMSyncSessionStateActive, - /// The sync session is not attempting to communicate with the Realm Object - /// Server, due to the user logging out or synchronization being paused. - RLMSyncSessionStateInactive, - /// The sync session encountered a fatal error and is permanently invalid; it should be discarded. - RLMSyncSessionStateInvalid -}; - -/** - The current state of a sync session's connection. Sessions which are not in - the Active state will always be Disconnected. - */ -typedef NS_ENUM(NSUInteger, RLMSyncConnectionState) { - /// The sync session is not connected to the server, and is not attempting - /// to connect, either because the session is inactive or because it is - /// waiting to retry after a failed connection. - RLMSyncConnectionStateDisconnected, - /// The sync session is attempting to connect to the Realm Object Server. - RLMSyncConnectionStateConnecting, - /// The sync session is currently connected to the Realm Object Server. - RLMSyncConnectionStateConnected, -}; - -/** - The transfer direction (upload or download) tracked by a given progress notification block. - - Progress notification blocks can be registered on sessions if your app wishes to be informed - how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. - */ -typedef RLM_CLOSED_ENUM(NSUInteger, RLMSyncProgressDirection) { - /// For monitoring upload progress. - RLMSyncProgressDirectionUpload, - /// For monitoring download progress. - RLMSyncProgressDirectionDownload, -}; - -/** - The desired behavior of a progress notification block. - - Progress notification blocks can be registered on sessions if your app wishes to be informed - how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. - */ -typedef NS_ENUM(NSUInteger, RLMSyncProgressMode) { - /** - The block will be called indefinitely, or until it is unregistered by calling - `-[RLMProgressNotificationToken invalidate]`. - - Notifications will always report the latest number of transferred bytes, and the - most up-to-date number of total transferrable bytes. - */ - RLMSyncProgressModeReportIndefinitely, - /** - The block will, upon registration, store the total number of bytes - to be transferred. When invoked, it will always report the most up-to-date number - of transferrable bytes out of that original number of transferrable bytes. - - When the number of transferred bytes reaches or exceeds the - number of transferrable bytes, the block will be unregistered. - */ - RLMSyncProgressModeForCurrentlyOutstandingWork, -}; - -@class RLMSyncUser, RLMSyncConfiguration, RLMSyncErrorActionToken; - -/** - The type of a progress notification block intended for reporting a session's network - activity to the user. - - `transferredBytes` refers to the number of bytes that have been uploaded or downloaded. - `transferrableBytes` refers to the total number of bytes transferred, and pending transfer. - */ -typedef void(^RLMProgressNotificationBlock)(NSUInteger transferredBytes, NSUInteger transferrableBytes); - -NS_ASSUME_NONNULL_BEGIN - -/** - A token object corresponding to a progress notification block on a session object. - - To stop notifications manually, call `-invalidate` on it. Notifications should be stopped before - the token goes out of scope or is destroyed. - */ -@interface RLMProgressNotificationToken : RLMNotificationToken -@end - -/** - An object encapsulating a Realm Object Server "session". Sessions represent the - communication between the client (and a local Realm file on disk), and the server - (and a remote Realm at a given URL stored on a Realm Object Server). - - Sessions are always created by the SDK and vended out through various APIs. The - lifespans of sessions associated with Realms are managed automatically. Session - objects can be accessed from any thread. - */ -@interface RLMSyncSession : NSObject - -/// The session's current state. -/// -/// This property is not KVO-compliant. -@property (nonatomic, readonly) RLMSyncSessionState state; - -/// The session's current connection state. -/// -/// This property is KVO-compliant and can be observed to be notified of changes. -/// Be warned that KVO observers for this property may be called on a background -/// thread. -@property (atomic, readonly) RLMSyncConnectionState connectionState; - -/// The Realm Object Server URL of the remote Realm this session corresponds to. -@property (nullable, nonatomic, readonly) NSURL *realmURL; - -/// The user that owns this session. -- (nullable RLMSyncUser *)parentUser; - -/** - If the session is valid, return a sync configuration that can be used to open the Realm - associated with this session. - */ -- (nullable RLMSyncConfiguration *)configuration; - -/** - Temporarily suspend syncronization and disconnect from the server. - - The session will not attempt to connect to Realm Object Server until `resume` - is called or the Realm file is closed and re-opened. - */ -- (void)suspend; - -/** - Resume syncronization and reconnect to Realm Object Server after suspending. - - This is a no-op if the session was already active or if the session is invalid. - Newly created sessions begin in the Active state and do not need to be resumed. - */ -- (void)resume; - -/** - Register a progress notification block. - - Multiple blocks can be registered with the same session at once. Each block - will be invoked on a side queue devoted to progress notifications. - - If the session has already received progress information from the - synchronization subsystem, the block will be called immediately. Otherwise, it - will be called as soon as progress information becomes available. - - The token returned by this method must be retained as long as progress - notifications are desired, and the `-invalidate` method should be called on it - when notifications are no longer needed and before the token is destroyed. - - If no token is returned, the notification block will never be called again. - There are a number of reasons this might be true. If the session has previously - experienced a fatal error it will not accept progress notification blocks. If - the block was configured in the `RLMSyncProgressForCurrentlyOutstandingWork` - mode but there is no additional progress to report (for example, the number - of transferrable bytes and transferred bytes are equal), the block will not be - called again. - - @param direction The transfer direction (upload or download) to track in this progress notification block. - @param mode The desired behavior of this progress notification block. - @param block The block to invoke when notifications are available. - - @return A token which must be held for as long as you want notifications to be delivered. - - @see `RLMSyncProgressDirection`, `RLMSyncProgress`, `RLMProgressNotificationBlock`, `RLMProgressNotificationToken` - */ -- (nullable RLMProgressNotificationToken *)addProgressNotificationForDirection:(RLMSyncProgressDirection)direction - mode:(RLMSyncProgressMode)mode - block:(RLMProgressNotificationBlock)block -NS_REFINED_FOR_SWIFT; - -/** - Given an error action token, immediately handle the corresponding action. - - @see `RLMSyncErrorClientResetError`, `RLMSyncErrorPermissionDeniedError` - */ -+ (void)immediatelyHandleError:(RLMSyncErrorActionToken *)token; - -/** - Get the sync session for the given Realm if it is a synchronized Realm, or `nil` - if it is not. - */ -+ (nullable RLMSyncSession *)sessionForRealm:(RLMRealm *)realm; - -@end - -// MARK: - Error action token - -#pragma mark - Error action token - -/** - An opaque token returned as part of certain errors. It can be - passed into certain APIs to perform certain actions. - - @see `RLMSyncErrorClientResetError`, `RLMSyncErrorPermissionDeniedError` - */ -@interface RLMSyncErrorActionToken : NSObject - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); - -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); - -@end - -/** - A task object which can be used to observe or cancel an async open. - - When a synchronized Realm is opened asynchronously, the latest state of the - Realm is downloaded from the server before the completion callback is invoked. - This task object can be used to observe the state of the download or to cancel - it. This should be used instead of trying to observe the download via the sync - session as the sync session itself is created asynchronously, and may not exist - yet when -[RLMRealm asyncOpenWithConfiguration:completion:] returns. - */ -@interface RLMAsyncOpenTask : NSObject -/** - Register a progress notification block. - - Each registered progress notification block is called whenever the sync - subsystem has new progress data to report until the task is either cancelled - or the completion callback is called. Progress notifications are delivered on - the main queue. - */ -- (void)addProgressNotificationBlock:(RLMProgressNotificationBlock)block; - -/** - Register a progress notification block which is called on the given queue. - - Each registered progress notification block is called whenever the sync - subsystem has new progress data to report until the task is either cancelled - or the completion callback is called. Progress notifications are delivered on - the supplied queue. - */ -- (void)addProgressNotificationOnQueue:(dispatch_queue_t)queue - block:(RLMProgressNotificationBlock)block; - -/** - Cancel the asynchronous open. - - Any download in progress will be cancelled, and the completion block for this - async open will never be called. If multiple async opens on the same Realm are - happening concurrently, all other opens will fail with the error "operation cancelled". - */ -- (void)cancel; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.h b/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.h deleted file mode 100644 index 78a278b..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.h +++ /dev/null @@ -1,30 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 - -@class RLMSyncUser; - -/// An object that handles refreshing a session's token periodically, as long -/// as the session remains live and valid. -@interface RLMSyncSessionRefreshHandle : NSObject - -- (void)scheduleRefreshTimer:(NSDate *)dateWhenTokenExpires; -- (void)invalidate; - -@end diff --git a/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp b/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp deleted file mode 100644 index 26b5bea..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncSessionRefreshHandle.hpp +++ /dev/null @@ -1,43 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncSessionRefreshHandle.h" - -#import "RLMSyncUtil_Private.h" - -#import - -namespace realm { -class SyncSession; -class SyncUser; -} - -@class RLMSyncUser; - -@interface RLMSyncSessionRefreshHandle () - -NS_ASSUME_NONNULL_BEGIN - -- (instancetype)initWithRealmURL:(NSURL *)realmURL - user:(std::shared_ptr)user - session:(std::shared_ptr)session - completionBlock:(nullable RLMSyncBasicErrorReportingBlock)completionBlock; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Lesson14/Pods/Realm/include/RLMSyncSession_Private.hpp b/Lesson14/Pods/Realm/include/RLMSyncSession_Private.hpp deleted file mode 100644 index b14d2f6..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncSession_Private.hpp +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncSession.h" - -#import "RLMSyncUtil_Private.h" -#import - -namespace realm { -class AsyncOpenTask; -class SyncSession; -} - -NS_ASSUME_NONNULL_BEGIN - -@interface RLMSyncSession () { -@public // So it's visible to tests - std::weak_ptr _session; -} RLM_SYNC_UNINITIALIZABLE - -- (instancetype)initWithSyncSession:(std::shared_ptr const&)session; - -/// Wait for pending uploads to complete or the session to expire, and dispatch the callback onto the specified queue. -- (BOOL)waitForUploadCompletionOnQueue:(nullable dispatch_queue_t)queue callback:(void(^)(NSError * _Nullable))callback; - -/// Wait for pending downloads to complete or the session to expire, and dispatch the callback onto the specified queue. -- (BOOL)waitForDownloadCompletionOnQueue:(nullable dispatch_queue_t)queue callback:(void(^)(NSError * _Nullable))callback; - -@end - -@interface RLMSyncErrorActionToken () - -- (instancetype)initWithOriginalPath:(std::string)originalPath; - -@end - -@interface RLMAsyncOpenTask () -@property (nonatomic) std::shared_ptr task; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncSubscription.h b/Lesson14/Pods/Realm/include/RLMSyncSubscription.h deleted file mode 100644 index 307daef..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncSubscription.h +++ /dev/null @@ -1,416 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2018 Realm Inc. -// -// 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 -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - `RLMSyncSubscriptionState` is an enumeration representing the possible state of a sync subscription. - */ -typedef RLM_CLOSED_ENUM(NSInteger, RLMSyncSubscriptionState) { - /** - An error occurred while creating the subscription or while the server was processing it. - */ - RLMSyncSubscriptionStateError = -1, - - /** - The subscription is being created, but has not yet been written to the synced Realm. - */ - RLMSyncSubscriptionStateCreating = 2, - - /** - The subscription has been created, and is waiting to be processed by the server. - */ - RLMSyncSubscriptionStatePending = 0, - - /** - The subscription has been processed by the server, and objects matching the subscription - are now being synchronized to this client. - */ - RLMSyncSubscriptionStateComplete = 1, - - /** - This subscription has been removed. - */ - RLMSyncSubscriptionStateInvalidated = 3, -}; - -/** - `RLMSyncSubscription` represents a subscription to a set of objects in a synced Realm. - - When query-based sync is enabled for a synchronized Realm, the server only - synchronizes objects to the client when they match a sync subscription - registered by that client. A subscription consists of of a query (represented - by an `RLMResults`) and an optional name. - - The state of the subscription can be observed using - [Key-Value Observing](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html) - on the `state` property. - - Subscriptions are created using `-[RLMResults subscribe]` or - `-[RLMResults subscribeWithName:]`. Existing subscriptions for a Realm can be - looked up with `-[RLMRealm subscriptions]` or `-[RLMRealm subscriptionWithName:]`. - */ -@interface RLMSyncSubscription : NSObject - -/** - The unique name for this subscription. - - This will be `nil` if this object was created with `-[RLMResults subscribe]`. - Subscription objects read from a Realm with `-[RLMRealm subscriptions]` will - always have a non-`nil` name and subscriptions which were not explicitly named - will have an automatically generated one. - */ -@property (nonatomic, readonly, nullable) NSString *name; - -/** - The current state of the subscription. See `RLMSyncSubscriptionState`. - */ -@property (nonatomic, readonly) RLMSyncSubscriptionState state; - -/** - The error which occurred when registering this subscription, if any. - - Will be non-nil only when `state` is `RLMSyncSubscriptionStateError`. - */ -@property (nonatomic, readonly, nullable) NSError *error; - -/** - The raw query which this subscription is running on the server. - - This string is a serialized representation of the RLMResults which the - subscription was created from. This representation does *not* use NSPredicate - syntax, and is not guaranteed to remain consistent between versions of Realm. - Any use of this other than manual inspection when debugging is likely to be - incorrect. - - This is `nil` while the subscription is in the Creating state. - */ -@property (nonatomic, readonly, nullable) NSString *query; - -/** - When this subscription was first created. - - This value will be `nil` for subscriptions created with older versions of Realm - which did not store the creation date. Newly created subscriptions should - always have a non-nil creation date. - */ -@property (nonatomic, readonly, nullable) NSDate *createdAt; - -/** - When this subscription was last updated. - - This value will be `nil` for subscriptions created with older versions of Realm - which did not store the update date. Newly created subscriptions should - always have a non-nil update date. - - The update date is the time when the subscription was last updated by a call - to `-[RLMResults subscribeWithOptions:]`, and not when the set of objects which - match the subscription last changed. - */ -@property (nonatomic, readonly, nullable) NSDate *updatedAt; - -/** - When this subscription will be automatically removed. - - If the `timeToLive` parameter is set when creating a sync subscription, the - subscription will be automatically removed the first time that any subscription - is created, modified, or deleted after that time has elapsed. - - This property will be `nil` if the `timeToLive` option was not enabled. - */ -@property (nonatomic, readonly, nullable) NSDate *expiresAt; - -/** - How long this subscription will persist after last being updated. - - If the `timeToLive` parameter is set when creating a sync subscription, the - subscription will be automatically removed the first time that any subscription - is created, modified, or deleted after that time has elapsed. - - This property will be NaN if the `timeToLive` option was not enabled. - */ -@property (nonatomic, readonly) NSTimeInterval timeToLive; - -/** - Remove this subscription. - - Removing a subscription will delete all objects from the local Realm that were - matched only by that subscription and not any remaining subscriptions. The - deletion is performed by the server, and so has no immediate impact on the - contents of the local Realm. If the device is currently offline, the removal - will not be processed until the device returns online. - - Unsubscribing is an asynchronous operation and will not immediately remove the - subscription from the Realm's list of subscriptions. Observe the state property - to be notified of when the subscription has actually been removed. - */ -- (void)unsubscribe; - -#pragma mark - Unavailable Methods - -/** - `-[RLMSyncSubscription init]` is not available because `RLMSyncSubscription` cannot be created directly. - */ -- (instancetype)init __attribute__((unavailable("RLMSyncSubscription cannot be created directly"))); - -/** - `+[RLMSyncSubscription new]` is not available because `RLMSyncSubscription` cannot be created directly. - */ -+ (instancetype)new __attribute__((unavailable("RLMSyncSubscription cannot be created directly"))); - -@end - -/** - Configuration options for query-based sync subscriptions. - */ -@interface RLMSyncSubscriptionOptions : NSObject -/** - The name of the subscription. - - Naming a subscription makes it possible to look up a subscription by name - (using `-[RLMRealm subscriptionWithName:]`) or update an existing - subscription rather than creating a new one. - */ -@property (nonatomic, copy, nullable) NSString *name; - -/** - Whether this should update an existing subscription with the same name. - - By default trying to create a subscription with a name that's already in use - will fail unless the new subscription is an exact match for the existing one. - If this is set to YES, instead the existing subscription will be updated using - the query and options from the new subscription. This only works if the new - subscription is for the same type of objects as the existing subscription. - Trying to overwrite a subscription with a subscription of a different type of - objects will fail. - - The `updatedAt` and (if `timeToLive` is used) `expiresAt` properties are - updated whenever a subscription is overwritten even if nothing else has changed. - */ -@property (nonatomic) BOOL overwriteExisting; - -/** - How long (in seconds) a subscription should persist after being created. - - By default subscriptions are persistent, and last until they are explicitly - removed by calling `unsubscribe()`. Subscriptions can instead be made temporary - by setting the time to live to how long the subscription should remain. After - that time has elapsed the subscription will be automatically removed. - - A time to live of 0 or less disables subscription expiration. - */ -@property (nonatomic) NSTimeInterval timeToLive; - -/** - The maximum number of top-level matches to include in this subscription. - - If more top-level objects than the limit match the query, only the first - `limit` objects will be included. This respects the sort and distinct order of - the query being subscribed to for the determination of what the "first" objects - are. - - The limit does not count or apply to objects which are added indirectly due to - being linked to by the objects in the subscription or due to being listed in - `includeLinkingObjectProperties`. If the limit is larger than the number of - objects which match the query, all objects will be included. A limit of zero is - treated as unlimited. - */ -@property (nonatomic) NSUInteger limit; - -/** - Which RLMLinkingObjects properties should be included in the subscription. - - Outgoing links (i.e. `RLMArray` and `RLMObject` properties) are automatically - included in sync subscriptions. That is, if you subscribe to a query which - matches one object, every object which is reachable via links from that object - are also included in the subscription. - - By default, RLMLinkingObjects properties do not work this way. Instead, they - only report objects which happen to be included in a subscription. By naming - a RLMLinkingObjects property in this array, it can instead be treated as if - it was a RLMArray and include all objects which link to this object. - - Any keypath which ends in a RLMLinkingObject property can be included in this - array, including ones involving intermediate links. - */ -@property (nonatomic, copy, nullable) NSArray *includeLinkingObjectProperties; -@end - -/** - Support for subscribing to the results of object queries in a synced Realm. - */ -@interface RLMResults (SyncSubscription) - -/** - Subscribe to the query represented by this `RLMResults`. - - Subscribing to a query asks the server to synchronize all objects to the - client which match the query, along with all objects which are reachable - from those objects via links. This happens asynchronously, and the local - client Realm may not immediately have all objects which match the query. - Observe the `state` property of the returned subscription object to be - notified of when the subscription has been processed by the server and - all objects matching the query are available. - - The subscription will not be explicitly named. A name will be automatically - generated for internal use. The exact format of this name may change without - warning and should not be depended on. - - @return An object representing the newly-created subscription. - - @see RLMSyncSubscription -*/ -- (RLMSyncSubscription *)subscribe; - -/** - Subscribe to the query represented by this `RLMResults`. - - Subscribing to a query asks the server to synchronize all objects to the - client which match the query, along with all objects which are reachable - from those objects via links. This happens asynchronously, and the local - client Realm may not immediately have all objects which match the query. - Observe the `state` property of the returned subscription object to be - notified of when the subscription has been processed by the server and - all objects matching the query are available. - - Creating a new subscription with the same name and query as an existing - subscription will not create a new subscription, but instead will return - an object referring to the existing sync subscription. This means that - performing the same subscription twice followed by removing it once will - result in no subscription existing. - - The newly created subscription will not be reported by - `-[RLMRealm subscriptions]` or `-[RLMRealm subscriptionWithName:]` until - `state` has transitioned from `RLMSyncSubscriptionStateCreating` to any of the - other states. - - @param subscriptionName The name of the subscription. - - @return An object representing the newly-created subscription. - - @see RLMSyncSubscription -*/ -- (RLMSyncSubscription *)subscribeWithName:(nullable NSString *)subscriptionName; - -/** - Subscribe to a subset of the query represented by this `RLMResults`. - - Subscribing to a query asks the server to synchronize all objects to the - client which match the query, along with all objects which are reachable - from those objects via links. This happens asynchronously, and the local - client Realm may not immediately have all objects which match the query. - Observe the `state` property of the returned subscription object to be - notified of when the subscription has been processed by the server and - all objects matching the query are available. - - Creating a new subscription with the same name and query as an existing - subscription will not create a new subscription, but instead will return - an object referring to the existing sync subscription. This means that - performing the same subscription twice followed by removing it once will - result in no subscription existing. - - The newly created subscription will not be reported by - `-[RLMRealm subscriptions]` or `-[RLMRealm subscriptionWithName:]` until - `state` has transitioned from `RLMSyncSubscriptionStateCreating` to any of the - other states. - - The number of top-level matches may optionally be limited. This limit - respects the sort and distinct order of the query being subscribed to, - if any. Please note that the limit does not count or apply to objects - which are added indirectly due to being linked to by the objects in the - subscription. If the limit is larger than the number of objects which - match the query, all objects will be included. - - @param subscriptionName The name of the subscription - @param limit The maximum number of objects to include in the subscription. - - @return The subscription - - @see RLMSyncSubscription - */ -- (RLMSyncSubscription *)subscribeWithName:(nullable NSString *)subscriptionName limit:(NSUInteger)limit; - -/** - Subscribe to a subset of the query represented by this `RLMResults`. - - Subscribing to a query asks the server to synchronize all objects to the - client which match the query, along with all objects which are reachable - from those objects via links. This happens asynchronously, and the local - client Realm may not immediately have all objects which match the query. - Observe the `state` property of the returned subscription object to be - notified of when the subscription has been processed by the server and - all objects matching the query are available. - - Creating a new subscription with the same name and query as an existing - subscription will not create a new subscription, but instead will return - an object referring to the existing sync subscription. This means that - performing the same subscription twice followed by removing it once will - result in no subscription existing. - - The newly created subscription will not be reported by - `-[RLMRealm subscriptions]` or `-[RLMRealm subscriptionWithName:]` until - `state` has transitioned from `RLMSyncSubscriptionStateCreating` to any of the - other states. - - @param options The additional configuration options for the subscription. - @return The subscription. - - @see RLMSyncSubscription - */ -- (RLMSyncSubscription *)subscribeWithOptions:(RLMSyncSubscriptionOptions *)options; -@end - -/** - Support for managing existing subscriptions to object queries in a Realm. - */ -@interface RLMRealm (SyncSubscription) -/** - Get a list of the query-based sync subscriptions made for this Realm. - - This list includes all subscriptions which are currently in the states `Pending`, - `Created`, and `Error`. Newly created subscriptions which are still in the - `Creating` state are not included, and calling this immediately after calling - `-[RLMResults subscribe]` will typically not include that subscription. Similarly, - because unsubscription happens asynchronously, this may continue to include - subscriptions after `-[RLMSyncSubscription unsubscribe]` is called on them. - - This method can only be called on a Realm which is using query-based sync and - will throw an exception if called on a non-synchronized or full-sync Realm. - */ -- (RLMResults *)subscriptions; - -/** - Look up a specific query-based sync subscription by name. - - Subscriptions are created asynchronously, so calling this immediately after - calling `subscribeWithName:` on a `RLMResults` will typically return `nil`. - Only subscriptions which are currently in the states `Pending`, `Created`, - and `Error` can be retrieved with this method. - - This method can only be called on a Realm which is using query-based sync and - will throw an exception if called on a non-synchronized or full-sync Realm. - - @return The named subscription, or `nil` if no subscription exists with that name. - */ -- (nullable RLMSyncSubscription *)subscriptionWithName:(NSString *)name; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncUser.h b/Lesson14/Pods/Realm/include/RLMSyncUser.h deleted file mode 100644 index d871490..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncUser.h +++ /dev/null @@ -1,536 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import "RLMRealmConfiguration.h" -#import "RLMSyncCredentials.h" -#import "RLMSyncPermission.h" - -@class RLMSyncUser, RLMSyncUserInfo, RLMSyncCredentials, RLMSyncPermission, RLMSyncSession, RLMRealm, RLMSyncPermissionOffer; - -/** - The state of the user object. - */ -typedef NS_ENUM(NSUInteger, RLMSyncUserState) { - /// The user is logged out. Call `logInWithCredentials:...` with valid credentials to log the user back in. - RLMSyncUserStateLoggedOut, - /// The user is logged in, and any Realms associated with it are syncing with the Realm Object Server. - RLMSyncUserStateActive, - /// The user has encountered a fatal error state, and cannot be used. - RLMSyncUserStateError, -}; - -/// A block type used for APIs which asynchronously vend an `RLMSyncUser`. -typedef void(^RLMUserCompletionBlock)(RLMSyncUser * _Nullable, NSError * _Nullable); - -/// A block type used to report the status of a password change operation. -/// If the `NSError` argument is nil, the operation succeeded. -typedef void(^RLMPasswordChangeStatusBlock)(NSError * _Nullable); - -/// A block type used to report the status of a permission apply or revoke operation. -/// If the `NSError` argument is nil, the operation succeeded. -typedef void(^RLMPermissionStatusBlock)(NSError * _Nullable); - -/// A block type used to report the status of a permission offer operation. -typedef void(^RLMPermissionOfferStatusBlock)(NSString * _Nullable, NSError * _Nullable); - -/// A block type used to report the status of a permission offer response operation. -typedef void(^RLMPermissionOfferResponseStatusBlock)(NSURL * _Nullable, NSError * _Nullable); - -/// A block type used to asynchronously report results of a permissions get operation. -/// Exactly one of the two arguments will be populated. -typedef void(^RLMPermissionResultsBlock)(NSArray * _Nullable, NSError * _Nullable); - -/// A block type used to asynchronously report results of a permission offerss get operation. -/// Exactly one of the two arguments will be populated. -typedef void(^RLMPermissionOfferResultsBlock)(NSArray * _Nullable, NSError * _Nullable); - -/// A block type used to asynchronously report results of a user info retrieval. -/// Exactly one of the two arguments will be populated. -typedef void(^RLMRetrieveUserBlock)(RLMSyncUserInfo * _Nullable, NSError * _Nullable); - -/// A block type used to report an error related to a specific user. -typedef void(^RLMUserErrorReportingBlock)(RLMSyncUser * _Nonnull, NSError * _Nonnull); - -NS_ASSUME_NONNULL_BEGIN - -/** - A `RLMSyncUser` instance represents a single Realm Object Server user account. - - A user may have one or more credentials associated with it. These credentials - uniquely identify the user to the authentication provider, and are used to sign - into a Realm Object Server user account. - - Note that user objects are only vended out via SDK APIs, and cannot be directly - initialized. User objects can be accessed from any thread. - */ -@interface RLMSyncUser : NSObject - -/** - A dictionary of all valid, logged-in user identities corresponding to their user objects. - */ -+ (NSDictionary *)allUsers NS_REFINED_FOR_SWIFT; - -/** - The logged-in user. `nil` if none exists. - - @warning Throws an exception if more than one logged-in user exists. - */ -+ (nullable RLMSyncUser *)currentUser NS_REFINED_FOR_SWIFT; - -/** - The unique Realm Object Server user ID string identifying this user. - */ -@property (nullable, nonatomic, readonly) NSString *identity; - -/** - The user's refresh token used to access the Realm Object Server. - - This is required to make HTTP requests to Realm Object Server's REST API - for functionality not exposed natively. It should be treated as sensitive data. - */ -@property (nullable, nonatomic, readonly) NSString *refreshToken; - -/** - The URL of the authentication server this user will communicate with. - */ -@property (nullable, nonatomic, readonly) NSURL *authenticationServer; - -/** - Whether the user is a Realm Object Server administrator. Value reflects the - state at the time of the last successful login of this user. - */ -@property (nonatomic, readonly) BOOL isAdmin; - -/** - The current state of the user. - */ -@property (nonatomic, readonly) RLMSyncUserState state; - -#pragma mark - Lifecycle - -/** - Create, log in, and asynchronously return a new user object, specifying a custom - timeout for the network request and a custom queue to run the callback upon. - Credentials identifying the user must be passed in. The user becomes available in - the completion block, at which point it is ready for use. - */ -+ (void)logInWithCredentials:(RLMSyncCredentials *)credentials - authServerURL:(NSURL *)authServerURL - timeout:(NSTimeInterval)timeout - callbackQueue:(dispatch_queue_t)callbackQueue - onCompletion:(RLMUserCompletionBlock)completion NS_REFINED_FOR_SWIFT; - -/** - Create, log in, and asynchronously return a new user object. - - If the login completes successfully, the completion block will invoked with - a `RLMSyncUser` object representing the logged-in user. This object can be - used to open synchronized Realms. If the login fails, the completion block - will be invoked with an error. - - The completion block always runs on the main queue. - - @param credentials A credentials value identifying the user to be logged in. - @param authServerURL The URL of the authentication server (e.g. "http://realm.example.org:9080"). - @param completion A callback block that returns a user object or an error, - indicating the completion of the login operation. - */ -+ (void)logInWithCredentials:(RLMSyncCredentials *)credentials - authServerURL:(NSURL *)authServerURL - onCompletion:(RLMUserCompletionBlock)completion -NS_SWIFT_UNAVAILABLE("Use the full version of this API."); - - -/** - Returns the default configuration for the user. The default configuration - points to the default query-based Realm on the server the user authenticated against. - */ -- (RLMRealmConfiguration *)configuration NS_REFINED_FOR_SWIFT; - -/** - Create a query-based configuration instance for the given url. - - @param url The unresolved absolute URL to the Realm on the Realm Object Server, - e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the - path should contain the wildcard marker `~`, which will automatically - be filled in with the user identity by the Realm Object Server. - @return A default configuration object with the sync configuration set to use the given URL. - */ -- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; - -/** - Create a configuration instance for the given url. - - @param url The unresolved absolute URL to the Realm on the Realm Object Server, - e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the - path should contain the wildcard marker `~`, which will automatically - be filled in with the user identity by the Realm Object Server. - @param fullSynchronization If YES, all objects in the server Realm are - automatically synchronized, and the query subscription - methods cannot be used. - @return A default configuration object with the sync configuration set to use - the given URL and options. - */ -- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url - fullSynchronization:(bool)fullSynchronization NS_REFINED_FOR_SWIFT; - -/** - Create a configuration instance for the given url. - - @param url The unresolved absolute URL to the Realm on the Realm Object Server, - e.g. "realm://example.org/~/path/to/realm". "Unresolved" means the - path should contain the wildcard marker `~`, which will automatically - be filled in with the user identity by the Realm Object Server. - @param fullSynchronization If YES, all objects in the server Realm are - automatically synchronized, and the query subscription - methods cannot be used. - @param enableSSLValidation If NO, invalid SSL certificates for the server will - not be rejected. THIS SHOULD NEVER BE USED IN - PRODUCTION AND EXISTS ONLY FOR TESTING PURPOSES. - @param urlPrefix A prefix which is prepending to URLs constructed for - the server. This should normally be `nil`, and customized only - to match corresponding settings on the server. - @return A default configuration object with the sync configuration set to use - the given URL and options. - */ -- (RLMRealmConfiguration *)configurationWithURL:(nullable NSURL *)url - fullSynchronization:(bool)fullSynchronization - enableSSLValidation:(bool)enableSSLValidation - urlPrefix:(nullable NSString *)urlPrefix NS_REFINED_FOR_SWIFT; - -/** - Log a user out, destroying their server state, unregistering them from the SDK, - and removing any synced Realms associated with them from on-disk storage on - next app launch. If the user is already logged out or in an error state, this - method does nothing. - - This method should be called whenever the application is committed to not using - a user again unless they are recreated. - Failing to call this method may result in unused files and metadata needlessly - taking up space. - */ -- (void)logOut; - -/** - An optional error handler which can be set to notify the host application when - the user encounters an error. Errors reported by this error handler are always - `RLMSyncAuthError`s. - - @note Check for `RLMSyncAuthErrorInvalidAccessToken` to see if the user has - been remotely logged out because its refresh token expired, or because the - third party authentication service providing the user's identity has - logged the user out. - - @warning Regardless of whether an error handler is installed, certain user errors - will automatically cause the user to enter the logged out state. - */ -@property (nullable, nonatomic) RLMUserErrorReportingBlock errorHandler NS_REFINED_FOR_SWIFT; - -#pragma mark - Sessions - -/** - Retrieve a valid session object belonging to this user for a given URL, or `nil` - if no such object exists. - */ -- (nullable RLMSyncSession *)sessionForURL:(NSURL *)url; - -/** - Retrieve all the valid sessions belonging to this user. - */ -- (NSArray *)allSessions; - -#pragma mark - Passwords - -/** - Change this user's password asynchronously. - - @warning Changing a user's password using an authentication server that doesn't - use HTTPS is a major security flaw, and should only be done while - testing. - - @param newPassword The user's new password. - @param completion Completion block invoked when login has completed or failed. - The callback will be invoked on a background queue provided - by `NSURLSession`. - */ -- (void)changePassword:(NSString *)newPassword completion:(RLMPasswordChangeStatusBlock)completion; - -/** - Change an arbitrary user's password asynchronously. - - @note The current user must be an admin user for this operation to succeed. - - @warning Changing a user's password using an authentication server that doesn't - use HTTPS is a major security flaw, and should only be done while - testing. - - @param newPassword The user's new password. - @param userID The identity of the user whose password should be changed. - @param completion Completion block invoked when login has completed or failed. - The callback will be invoked on a background queue provided - by `NSURLSession`. - */ -- (void)changePassword:(NSString *)newPassword forUserID:(NSString *)userID completion:(RLMPasswordChangeStatusBlock)completion; - -/** - Ask the server to send a password reset email to the given email address. - - If `email` is an email address which is associated with a user account that was - registered using the "password" authentication service, the server will send an - email to that address with a password reset token. No error is reported if the - email address is invalid or not associated with an account. - - @param serverURL The authentication server URL for the user. - @param email The email address to send the email to. - @param completion A block which will be called when the request completes or - fails. The callback will be invoked on a background queue - provided by `NSURLSession`, and not on the calling queue. - */ -+ (void)requestPasswordResetForAuthServer:(NSURL *)serverURL - userEmail:(NSString *)email - completion:(RLMPasswordChangeStatusBlock)completion; - -/** - Change a user's password using a one-time password reset token. - - By default, the password reset email sent by ROS will link to a web site where - the user can select a new password, and the app will not need to call this - method. If you wish to instead handle this within your native app, you must - change the `baseURL` in the server configuration for `PasswordAuthProvider` to - a scheme registered for your app, extract the token from the URL, and call this - method after prompting the user for a new password. - - @warning Changing a user's password using an authentication server that doesn't - use HTTPS is a major security flaw, and should only be done while - testing. - - @param serverURL The authentication server URL for the user. - @param token The one-time use token from the URL. - @param newPassword The user's new password. - @param completion A block which will be called when the request completes or - fails. The callback will be invoked on a background queue - provided by `NSURLSession`, and not on the calling queue. - */ -+ (void)completePasswordResetForAuthServer:(NSURL *)serverURL - token:(NSString *)token - password:(NSString *)newPassword - completion:(RLMPasswordChangeStatusBlock)completion; - -/** - Ask the server to send a confirmation email to the given email address. - - If `email` is an email address which is associated with a user account that was - registered using the "password" authentication service, the server will send an - email to that address with a confirmation token. No error is reported if the - email address is invalid or not associated with an account. - - @param serverURL The authentication server URL for the user. - @param email The email address to send the email to. - @param completion A block which will be called when the request completes or - fails. The callback will be invoked on a background queue - provided by `NSURLSession`, and not on the calling queue. - */ -+ (void)requestEmailConfirmationForAuthServer:(NSURL *)serverURL - userEmail:(NSString *)email - completion:(RLMPasswordChangeStatusBlock)completion; - -/** - Confirm a user's email using a one-time confirmation token. - - By default, the confirmation email sent by ROS will link to a web site with - a generic "thank you for confirming your email" message, and the app will not - need to call this method. If you wish to instead handle this within your native - app, you must change the `baseURL` in the server configuration for - `PasswordAuthProvider` to a scheme registered for your app, extract the token - from the URL, and call this method. - - @param serverURL The authentication server URL for the user. - @param token The one-time use token from the URL. - @param completion A block which will be called when the request completes or - fails. The callback will be invoked on a background queue - provided by `NSURLSession`, and not on the calling queue. - */ -+ (void)confirmEmailForAuthServer:(NSURL *)serverURL - token:(NSString *)token - completion:(RLMPasswordChangeStatusBlock)completion; - -#pragma mark - Administrator - -/** - Given a Realm Object Server authentication provider and a provider identifier for a user - (for example, a username), look up and return user information for that user. - - @param providerUserIdentity The username or identity of the user as issued by the authentication provider. - In most cases this is different from the Realm Object Server-issued identity. - @param provider The authentication provider that manages the user whose information is desired. - @param completion Completion block invoked when request has completed or failed. - The callback will be invoked on a background queue provided - by `NSURLSession`. - */ -- (void)retrieveInfoForUser:(NSString *)providerUserIdentity - identityProvider:(RLMIdentityProvider)provider - completion:(RLMRetrieveUserBlock)completion; - -#pragma mark - Permissions - -/** - Asynchronously retrieve all permissions associated with the user calling this method. - - The results will be returned through the callback block, or an error if the operation failed. - The callback block will be run on a background thread and not the calling thread. - */ -- (void)retrievePermissionsWithCallback:(RLMPermissionResultsBlock)callback; - -/** - Apply a given permission. - - The operation will take place asynchronously, and the callback will be used to report whether - the permission change succeeded or failed. The user calling this method must have the right - to grant the given permission, or else the operation will fail. - - @see `RLMSyncPermission` - */ -- (void)applyPermission:(RLMSyncPermission *)permission callback:(RLMPermissionStatusBlock)callback; - -/** - Create a permission offer for a Realm. - - A permission offer is used to grant access to a Realm this user manages to another - user. Creating a permission offer produces a string token which can be passed to the - recepient in any suitable way (for example, via e-mail). - - The operation will take place asynchronously. The token can be accepted by the recepient - using the `-[RLMSyncUser acceptOfferForToken:callback:]` method. - - @param url The URL of the Realm for which the permission offer should pertain. This - may be the URL of any Realm which this user is allowed to manage. If the URL - has a `~` wildcard it will be replaced with this user's user identity. - @param accessLevel What access level to grant to whoever accepts the token. - @param expirationDate Optionally, a date which indicates when the offer expires. If the - recepient attempts to accept the offer after the date it will be rejected. - @param callback A callback indicating whether the operation succeeded or failed. If it - succeeded the token will be passed in as a string. - - @see `acceptOfferForToken:callback:` - */ -- (void)createOfferForRealmAtURL:(NSURL *)url - accessLevel:(RLMSyncAccessLevel)accessLevel - expiration:(nullable NSDate *)expirationDate - callback:(RLMPermissionOfferStatusBlock)callback NS_REFINED_FOR_SWIFT; - -/** - Accept a permission offer. - - Pass in a token representing a permission offer. The operation will take place asynchronously. - If the operation succeeds, the callback will be passed the URL of the Realm for which the - offer applied, so the Realm can be opened. - - The token this method accepts can be created by the offering user through the - `-[RLMSyncUser createOfferForRealmAtURL:accessLevel:expiration:callback:]` method. - - @see `createOfferForRealmAtURL:accessLevel:expiration:callback:` - */ -- (void)acceptOfferForToken:(NSString *)token - callback:(RLMPermissionOfferResponseStatusBlock)callback; - -/** - Revoke a permission offer. - - Pass in a token representing a permission offer which was created by this - user. The operation will take place asynchronously. If the operation succeeds, - the callback will be passed the URL of the Realm for which the offer was - revoked. After this operation completes, the token can no longer be accepted - by the recipient. - - @see `createOfferForRealmAtURL:accessLevel:expiration:callback:` - */ -- (void)invalidateOfferForToken:(NSString *)token - callback:(RLMPermissionStatusBlock)callback; - -/** - Asynchronously retrieve all pending permission offers created by the calling user. - - The results will be returned through the callback block, or an error if the operation failed. - The callback block will be run on a background thread and not the calling thread. - */ -- (void)retrievePermissionOffersWithCallback:(RLMPermissionOfferResultsBlock)callback; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("RLMSyncUser cannot be created directly"))); -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("RLMSyncUser cannot be created directly"))); - -@end - -#pragma mark - User info classes - -/** - A data object representing a user account associated with a user. - - @see `RLMSyncUserInfo` - */ -@interface RLMSyncUserAccountInfo : NSObject - -/// The authentication provider which manages this user account. -@property (nonatomic, readonly) RLMIdentityProvider provider; - -/// The username or identity of this user account. -@property (nonatomic, readonly) NSString *providerUserIdentity; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly"))); -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("RLMSyncUserAccountInfo cannot be created directly"))); - -@end - -/** - A data object representing information about a user that was retrieved from a user lookup call. - */ -@interface RLMSyncUserInfo : NSObject - -/** - An array of all the user accounts associated with this user. - */ -@property (nonatomic, readonly) NSArray *accounts; - -/** - The identity issued to this user by the Realm Object Server. - */ -@property (nonatomic, readonly) NSString *identity; - -/** - Metadata about this user stored on the Realm Object Server. - */ -@property (nonatomic, readonly) NSDictionary *metadata; - -/** - Whether the user is flagged on the Realm Object Server as an administrator. - */ -@property (nonatomic, readonly) BOOL isAdmin; - -/// :nodoc: -- (instancetype)init __attribute__((unavailable("RLMSyncUserInfo cannot be created directly"))); -/// :nodoc: -+ (instancetype)new __attribute__((unavailable("RLMSyncUserInfo cannot be created directly"))); - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncUser_Private.hpp b/Lesson14/Pods/Realm/include/RLMSyncUser_Private.hpp deleted file mode 100644 index 4c414f6..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncUser_Private.hpp +++ /dev/null @@ -1,71 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncUser.h" - -#import "RLMSyncConfiguration.h" -#import "RLMSyncUtil_Private.h" - -#import "sync/sync_config.hpp" -#import "sync/sync_user.hpp" -#import "sync/impl/sync_metadata.hpp" - -@class RLMSyncConfiguration, RLMSyncSessionRefreshHandle; - -using namespace realm; - -typedef void(^RLMFetchedRealmCompletionBlock)(NSError * _Nullable, RLMRealm * _Nullable, BOOL * _Nonnull); - -NS_ASSUME_NONNULL_BEGIN - -class CocoaSyncUserContext : public SyncUserContext { -public: - void register_refresh_handle(const std::string& path, RLMSyncSessionRefreshHandle *handle); - void unregister_refresh_handle(const std::string& path); - void invalidate_all_handles(); - - RLMUserErrorReportingBlock error_handler() const; - void set_error_handler(RLMUserErrorReportingBlock); - -private: - /** - A map of paths to 'refresh handles'. - - A refresh handle is an object that encapsulates the concept of periodically - refreshing the Realm's access token before it expires. Tokens are indexed by their - paths (e.g. `/~/path/to/realm`). - */ - std::unordered_map m_refresh_handles; - std::mutex m_mutex; - - /** - An optional callback invoked when the authentication server reports the user as - being in an expired state. - */ - RLMUserErrorReportingBlock m_error_handler; - mutable std::mutex m_error_handler_mutex; -}; - -@interface RLMSyncUser () -- (instancetype)initWithSyncUser:(std::shared_ptr)user; -- (NSURL *)defaultRealmURL; -- (std::shared_ptr)_syncUser; -+ (void)_setUpBindingContextFactory; -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncUtil.h b/Lesson14/Pods/Realm/include/RLMSyncUtil.h deleted file mode 100644 index 222dcb7..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncUtil.h +++ /dev/null @@ -1,191 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -/// A token originating from the Realm Object Server. -typedef NSString* RLMServerToken; - -NS_ASSUME_NONNULL_BEGIN - -/// A user info key for use with `RLMSyncErrorClientResetError`. -extern NSString *const kRLMSyncPathOfRealmBackupCopyKey; - -/// A user info key for use with certain error types. -extern NSString *const kRLMSyncErrorActionTokenKey; - -/** - The error domain string for all SDK errors related to errors reported - by the synchronization manager error handler, as well as general sync - errors that don't fall into any of the other categories. - */ -extern NSString *const RLMSyncErrorDomain; - -/** - The error domain string for all SDK errors related to the authentication - endpoint. - */ -extern NSString *const RLMSyncAuthErrorDomain; - -/** - The error domain string for all SDK errors related to the permissions - system and APIs. - */ -extern NSString *const RLMSyncPermissionErrorDomain; - -/** - An error related to a problem that might be reported by the synchronization manager - error handler, or a callback on a sync-related API that performs asynchronous work. - */ -typedef RLM_ERROR_ENUM(NSInteger, RLMSyncError, RLMSyncErrorDomain) { - - /// An error that indicates a problem with the session (a specific Realm opened for sync). - RLMSyncErrorClientSessionError = 4, - - /// An error that indicates a problem with a specific user. - RLMSyncErrorClientUserError = 5, - - /** - An error that indicates an internal, unrecoverable problem - with the underlying synchronization engine. - */ - RLMSyncErrorClientInternalError = 6, - - /** - An error that indicates the Realm needs to be reset. - - A synced Realm may need to be reset because the Realm Object Server encountered an - error and had to be restored from a backup. If the backup copy of the remote Realm - is of an earlier version than the local copy of the Realm, the server will ask the - client to reset the Realm. - - The reset process is as follows: the local copy of the Realm is copied into a recovery - directory for safekeeping, and then deleted from the original location. The next time - the Realm for that URL is opened, the Realm will automatically be re-downloaded from the - Realm Object Server, and can be used as normal. - - Data written to the Realm after the local copy of the Realm diverged from the backup - remote copy will be present in the local recovery copy of the Realm file. The - re-downloaded Realm will initially contain only the data present at the time the Realm - was backed up on the server. - - The client reset process can be initiated in one of two ways. - - The `userInfo` dictionary contains an opaque token object under the key - `kRLMSyncErrorActionTokenKey`. This token can be passed into - `+[RLMSyncSession immediatelyHandleError:]` in order to immediately perform the client - reset process. This should only be done after your app closes and invalidates every - instance of the offending Realm on all threads (note that autorelease pools may make this - difficult to guarantee). - - If `+[RLMSyncSession immediatelyHandleError:]` is not called, the client reset process - will be automatically carried out the next time the app is launched and the - `RLMSyncManager` singleton is accessed. - - The value for the `kRLMSyncPathOfRealmBackupCopyKey` key in the `userInfo` dictionary - describes the path of the recovered copy of the Realm. This copy will not actually be - created until the client reset process is initiated. - - @see `-[NSError rlmSync_errorActionToken]`, `-[NSError rlmSync_clientResetBackedUpRealmPath]` - */ - RLMSyncErrorClientResetError = 7, - - /** - An error that indicates an authentication error occurred. - - The `kRLMSyncUnderlyingErrorKey` key in the user info dictionary will contain the - underlying error, which is guaranteed to be under the `RLMSyncAuthErrorDomain` - error domain. - */ - RLMSyncErrorUnderlyingAuthError = 8, - - /** - An error that indicates the user does not have permission to perform an operation - upon a synced Realm. For example, a user may receive this error if they attempt to - open a Realm they do not have at least read access to, or write to a Realm they only - have read access to. - - This error may also occur if a user incorrectly opens a Realm they have read-only - permissions to without using the `asyncOpen()` APIs. - - A Realm that suffers a permission denied error is, by default, flagged so that its - local copy will be deleted the next time the application starts. - - The `userInfo` dictionary contains an opaque token object under the key - `kRLMSyncErrorActionTokenKey`. This token can be passed into - `+[RLMSyncSession immediatelyHandleError:]` in order to immediately delete the local - copy. This should only be done after your app closes and invalidates every instance - of the offending Realm on all threads (note that autorelease pools may make this - difficult to guarantee). - - @warning It is strongly recommended that, if a Realm has encountered a permission denied - error, its files be deleted before attempting to re-open it. - - @see `-[NSError rlmSync_errorActionToken]` - */ - RLMSyncErrorPermissionDeniedError = 9, -}; - -/// An error which is related to authentication to a Realm Object Server. -typedef RLM_ERROR_ENUM(NSInteger, RLMSyncAuthError, RLMSyncAuthErrorDomain) { - /// An error that indicates that the response received from the authentication server was malformed. - RLMSyncAuthErrorBadResponse = 1, - - /// An error that indicates that the supplied Realm path was invalid, or could not be resolved by the authentication - /// server. - RLMSyncAuthErrorBadRemoteRealmPath = 2, - - /// An error that indicates that the response received from the authentication server was an HTTP error code. The - /// `userInfo` dictionary contains the actual error code value. - RLMSyncAuthErrorHTTPStatusCodeError = 3, - - /// An error that indicates a problem with the session (a specific Realm opened for sync). - RLMSyncAuthErrorClientSessionError = 4, - - /// An error that indicates that the provided credentials are ill-formed. - RLMSyncAuthErrorInvalidParameters = 601, - - /// An error that indicates that no Realm path was included in the URL. - RLMSyncAuthErrorMissingPath = 602, - - /// An error that indicates that the provided credentials are invalid. - RLMSyncAuthErrorInvalidCredential = 611, - - /// An error that indicates that the user with provided credentials does not exist. - RLMSyncAuthErrorUserDoesNotExist = 612, - - /// An error that indicates that the user cannot be registered as it exists already. - RLMSyncAuthErrorUserAlreadyExists = 613, - - /// An error that indicates the path is invalid or the user doesn't have access to that Realm. - RLMSyncAuthErrorAccessDeniedOrInvalidPath = 614, - - /// An error that indicates the refresh token was invalid. - RLMSyncAuthErrorInvalidAccessToken = 615, - - /// An error that indicates the permission offer is expired. - RLMSyncAuthErrorExpiredPermissionOffer = 701, - - /// An error that indicates the permission offer is ambiguous. - RLMSyncAuthErrorAmbiguousPermissionOffer = 702, - - /// An error that indicates the file at the given path can't be shared. - RLMSyncAuthErrorFileCannotBeShared = 703, -}; - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.h b/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.h deleted file mode 100644 index 6b2c9c4..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.h +++ /dev/null @@ -1,136 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -#import -#import -#import - -typedef NS_ENUM(NSUInteger, RLMSyncSystemErrorKind) { - // Specific - RLMSyncSystemErrorKindClientReset, - RLMSyncSystemErrorKindPermissionDenied, - // General - RLMSyncSystemErrorKindClient, - RLMSyncSystemErrorKindConnection, - RLMSyncSystemErrorKindSession, - RLMSyncSystemErrorKindUser, - RLMSyncSystemErrorKindUnknown, -}; - -@class RLMSyncUser; - -typedef void(^RLMSyncCompletionBlock)(NSError * _Nullable, NSDictionary * _Nullable); -typedef void(^RLMSyncBasicErrorReportingBlock)(NSError * _Nullable); - -typedef NSString* RLMServerPath; - -NS_ASSUME_NONNULL_BEGIN - -extern RLMIdentityProvider const RLMIdentityProviderAccessToken; -extern RLMIdentityProvider const RLMIdentityProviderRealm; -extern RLMIdentityProvider const RLMIdentityProviderCustomRefreshToken; - -extern NSString *const kRLMSyncAppIDKey; -extern NSString *const kRLMSyncDataKey; -extern NSString *const kRLMSyncErrorJSONKey; -extern NSString *const kRLMSyncErrorStatusCodeKey; -extern NSString *const kRLMSyncIdentityKey; -extern NSString *const kRLMSyncIsAdminKey; -extern NSString *const kRLMSyncNewPasswordKey; -extern NSString *const kRLMSyncPasswordKey; -extern NSString *const kRLMSyncPathKey; -extern NSString *const kRLMSyncTokenKey; -extern NSString *const kRLMSyncProviderKey; -extern NSString *const kRLMSyncProviderIDKey; -extern NSString *const kRLMSyncRegisterKey; -extern NSString *const kRLMSyncUnderlyingErrorKey; -extern NSString *const kRLMSyncUserIDKey; - -FOUNDATION_EXTERN uint8_t RLMGetComputedPermissions(RLMRealm *realm, id _Nullable object); - -#define RLM_SYNC_UNINITIALIZABLE \ -- (instancetype)init __attribute__((unavailable("This type cannot be created directly"))); \ -+ (instancetype)new __attribute__((unavailable("This type cannot be created directly"))); - -NS_ASSUME_NONNULL_END - -/// A macro to parse a string out of a JSON dictionary, or return nil. -#define RLM_SYNC_PARSE_STRING_OR_ABORT(json_macro_val, key_macro_val, prop_macro_val) \ -{ \ -id data = json_macro_val[key_macro_val]; \ -if (![data isKindOfClass:[NSString class]]) { return nil; } \ -self.prop_macro_val = data; \ -} \ - -#define RLM_SYNC_PARSE_OPTIONAL_STRING(json_macro_val, key_macro_val, prop_macro_val) \ -{ \ -id data = json_macro_val[key_macro_val]; \ -if (![data isKindOfClass:[NSString class]]) { data = nil; } \ -self.prop_macro_val = data; \ -} \ - -#define RLM_SYNC_PARSE_OPTIONAL_BOOL(json_macro_val, key_macro_val, prop_macro_val) \ -{ \ -id data = json_macro_val[key_macro_val]; \ -if (![data isKindOfClass:[NSNumber class]]) { data = @NO; } \ -self.prop_macro_val = [data boolValue]; \ -} \ - -/// A macro to parse a double out of a JSON dictionary, or return nil. -#define RLM_SYNC_PARSE_DOUBLE_OR_ABORT(json_macro_val, key_macro_val, prop_macro_val) \ -{ \ -id data = json_macro_val[key_macro_val]; \ -if (![data isKindOfClass:[NSNumber class]]) { return nil; } \ -self.prop_macro_val = [data doubleValue]; \ -} \ - -/// A macro to build a sub-model out of a JSON dictionary, or return nil. -#define RLM_SYNC_PARSE_MODEL_OR_ABORT(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ -{ \ -id raw = json_macro_val[key_macro_val]; \ -if (![raw isKindOfClass:[NSDictionary class]]) { return nil; } \ -id model = [[class_macro_val alloc] initWithDictionary:raw]; \ -if (!model) { return nil; } \ -self.prop_macro_val = model; \ -} \ - -/// A macro to build an array of sub-models out of a JSON dictionary, or return nil. -#define RLM_SYNC_PARSE_MODEL_ARRAY_OR_ABORT(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ -{ \ -NSArray *jsonArray = json_macro_val[key_macro_val]; \ -if (![jsonArray isKindOfClass:[NSArray class]]) { return nil; } \ -NSMutableArray *buffer = [NSMutableArray array]; \ -for (id value in jsonArray) { \ -id next = nil; \ -if ([value isKindOfClass:[NSDictionary class]]) { next = [[class_macro_val alloc] initWithDictionary:value]; } \ -if (!next) { return nil; } \ -[buffer addObject:next]; \ -} \ -self.prop_macro_val = [buffer copy]; \ -} \ - -#define RLM_SYNC_PARSE_OPTIONAL_MODEL(json_macro_val, key_macro_val, class_macro_val, prop_macro_val) \ -{ \ -id model; \ -id raw = json_macro_val[key_macro_val]; \ -if (![raw isKindOfClass:[NSDictionary class]]) { model = nil; } \ -else { model = [[class_macro_val alloc] initWithDictionary:raw]; } \ -self.prop_macro_val = model; \ -} \ diff --git a/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.hpp b/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.hpp deleted file mode 100644 index 8e622d1..0000000 --- a/Lesson14/Pods/Realm/include/RLMSyncUtil_Private.hpp +++ /dev/null @@ -1,53 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMSyncUtil_Private.h" - -#import "RLMSyncConfiguration_Private.h" -#import "RLMSyncPermission.h" - -#import "sync/sync_manager.hpp" -#import "realm/util/optional.hpp" - -@class RLMSyncErrorResponseModel; -class CocoaSyncUserContext; - -namespace realm { -enum class AccessLevel; -} - -realm::SyncSessionStopPolicy translateStopPolicy(RLMSyncStopPolicy stopPolicy); -RLMSyncStopPolicy translateStopPolicy(realm::SyncSessionStopPolicy stop_policy); - -std::shared_ptr sync_session_for_realm(RLMRealm *realm); - -#pragma mark - Get user context - -CocoaSyncUserContext& context_for(const std::shared_ptr& user); - -#pragma mark - Error construction - -NSError *make_auth_error_bad_response(NSDictionary *json=nil); -NSError *make_auth_error_http_status(NSInteger status); -NSError *make_auth_error_client_issue(); -NSError *make_auth_error(RLMSyncErrorResponseModel *responseModel); - -// Set 'code' to NSNotFound to not actually have an error code. -NSError *make_sync_error(RLMSyncSystemErrorKind kind, NSString *description, NSInteger code, NSDictionary *custom); -NSError *make_sync_error(NSError *wrapped_auth_error); -NSError *make_sync_error(std::error_code, RLMSyncSystemErrorKind kind=RLMSyncSystemErrorKindSession); diff --git a/Lesson14/Pods/Realm/include/RLMThreadSafeReference.h b/Lesson14/Pods/Realm/include/RLMThreadSafeReference.h deleted file mode 100644 index a935ebe..0000000 --- a/Lesson14/Pods/Realm/include/RLMThreadSafeReference.h +++ /dev/null @@ -1,106 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 - -@class RLMRealm; - -NS_ASSUME_NONNULL_BEGIN - -/** - Objects of types which conform to `RLMThreadConfined` can be managed by a Realm, which will make - them bound to a thread-specific `RLMRealm` instance. Managed objects must be explicitly exported - and imported to be passed between threads. - - Managed instances of objects conforming to this protocol can be converted to a thread-safe - reference for transport between threads by passing to the - `+[RLMThreadSafeReference referenceWithThreadConfined:]` constructor. - - Note that only types defined by Realm can meaningfully conform to this protocol, and defining new - classes which attempt to conform to it will not make them work with `RLMThreadSafeReference`. - */ -@protocol RLMThreadConfined -// Conformance to the `RLMThreadConfined_Private` protocol will be enforced at runtime. - -/** - The Realm which manages the object, or `nil` if the object is unmanaged. - - Unmanaged objects are not confined to a thread and cannot be passed to methods expecting a - `RLMThreadConfined` object. - */ -@property (nonatomic, readonly, nullable) RLMRealm *realm; - -/// Indicates if the object can no longer be accessed because it is now invalid. -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - -@end - -/** - An object intended to be passed between threads containing a thread-safe reference to its - thread-confined object. - - To resolve a thread-safe reference on a target Realm on a different thread, pass to - `-[RLMRealm resolveThreadSafeReference:]`. - - @warning A `RLMThreadSafeReference` object must be resolved at most once. - Failing to resolve a `RLMThreadSafeReference` will result in the source version of the - Realm being pinned until the reference is deallocated. - - @note Prefer short-lived `RLMThreadSafeReference`s as the data for the version of the source Realm - will be retained until all references have been resolved or deallocated. - - @see `RLMThreadConfined` - @see `-[RLMRealm resolveThreadSafeReference:]` - */ -@interface RLMThreadSafeReference<__covariant Confined : id> : NSObject - -/** - Create a thread-safe reference to the thread-confined object. - - @param threadConfined The thread-confined object to create a thread-safe reference to. - - @note You may continue to use and access the thread-confined object after passing it to this - constructor. - */ -+ (instancetype)referenceWithThreadConfined:(Confined)threadConfined; - -/** - Indicates if the reference can no longer be resolved because an attempt to resolve it has already - occurred. References can only be resolved once. - */ -@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated; - -#pragma mark - Unavailable Methods - -/** - `-[RLMThreadSafeReference init]` is not available because `RLMThreadSafeReference` cannot be - created directly. `RLMThreadSafeReference` instances must be obtained by calling - `-[RLMRealm resolveThreadSafeReference:]`. - */ -- (instancetype)init __attribute__((unavailable("RLMThreadSafeReference cannot be created directly"))); - -/** - `-[RLMThreadSafeReference new]` is not available because `RLMThreadSafeReference` cannot be - created directly. `RLMThreadSafeReference` instances must be obtained by calling - `-[RLMRealm resolveThreadSafeReference:]`. - */ -+ (instancetype)new __attribute__((unavailable("RLMThreadSafeReference cannot be created directly"))); - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMThreadSafeReference_Private.hpp b/Lesson14/Pods/Realm/include/RLMThreadSafeReference_Private.hpp deleted file mode 100644 index 5cf78ed..0000000 --- a/Lesson14/Pods/Realm/include/RLMThreadSafeReference_Private.hpp +++ /dev/null @@ -1,44 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 "RLMThreadSafeReference.h" -#import "thread_safe_reference.hpp" - -NS_ASSUME_NONNULL_BEGIN - -@protocol RLMThreadConfined_Private - -// Constructs a new `ThreadSafeReference` -- (std::unique_ptr)makeThreadSafeReference; - -// The extra information needed to construct an instance of this type from the Object Store type -@property (nonatomic, readonly, nullable) id objectiveCMetadata; - -// Constructs an new instance of this type -+ (nullable instancetype)objectWithThreadSafeReference:(std::unique_ptr)reference - metadata:(nullable id)metadata - realm:(RLMRealm *)realm; -@end - -@interface RLMThreadSafeReference () - -- (nullable id)resolveReferenceInRealm:(RLMRealm *)realm; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Lesson14/Pods/Realm/include/RLMUpdateChecker.hpp b/Lesson14/Pods/Realm/include/RLMUpdateChecker.hpp deleted file mode 100644 index 7f01ac7..0000000 --- a/Lesson14/Pods/Realm/include/RLMUpdateChecker.hpp +++ /dev/null @@ -1,20 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -// Asynchronously check for updates to Realm if running on a simulator -void RLMCheckForUpdates(); diff --git a/Lesson14/Pods/Realm/include/RLMUtil.hpp b/Lesson14/Pods/Realm/include/RLMUtil.hpp deleted file mode 100644 index 6e72dd5..0000000 --- a/Lesson14/Pods/Realm/include/RLMUtil.hpp +++ /dev/null @@ -1,182 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 -#import -#import - -#import -#import -#import -#import -#import - -namespace realm { - class Mixed; -} - -@class RLMObjectSchema; -@class RLMProperty; - -namespace realm { - class RealmFileException; -} - -__attribute__((format(NSString, 1, 2))) -NSException *RLMException(NSString *fmt, ...); -NSException *RLMException(std::exception const& exception); - -NSError *RLMMakeError(RLMError code, std::exception const& exception); -NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError&); -NSError *RLMMakeError(RLMError code, const realm::RealmFileException&); -NSError *RLMMakeError(std::system_error const& exception); - -void RLMSetErrorOrThrow(NSError *error, NSError **outError); - -// returns if the object can be inserted as the given type -BOOL RLMIsObjectValidForProperty(id obj, RLMProperty *prop); -// throw an exception if the object is not a valid value for the property -void RLMValidateValueForProperty(id obj, RLMObjectSchema *objectSchema, - RLMProperty *prop, bool validateObjects=false); -BOOL RLMValidateValue(id value, RLMPropertyType type, bool optional, bool array, - NSString *objectClassName); - -void RLMThrowTypeError(id obj, RLMObjectSchema *objectSchema, RLMProperty *prop); - -// gets default values for the given schema (+defaultPropertyValues) -// merges with native property defaults if Swift class -NSDictionary *RLMDefaultValuesForObjectSchema(RLMObjectSchema *objectSchema); - -BOOL RLMIsDebuggerAttached(); -BOOL RLMIsRunningInPlayground(); - -// C version of isKindOfClass -static inline BOOL RLMIsKindOfClass(Class class1, Class class2) { - while (class1) { - if (class1 == class2) return YES; - class1 = class_getSuperclass(class1); - } - return NO; -} - -template -static inline T *RLMDynamicCast(__unsafe_unretained id obj) { - if ([obj isKindOfClass:[T class]]) { - return obj; - } - return nil; -} - -static inline id RLMCoerceToNil(__unsafe_unretained id obj) { - if (static_cast(obj) == NSNull.null) { - return nil; - } - else if (__unsafe_unretained auto optional = RLMDynamicCast(obj)) { - return RLMCoerceToNil(RLMGetOptional(optional)); - } - return obj; -} - -template -static inline T RLMCoerceToNil(__unsafe_unretained T obj) { - return RLMCoerceToNil(static_cast(obj)); -} - -id RLMAsFastEnumeration(id obj); - -// String conversion utilities -static inline NSString * RLMStringDataToNSString(realm::StringData stringData) { - static_assert(sizeof(NSUInteger) >= sizeof(size_t), - "Need runtime overflow check for size_t to NSUInteger conversion"); - if (stringData.is_null()) { - return nil; - } - else { - return [[NSString alloc] initWithBytes:stringData.data() - length:stringData.size() - encoding:NSUTF8StringEncoding]; - } -} - -static inline realm::StringData RLMStringDataWithNSString(__unsafe_unretained NSString *const string) { - static_assert(sizeof(size_t) >= sizeof(NSUInteger), - "Need runtime overflow check for NSUInteger to size_t conversion"); - return realm::StringData(string.UTF8String, - [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); -} - -// Binary conversion utilities -static inline NSData *RLMBinaryDataToNSData(realm::BinaryData binaryData) { - return binaryData ? [NSData dataWithBytes:binaryData.data() length:binaryData.size()] : nil; -} - -static inline realm::BinaryData RLMBinaryDataForNSData(__unsafe_unretained NSData *const data) { - // this is necessary to ensure that the empty NSData isn't treated by core as the null realm::BinaryData - // because data.bytes == 0 when data.length == 0 - // the casting bit ensures that we create a data with a non-null pointer - auto bytes = static_cast(data.bytes) ?: static_cast((__bridge void *)data); - return realm::BinaryData(bytes, data.length); -} - -// Date conversion utilities -// These use the reference date and shift the seconds rather than just getting -// the time interval since the epoch directly to avoid losing sub-second precision -static inline NSDate *RLMTimestampToNSDate(realm::Timestamp ts) NS_RETURNS_RETAINED { - if (ts.is_null()) - return nil; - auto timeInterval = ts.get_seconds() - NSTimeIntervalSince1970 + ts.get_nanoseconds() / 1'000'000'000.0; - return [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:timeInterval]; -} - -static inline realm::Timestamp RLMTimestampForNSDate(__unsafe_unretained NSDate *const date) { - if (!date) - return {}; - auto timeInterval = date.timeIntervalSinceReferenceDate; - if (isnan(timeInterval)) - return {0, 0}; // Arbitrary choice - - // Clamp dates that we can't represent as a Timestamp to the maximum value - if (timeInterval >= std::numeric_limits::max() - NSTimeIntervalSince1970) - return {std::numeric_limits::max(), 1'000'000'000 - 1}; - if (timeInterval - NSTimeIntervalSince1970 < std::numeric_limits::min()) - return {std::numeric_limits::min(), -1'000'000'000 + 1}; - - auto seconds = static_cast(timeInterval); - auto nanoseconds = static_cast((timeInterval - seconds) * 1'000'000'000.0); - seconds += static_cast(NSTimeIntervalSince1970); - - // Seconds and nanoseconds have to have the same sign - if (nanoseconds < 0 && seconds > 0) { - nanoseconds += 1'000'000'000; - --seconds; - } - return {seconds, nanoseconds}; -} - -static inline NSUInteger RLMConvertNotFound(size_t index) { - return index == realm::not_found ? NSNotFound : index; -} - -id RLMMixedToObjc(realm::Mixed const& value); - -// Given a bundle identifier, return the base directory on the disk within which Realm database and support files should -// be stored. -NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier); - -// Get a NSDateFormatter for ISO8601-formatted strings -NSDateFormatter *RLMISO8601Formatter(); diff --git a/Lesson14/Pods/Realm/include/Realm.h b/Lesson14/Pods/Realm/include/Realm.h deleted file mode 100644 index f460336..0000000 --- a/Lesson14/Pods/Realm/include/Realm.h +++ /dev/null @@ -1,41 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2014 Realm Inc. -// -// 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 - -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import -#import diff --git a/Lesson14/Pods/Realm/include/audit.hpp b/Lesson14/Pods/Realm/include/audit.hpp deleted file mode 100644 index 81ea76b..0000000 --- a/Lesson14/Pods/Realm/include/audit.hpp +++ /dev/null @@ -1,34 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2018 Realm Inc. -// -// 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. -// -//////////////////////////////////////////////////////////////////////////// - -namespace realm { -class Table; -class TableView; -template class BasicRowExpr; -using RowExpr = BasicRowExpr
; -struct VersionID; - -class AuditInterface { -public: - virtual ~AuditInterface() {} - - virtual void record_query(realm::VersionID, realm::TableView const&) = 0; - virtual void record_read(realm::VersionID, realm::RowExpr) = 0; - virtual void record_write(realm::VersionID, realm::VersionID) = 0; -}; -} diff --git a/Lesson14/Pods/Realm/include/binding_callback_thread_observer.hpp b/Lesson14/Pods/Realm/include/binding_callback_thread_observer.hpp deleted file mode 100644 index e956349..0000000 --- a/Lesson14/Pods/Realm/include/binding_callback_thread_observer.hpp +++ /dev/null @@ -1,42 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP -#define REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP - -#include - -namespace realm { -// Interface for bindings interested in registering callbacks before/after the ObjectStore thread runs. -// This is for example helpful to attach/detach the pthread to the JavaVM in order to be able to perform JNI calls. -class BindingCallbackThreadObserver { -public: - // This method is called just before the thread is started - virtual void did_create_thread() = 0; - - // This method is called just before the thread is being destroyed - virtual void will_destroy_thread() = 0; - - // This method is called with any exception throws by client.run(). - virtual void handle_error(std::exception const& e) = 0; -}; - -extern BindingCallbackThreadObserver* g_binding_callback_thread_observer; -} - -#endif // REALM_OS_BINDING_CALLBACK_THREAD_OBSERVER_HPP diff --git a/Lesson14/Pods/Realm/include/binding_context.hpp b/Lesson14/Pods/Realm/include/binding_context.hpp deleted file mode 100644 index 8d7532c..0000000 --- a/Lesson14/Pods/Realm/include/binding_context.hpp +++ /dev/null @@ -1,185 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 BINDING_CONTEXT_HPP -#define BINDING_CONTEXT_HPP - -#include "index_set.hpp" - -#include -#include -#include - -namespace realm { -// BindingContext is the extension point for adding binding-specific behavior to -// a SharedRealm. It can be used to store additional data associated with the -// Realm which is needed by the binding, and there are several methods which -// can be overridden to receive notifications of state changes within the Realm. -// -// A simple implementation which lets the user register functions to be -// called on refresh could look like the following: -// -// class BindingContextImplementation : public BindingContext { -// public: -// // A token returned from add_notification that can be used to remove the -// // notification later -// struct token : private std::list>::iterator { -// token(std::list>::iterator it) : std::list>::iterator(it) { } -// friend class DelegateImplementation; -// }; -// -// token add_notification(std::function func) -// { -// m_registered_notifications.push_back(std::move(func)); -// return token(std::prev(m_registered_notifications.end())); -// } -// -// void remove_notification(token entry) -// { -// m_registered_notifications.erase(entry); -// } -// -// // Override the did_change method to call each registered notification -// void did_change(std::vector const&, std::vector const&, bool) override -// { -// // Loop oddly so that unregistering a notification from within the -// // registered function works -// for (auto it = m_registered_notifications.begin(); it != m_registered_notifications.end(); ) { -// (*it++)(); -// } -// } -// -// private: -// std::list> m_registered_notifications; -// }; -class Realm; -class Schema; -class BindingContext { -public: - virtual ~BindingContext() = default; - - std::weak_ptr realm; - - // If the user adds a notification handler to the Realm, will it ever - // actually be called? - virtual bool can_deliver_notifications() const noexcept { return true; } - - // Called when the Realm is about to send notifications about Realm, - // Collection or Object changes. This method will be called even if - // no notification callbacks have been registered. - virtual void will_send_notifications() { } - - // Called when the Realm is done sending all change notifications. This method - // will be called even if no notification callbacks have been registered. - virtual void did_send_notifications() { } - - // Called by the Realm when refresh called or a notification arrives which - // is triggered through write transaction committed by itself or a different - // Realm instance. - virtual void before_notify() { } - - // Called by the Realm when a write transaction is committed to the file by - // a different Realm instance (possibly in a different process) - virtual void changes_available() { } - - struct ObserverState; - - // Override this function if you want to receive detailed information about - // external changes to a specific set of objects. - // This is called before each operation which may advance the read - // transaction to include - // ObserverStates for each row for which detailed change information is - // desired. - virtual std::vector get_observed_rows() { return {}; } - - // Called immediately before the read transaction is advanced if detailed - // change information was requested (by returning a non-empty array from - // get_observed_rows()). - // The observers vector is the vector returned by get_observed_row(), - // updated with change information. The invalidated vector is a list of the - // `info` fields of observed rows which will be deleted. - virtual void will_change(std::vector const& observers, - std::vector const& invalidated); - - // Called immediately after the read transaction version is advanced. Unlike - // will_change(), this is called even if detailed change information was not - // requested or if the Realm is not actually in a read transaction, although - // both vectors will be empty in that case. - virtual void did_change(std::vector const& observers, - std::vector const& invalidated, - bool version_changed=true); - - // Called immediately after the corresponding Realm's schema is changed through - // update_schema()/set_schema_subset() or the schema is changed by another Realm - // instance. The parameter is a schema reference which is the same as the return - // value of Realm::schema(). - virtual void schema_did_change(Schema const&) {} - - // Change information for a single field of a row - struct ColumnInfo { - // The index of this column prior to the changes in the tracked - // transaction, or -1 for newly inserted columns. - size_t initial_column_index = -1; - // What kind of change occurred? - // Always Set or None for everything but LinkList columns. - enum class Kind { - None, // No change - Set, // The value or entries at `indices` were assigned to - Insert, // New values were inserted at each of the indices given - Remove, // Values were removed at each of the indices given - SetAll // The entire LinkList has been replaced with a new set of values - } kind = Kind::None; - // The indices where things happened for Set, Insert and Remove on - // LinkList columns. Not used for other types or for None or SetAll. - IndexSet indices; - }; - - // Information about an observed row in a table - // - // Each object which needs detailed change information should have an - // ObserverState entry in the vector returned from get_observed_rows(), with - // the initial table and row indexes set (and optionally the info field). - // The Realm parses the transaction log, and populates the `changes` vector - // in each ObserverState with information about what changes were made. - struct ObserverState { - // Initial table and row which is observed - // May be updated by row insertions and removals - size_t table_ndx; - size_t row_ndx; - - // Opaque userdata for the delegate's use - void* info; - - // Populated with information about which columns were changed - // May be shorter than the actual number of columns if the later columns - // are not modified - std::vector changes; - - // Simple lexographic ordering - friend bool operator<(ObserverState const& lft, ObserverState const& rgt) - { - return std::tie(lft.table_ndx, lft.row_ndx) < std::tie(rgt.table_ndx, rgt.row_ndx); - } - }; -}; - -inline void BindingContext::will_change(std::vector const&, std::vector const&) { } -inline void BindingContext::did_change(std::vector const&, std::vector const&, bool) { } -} // namespace realm - -#endif /* BINDING_CONTEXT_HPP */ diff --git a/Lesson14/Pods/Realm/include/collection_notifications.hpp b/Lesson14/Pods/Realm/include/collection_notifications.hpp deleted file mode 100644 index bbd41e5..0000000 --- a/Lesson14/Pods/Realm/include/collection_notifications.hpp +++ /dev/null @@ -1,182 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2016 Realm Inc. -// -// 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 REALM_COLLECTION_NOTIFICATIONS_HPP -#define REALM_COLLECTION_NOTIFICATIONS_HPP - -#include "index_set.hpp" -#include "util/atomic_shared_ptr.hpp" - -#include -#include -#include -#include - -namespace realm { -namespace _impl { - class CollectionNotifier; -} - -// A token which keeps an asynchronous query alive -struct NotificationToken { - NotificationToken() = default; - NotificationToken(std::shared_ptr<_impl::CollectionNotifier> notifier, uint64_t token); - ~NotificationToken(); - - NotificationToken(NotificationToken&&); - NotificationToken& operator=(NotificationToken&&); - - NotificationToken(NotificationToken const&) = delete; - NotificationToken& operator=(NotificationToken const&) = delete; - - void suppress_next(); - -private: - util::AtomicSharedPtr<_impl::CollectionNotifier> m_notifier; - uint64_t m_token; -}; - -struct CollectionChangeSet { - struct Move { - size_t from; - size_t to; - - bool operator==(Move m) const noexcept { return from == m.from && to == m.to; } - }; - - // Indices which were removed from the _old_ collection - IndexSet deletions; - - // Indices in the _new_ collection which are new insertions - IndexSet insertions; - - // Indices of objects in the _old_ collection which were modified - IndexSet modifications; - - // Indices in the _new_ collection which were modified. This will always - // have the same number of indices as `modifications` and conceptually - // represents the same entries, just in different versions of the collection. - // It exists for the sake of code which finds it easier to process - // modifications after processing deletions and insertions rather than before. - IndexSet modifications_new; - - // Rows in the collection which moved. - // - // Every `from` index will also be present in `deletions` and every `to` - // index will be present in `insertions`. - // - // This is currently not reliably calculated for all types of collections. A - // reported move will always actually be a move, but there may also be - // unreported moves which show up only as a delete/insert pair. - std::vector moves; - - // Per-column version of `modifications` - std::vector columns; - - bool empty() const noexcept - { - return deletions.empty() && insertions.empty() && modifications.empty() - && modifications_new.empty() && moves.empty(); - } -}; - -// A type-erasing wrapper for the callback for collection notifications. Can be -// constructed with either any callable compatible with the signature -// `void (CollectionChangeSet, std::exception_ptr)`, an object with member -// functions `void before(CollectionChangeSet)`, `void after(CollectionChangeSet)`, -// `void error(std::exception_ptr)`, or a pointer to such an object. If a pointer -// is given, the caller is responsible for ensuring that the pointed-to object -// outlives the collection. -class CollectionChangeCallback { -public: - CollectionChangeCallback(std::nullptr_t={}) { } - - template - CollectionChangeCallback(Callback cb) : m_impl(make_impl(std::move(cb))) { } - template - CollectionChangeCallback& operator=(Callback cb) { m_impl = make_impl(std::move(cb)); return *this; } - - // Explicitly default the copy/move constructors as otherwise they'll use - // the above ones and add an extra layer of wrapping - CollectionChangeCallback(CollectionChangeCallback&&) = default; - CollectionChangeCallback(CollectionChangeCallback const&) = default; - CollectionChangeCallback& operator=(CollectionChangeCallback&&) = default; - CollectionChangeCallback& operator=(CollectionChangeCallback const&) = default; - - void before(CollectionChangeSet const& c) { m_impl->before(c); } - void after(CollectionChangeSet const& c) { m_impl->after(c); } - void error(std::exception_ptr e) { m_impl->error(e); } - - explicit operator bool() const { return !!m_impl; } - -private: - struct Base { - virtual ~Base() {} - virtual void before(CollectionChangeSet const&)=0; - virtual void after(CollectionChangeSet const&)=0; - virtual void error(std::exception_ptr)=0; - }; - - template()(CollectionChangeSet(), std::exception_ptr()))> - std::shared_ptr make_impl(Callback cb) - { - return std::make_shared>(std::move(cb)); - } - - template().after(CollectionChangeSet())), typename = void> - std::shared_ptr make_impl(Callback cb) - { - return std::make_shared>(std::move(cb)); - } - - template().after(CollectionChangeSet())), typename = void> - std::shared_ptr make_impl(Callback* cb) - { - return std::make_shared>(cb); - } - - template - struct Impl : public Base { - T impl; - Impl(T impl) : impl(std::move(impl)) { } - void before(CollectionChangeSet const&) override { } - void after(CollectionChangeSet const& change) override { impl(change, {}); } - void error(std::exception_ptr error) override { impl({}, error); } - }; - template - struct Impl2 : public Base { - T impl; - Impl2(T impl) : impl(std::move(impl)) { } - void before(CollectionChangeSet const& c) override { impl.before(c); } - void after(CollectionChangeSet const& c) override { impl.after(c); } - void error(std::exception_ptr error) override { impl.error(error); } - }; - template - struct Impl3 : public Base { - T* impl; - Impl3(T* impl) : impl(impl) { } - void before(CollectionChangeSet const& c) override { impl->before(c); } - void after(CollectionChangeSet const& c) override { impl->after(c); } - void error(std::exception_ptr error) override { impl->error(error); } - }; - - std::shared_ptr m_impl; -}; -} // namespace realm - -#endif // REALM_COLLECTION_NOTIFICATIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm.hpp b/Lesson14/Pods/Realm/include/core/realm.hpp deleted file mode 100644 index 7ede53f..0000000 --- a/Lesson14/Pods/Realm/include/core/realm.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_HPP -#define REALM_HPP - -#include -#include -#include -#include -#include -#include -#include - -#endif // REALM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/alloc.hpp b/Lesson14/Pods/Realm/include/core/realm/alloc.hpp deleted file mode 100644 index 157d244..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/alloc.hpp +++ /dev/null @@ -1,387 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ALLOC_HPP -#define REALM_ALLOC_HPP - -#include -#include -#include - -#include -#include -#include - -namespace realm { - -class Allocator; - -class Replication; - -using ref_type = size_t; - -int_fast64_t from_ref(ref_type) noexcept; -ref_type to_ref(int_fast64_t) noexcept; -int64_t to_int64(size_t value) noexcept; - -class MemRef { -public: - MemRef() noexcept; - ~MemRef() noexcept; - - MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept; - MemRef(ref_type ref, Allocator& alloc) noexcept; - - char* get_addr(); - ref_type get_ref(); - void set_ref(ref_type ref); - void set_addr(char* addr); - -private: - char* m_addr; - ref_type m_ref; -#if REALM_ENABLE_MEMDEBUG - // Allocator that created m_ref. Used to verify that the ref is valid whenever you call - // get_ref()/get_addr and that it e.g. has not been free'ed - const Allocator* m_alloc = nullptr; -#endif -}; - - -/// The common interface for Realm allocators. -/// -/// A Realm allocator must associate a 'ref' to each allocated -/// object and be able to efficiently map any 'ref' to the -/// corresponding memory address. The 'ref' is an integer and it must -/// always be divisible by 8. Also, a value of zero is used to -/// indicate a null-reference, and must therefore never be returned by -/// Allocator::alloc(). -/// -/// The purpose of the 'refs' is to decouple the memory reference from -/// the actual address and thereby allowing objects to be relocated in -/// memory without having to modify stored references. -/// -/// \sa SlabAlloc -class Allocator { -public: - /// The specified size must be divisible by 8, and must not be - /// zero. - /// - /// \throw std::bad_alloc If insufficient memory was available. - MemRef alloc(size_t size); - - /// Calls do_realloc(). - /// - /// Note: The underscore has been added because the name `realloc` - /// would conflict with a macro on the Windows platform. - MemRef realloc_(ref_type, const char* addr, size_t old_size, size_t new_size); - - /// Calls do_free(). - /// - /// Note: The underscore has been added because the name `free - /// would conflict with a macro on the Windows platform. - void free_(ref_type, const char* addr) noexcept; - - /// Shorthand for free_(mem.get_ref(), mem.get_addr()). - void free_(MemRef mem) noexcept; - - /// Calls do_translate(). - char* translate(ref_type ref) const noexcept; - - /// Returns true if, and only if the object at the specified 'ref' - /// is in the immutable part of the memory managed by this - /// allocator. The method by which some objects become part of the - /// immuatble part is entirely up to the class that implements - /// this interface. - bool is_read_only(ref_type) const noexcept; - - /// Returns a simple allocator that can be used with free-standing - /// Realm objects (such as a free-standing table). A - /// free-standing object is one that is not part of a Group, and - /// therefore, is not part of an actual database. - static Allocator& get_default() noexcept; - - virtual ~Allocator() noexcept; - - // Disable copying. Copying an allocator can produce double frees. - Allocator(const Allocator&) = delete; - Allocator& operator=(const Allocator&) = delete; - - virtual void verify() const = 0; - -#ifdef REALM_DEBUG - /// Terminate the program precisely when the specified 'ref' is - /// freed (or reallocated). You can use this to detect whether the - /// ref is freed (or reallocated), and even to get a stacktrace at - /// the point where it happens. Call watch(0) to stop watching - /// that ref. - void watch(ref_type ref) - { - m_debug_watch = ref; - } -#endif - - Replication* get_replication() noexcept; - -protected: - size_t m_baseline = 0; // Separation line between immutable and mutable refs. - - Replication* m_replication = nullptr; - - ref_type m_debug_watch = 0; - - /// The specified size must be divisible by 8, and must not be - /// zero. - /// - /// \throw std::bad_alloc If insufficient memory was available. - virtual MemRef do_alloc(const size_t size) = 0; - - /// The specified size must be divisible by 8, and must not be - /// zero. - /// - /// The default version of this function simply allocates a new - /// chunk of memory, copies over the old contents, and then frees - /// the old chunk. - /// - /// \throw std::bad_alloc If insufficient memory was available. - virtual MemRef do_realloc(ref_type, char* addr, size_t old_size, size_t new_size) = 0; - - /// Release the specified chunk of memory. - virtual void do_free(ref_type, char* addr) noexcept = 0; - - /// Map the specified \a ref to the corresponding memory - /// address. Note that if is_read_only(ref) returns true, then the - /// referenced object is to be considered immutable, and it is - /// then entirely the responsibility of the caller that the memory - /// is not modified by way of the returned memory pointer. - virtual char* do_translate(ref_type ref) const noexcept = 0; - - Allocator() noexcept; - - // FIXME: This really doesn't belong in an allocator, but it is the best - // place for now, because every table has a pointer leading here. It would - // be more obvious to place it in Group, but that would add a runtime overhead, - // and access is time critical. - // - // This means that multiple threads that allocate Realm objects through the - // default allocator will share this variable, which is a logical design flaw - // that can make sync_if_needed() re-run queries even though it is not required. - // It must be atomic because it's shared. - std::atomic m_table_versioning_counter; - std::atomic m_latest_observed_counter; - - /// Bump the global version counter. This method should be called when - /// version bumping is initiated. Then following calls to should_propagate_version() - /// can be used to prune the version bumping. - void bump_global_version() noexcept; - - /// Determine if the "local_version" is out of sync, so that it should - /// be updated. In that case: also update it. Called from Table::bump_version - /// to control propagation of version updates on tables within the group. - bool should_propagate_version(uint_fast64_t& local_version) noexcept; - - /// Note the current global version has been observed. - void observe_version() noexcept; - - friend class Table; - friend class Group; -}; - -inline void Allocator::bump_global_version() noexcept -{ - if (m_latest_observed_counter == m_table_versioning_counter) - m_table_versioning_counter += 1; -} - - -inline void Allocator::observe_version() noexcept -{ - if (m_latest_observed_counter != m_table_versioning_counter) - m_latest_observed_counter.store(m_table_versioning_counter, std::memory_order_relaxed); -} - - -inline bool Allocator::should_propagate_version(uint_fast64_t& local_version) noexcept -{ - if (local_version != m_table_versioning_counter) { - local_version = m_table_versioning_counter; - return true; - } - else { - return false; - } -} - - -// Implementation: - -inline int_fast64_t from_ref(ref_type v) noexcept -{ - // Check that v is divisible by 8 (64-bit aligned). - REALM_ASSERT_DEBUG(v % 8 == 0); - - static_assert(std::is_same::value, - "If ref_type changes, from_ref and to_ref should probably be updated"); - - // Make sure that we preserve the bit pattern of the ref_type (without sign extension). - return util::from_twos_compl(uint_fast64_t(v)); -} - -inline ref_type to_ref(int_fast64_t v) noexcept -{ - // Check that v is divisible by 8 (64-bit aligned). - REALM_ASSERT_DEBUG(v % 8 == 0); - - // C++11 standard, paragraph 4.7.2 [conv.integral]: - // If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source - // integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's - // complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is - // no truncation). - end note ] - static_assert(std::is_unsigned::value, - "If ref_type changes, from_ref and to_ref should probably be updated"); - return ref_type(v); -} - -inline int64_t to_int64(size_t value) noexcept -{ - // FIXME: Enable once we get clang warning flags correct - // REALM_ASSERT_DEBUG(value <= std::numeric_limits::max()); - return static_cast(value); -} - - -inline MemRef::MemRef() noexcept - : m_addr(nullptr) - , m_ref(0) -{ -} - -inline MemRef::~MemRef() noexcept -{ -} - -inline MemRef::MemRef(char* addr, ref_type ref, Allocator& alloc) noexcept - : m_addr(addr) - , m_ref(ref) -{ - static_cast(alloc); -#if REALM_ENABLE_MEMDEBUG - m_alloc = &alloc; -#endif -} - -inline MemRef::MemRef(ref_type ref, Allocator& alloc) noexcept - : m_addr(alloc.translate(ref)) - , m_ref(ref) -{ - static_cast(alloc); -#if REALM_ENABLE_MEMDEBUG - m_alloc = &alloc; -#endif -} - -inline char* MemRef::get_addr() -{ -#if REALM_ENABLE_MEMDEBUG - // Asserts if the ref has been freed - m_alloc->translate(m_ref); -#endif - return m_addr; -} - -inline ref_type MemRef::get_ref() -{ -#if REALM_ENABLE_MEMDEBUG - // Asserts if the ref has been freed - m_alloc->translate(m_ref); -#endif - return m_ref; -} - -inline void MemRef::set_ref(ref_type ref) -{ -#if REALM_ENABLE_MEMDEBUG - // Asserts if the ref has been freed - m_alloc->translate(ref); -#endif - m_ref = ref; -} - -inline void MemRef::set_addr(char* addr) -{ - m_addr = addr; -} - -inline MemRef Allocator::alloc(size_t size) -{ - return do_alloc(size); -} - -inline MemRef Allocator::realloc_(ref_type ref, const char* addr, size_t old_size, size_t new_size) -{ -#ifdef REALM_DEBUG - if (ref == m_debug_watch) - REALM_TERMINATE("Allocator watch: Ref was reallocated"); -#endif - return do_realloc(ref, const_cast(addr), old_size, new_size); -} - -inline void Allocator::free_(ref_type ref, const char* addr) noexcept -{ -#ifdef REALM_DEBUG - if (ref == m_debug_watch) - REALM_TERMINATE("Allocator watch: Ref was freed"); -#endif - return do_free(ref, const_cast(addr)); -} - -inline void Allocator::free_(MemRef mem) noexcept -{ - free_(mem.get_ref(), mem.get_addr()); -} - -inline char* Allocator::translate(ref_type ref) const noexcept -{ - return do_translate(ref); -} - -inline bool Allocator::is_read_only(ref_type ref) const noexcept -{ - REALM_ASSERT_DEBUG(ref != 0); - REALM_ASSERT_DEBUG(m_baseline != 0); // Attached SlabAlloc - return ref < m_baseline; -} - -inline Allocator::Allocator() noexcept -{ - m_table_versioning_counter = 0; - m_latest_observed_counter = 0; -} - -inline Allocator::~Allocator() noexcept -{ -} - -inline Replication* Allocator::get_replication() noexcept -{ - return m_replication; -} - -} // namespace realm - -#endif // REALM_ALLOC_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/alloc_slab.hpp b/Lesson14/Pods/Realm/include/core/realm/alloc_slab.hpp deleted file mode 100644 index e07edea..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/alloc_slab.hpp +++ /dev/null @@ -1,745 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ALLOC_SLAB_HPP -#define REALM_ALLOC_SLAB_HPP - -#include // unint8_t etc -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace realm { - -// Pre-declarations -class Group; -class GroupWriter; - - -/// Thrown by Group and SharedGroup constructors if the specified file -/// (or memory buffer) does not appear to contain a valid Realm -/// database. -struct InvalidDatabase; - - -/// The allocator that is used to manage the memory of a Realm -/// group, i.e., a Realm database. -/// -/// Optionally, it can be attached to an pre-existing database (file -/// or memory buffer) which then becomes an immuatble part of the -/// managed memory. -/// -/// To attach a slab allocator to a pre-existing database, call -/// attach_file() or attach_buffer(). To create a new database -/// in-memory, call attach_empty(). -/// -/// For efficiency, this allocator manages its mutable memory as a set -/// of slabs. -class SlabAlloc : public Allocator { -public: - ~SlabAlloc() noexcept override; - SlabAlloc(); - - // Disable copying. Copying an allocator can produce double frees. - SlabAlloc(const SlabAlloc&) = delete; - SlabAlloc& operator=(const SlabAlloc&) = delete; - - /// \struct Config - /// \brief Storage for combining setup flags for initialization to - /// the SlabAlloc. - /// - /// \var Config::is_shared - /// Must be true if, and only if we are called on behalf of SharedGroup. - /// - /// \var Config::read_only - /// Open the file in read-only mode. This implies \a Config::no_create. - /// - /// \var Config::no_create - /// Fail if the file does not already exist. - /// - /// \var Config::skip_validate - /// Skip validation of file header. In a - /// set of overlapping SharedGroups, only the first one (the one - /// that creates/initlializes the coordination file) may validate - /// the header, otherwise it will result in a race condition. - /// - /// \var Config::encryption_key - /// 32-byte key to use to encrypt and decrypt the backing storage, - /// or nullptr to disable encryption. - /// - /// \var Config::session_initiator - /// If set, the caller is the session initiator and - /// guarantees exclusive access to the file. If attaching in - /// read/write mode, the file is modified: files on streaming form - /// is changed to non-streaming form, and if needed the file size - /// is adjusted to match mmap boundaries. - /// Must be set to false if is_shared is false. - /// - /// \var Config::clear_file - /// Always initialize the file as if it was a newly - /// created file and ignore any pre-existing contents. Requires that - /// Config::session_initiator be true as well. - struct Config { - bool is_shared = false; - bool read_only = false; - bool no_create = false; - bool skip_validate = false; - bool session_initiator = false; - bool clear_file = false; - bool disable_sync = false; - const char* encryption_key = nullptr; - }; - - struct Retry { - }; - - /// \brief Attach this allocator to the specified file. - /// - /// It is an error if this function is called at a time where the specified - /// Realm file (file system inode) is modified asynchronously. - /// - /// In non-shared mode (when this function is called on behalf of a - /// free-standing Group instance), it is the responsibility of the - /// application to ensure that the Realm file is not modified concurrently - /// from any other thread or process. - /// - /// In shared mode (when this function is called on behalf of a SharedGroup - /// instance), the caller (SharedGroup::do_open()) must take steps to ensure - /// cross-process mutual exclusion. - /// - /// Except for \a file_path, the parameters are passed in through a - /// configuration object. - /// - /// \return The `ref` of the root node, or zero if there is none. - /// - /// Please note that attach_file can fail to attach to a file due to a - /// collision with a writer extending the file. This can only happen if the - /// caller is *not* the session initiator. When this happens, attach_file() - /// throws SlabAlloc::Retry, and the caller must retry the call. The caller - /// should check if it has become the session initiator before retrying. - /// This can happen if the conflicting thread (or process) terminates or - /// crashes before the next retry. - /// - /// \throw util::File::AccessError - /// \throw SlabAlloc::Retry - ref_type attach_file(const std::string& file_path, Config& cfg); - - /// Get the attached file. Only valid when called on an allocator with - /// an attached file. - util::File& get_file(); - - /// Attach this allocator to the specified memory buffer. - /// - /// It is an error to call this function on an attached - /// allocator. Doing so will result in undefined behavor. - /// - /// \return The `ref` of the root node, or zero if there is none. - /// - /// \sa own_buffer() - /// - /// \throw InvalidDatabase - ref_type attach_buffer(const char* data, size_t size); - - /// Reads file format from file header. Must be called from within a write - /// transaction. - int get_committed_file_format_version() const noexcept; - - bool is_file_on_streaming_form() const - { - const Header& header = *reinterpret_cast(m_data); - return is_file_on_streaming_form(header); - } - - /// Attach this allocator to an empty buffer. - /// - /// It is an error to call this function on an attached - /// allocator. Doing so will result in undefined behavor. - void attach_empty(); - - /// Detach from a previously attached file or buffer. - /// - /// This function does not reset free space tracking. To - /// completely reset the allocator, you must also call - /// reset_free_space_tracking(). - /// - /// This function has no effect if the allocator is already in the - /// detached state (idempotency). - void detach() noexcept; - - class DetachGuard; - - /// If a memory buffer has been attached using attach_buffer(), - /// mark it as owned by this slab allocator. Behaviour is - /// undefined if this function is called on a detached allocator, - /// one that is not attached using attach_buffer(), or one for - /// which this function has already been called during the latest - /// attachment. - void own_buffer() noexcept; - - /// Returns true if, and only if this allocator is currently - /// in the attached state. - bool is_attached() const noexcept; - - /// Returns true if, and only if this allocator is currently in - /// the attached state and attachment was not established using - /// attach_empty(). - bool nonempty_attachment() const noexcept; - - /// Reserve disk space now to avoid allocation errors at a later - /// point in time, and to minimize on-disk fragmentation. In some - /// cases, less fragmentation translates into improved - /// performance. On flash or SSD-drives this is likely a waste. - /// - /// Note: File::prealloc() may misbehave under race conditions (see - /// documentation of File::prealloc()). For that reason, to avoid race - /// conditions, when this allocator is used in a transactional mode, this - /// function may be called only when the caller has exclusive write - /// access. In non-transactional mode it is the responsibility of the user - /// to ensure non-concurrent file mutation. - /// - /// This function will call File::sync(). - /// - /// It is an error to call this function on an allocator that is not - /// attached to a file. Doing so will result in undefined behavior. - void resize_file(size_t new_file_size); - -#ifdef REALM_DEBUG - /// Deprecated method, only called from a unit test - /// - /// WARNING: This method is NOT thread safe on multiple platforms; see - /// File::prealloc(). - /// - /// Reserve disk space now to avoid allocation errors at a later point in - /// time, and to minimize on-disk fragmentation. In some cases, less - /// fragmentation translates into improved performance. On SSD-drives - /// preallocation is likely a waste. - /// - /// When supported by the system, a call to this function will make the - /// database file at least as big as the specified size, and cause space on - /// the target device to be allocated (note that on many systems on-disk - /// allocation is done lazily by default). If the file is already bigger - /// than the specified size, the size will be unchanged, and on-disk - /// allocation will occur only for the initial section that corresponds to - /// the specified size. - /// - /// This function will call File::sync() if it changes the size of the file. - /// - /// It is an error to call this function on an allocator that is not - /// attached to a file. Doing so will result in undefined behavior. - void reserve_disk_space(size_t size_in_bytes); -#endif - - /// Get the size of the attached database file or buffer in number - /// of bytes. This size is not affected by new allocations. After - /// attachment, it can only be modified by a call to update_reader_view(). - /// - /// It is an error to call this function on a detached allocator, - /// or one that was attached using attach_empty(). Doing so will - /// result in undefined behavior. - size_t get_baseline() const noexcept; - - /// Get the total amount of managed memory. This is the baseline plus the - /// sum of the sizes of the allocated slabs. It includes any free space. - /// - /// It is an error to call this function on a detached - /// allocator. Doing so will result in undefined behavior. - size_t get_total_size() const noexcept; - - /// Mark all mutable memory (ref-space outside the attached file) as free - /// space. - void reset_free_space_tracking(); - - /// Update the readers view of the file: - /// - /// Remap the attached file such that a prefix of the specified - /// size becomes available in memory. If sucessfull, - /// get_baseline() will return the specified new file size. - /// - /// It is an error to call this function on a detached allocator, - /// or one that was not attached using attach_file(). Doing so - /// will result in undefined behavior. - /// - /// The file_size argument must be aligned to a *section* boundary: - /// The database file is logically split into sections, each section - /// guaranteed to be mapped as a contiguous address range. The allocation - /// of memory in the file must ensure that no allocation crosses the - /// boundary between two sections. - /// - /// Clears any allocator specicific caching of address translations - /// and force any later address translations to trigger decryption if required. - void update_reader_view(size_t file_size); - - /// Returns true initially, and after a call to reset_free_space_tracking() - /// up until the point of the first call to SlabAlloc::alloc(). Note that a - /// call to SlabAlloc::alloc() corresponds to a mutation event. - bool is_free_space_clean() const noexcept; - - /// Returns the amount of memory requested by calls to SlabAlloc::alloc(). - size_t get_commit_size() const - { - return m_commit_size; - } - - /// Returns the total amount of memory currently allocated in slab area - size_t get_allocated_size() const noexcept; - - /// Returns total amount of slab for all slab allocators - static size_t get_total_slab_size() noexcept; - - /// Hooks used to keep the encryption layer informed of the start and stop - /// of transactions. - void note_reader_start(const void* reader_id); - void note_reader_end(const void* reader_id) noexcept; - - void verify() const override; -#ifdef REALM_DEBUG - void enable_debug(bool enable) - { - m_debug_out = enable; - } - bool is_all_free() const; - void print() const; -#endif - struct MappedFile; - -protected: - MemRef do_alloc(const size_t size) override; - MemRef do_realloc(ref_type, char*, size_t old_size, size_t new_size) override; - // FIXME: It would be very nice if we could detect an invalid free operation in debug mode - void do_free(ref_type, char*) noexcept override; - char* do_translate(ref_type) const noexcept override; - - /// Returns the first section boundary *above* the given position. - size_t get_upper_section_boundary(size_t start_pos) const noexcept; - - /// Returns the first section boundary *at or below* the given position. - size_t get_lower_section_boundary(size_t start_pos) const noexcept; - - /// Returns true if the given position is at a section boundary - bool matches_section_boundary(size_t pos) const noexcept; - - /// Returns the index of the section holding a given address. - /// The section index is determined solely by the minimal section size, - /// and does not necessarily reflect the mapping. A mapping may - /// cover multiple sections - the initial mapping often does. - size_t get_section_index(size_t pos) const noexcept; - - /// Reverse: get the base offset of a section at a given index. Since the - /// computation is very time critical, this method just looks it up in - /// a table. The actual computation and setup of that table is done - /// during initialization with the help of compute_section_base() below. - inline size_t get_section_base(size_t index) const noexcept; - - /// Actually compute the starting offset of a section. Only used to initialize - /// a table of predefined results, which are then used by get_section_base(). - size_t compute_section_base(size_t index) const noexcept; - - /// Find a possible allocation of 'request_size' that will fit into a section - /// which is inside the range from 'start_pos' to 'start_pos'+'free_chunk_size' - /// If found return the position, if not return 0. - size_t find_section_in_range(size_t start_pos, size_t free_chunk_size, size_t request_size) const noexcept; - -private: - void internal_invalidate_cache() noexcept; - enum AttachMode { - attach_None, // Nothing is attached - attach_OwnedBuffer, // We own the buffer (m_data = nullptr for empty buffer) - attach_UsersBuffer, // We do not own the buffer - attach_SharedFile, // On behalf of SharedGroup - attach_UnsharedFile // Not on behalf of SharedGroup - }; - - // A slab is a dynamically allocated contiguous chunk of memory used to - // extend the amount of space available for database node - // storage. Inter-node references are represented as file offsets - // (a.k.a. "refs"), and each slab creates an apparently seamless extension - // of this file offset addressable space. Slabs are stored as rows in the - // Slabs table in order of ascending file offsets. - struct Slab { - ref_type ref_end; - std::unique_ptr addr; - size_t size; - - Slab(ref_type r, size_t s); - Slab(Slab&& slab) - : ref_end(slab.ref_end) - , addr(std::move(slab.addr)) - , size(slab.size) - { - slab.size = 0; - } - ~Slab(); - }; - - struct Chunk { // describes a freed in-file block - ref_type ref; - size_t size; - }; - - // free blocks that are in the slab area are managed using the following structures: - // - FreeBlock: Placed at the start of any free space. Holds the 'ref' corresponding to - // the start of the space, and prev/next links used to place it in a size-specific - // freelist. - // - BetweenBlocks: Structure sitting between any two free OR allocated spaces. - // describes the size of the space before and after. - // Each slab (area obtained from the underlying system) has a terminating BetweenBlocks - // at the beginning and at the end of the Slab. - struct FreeBlock { - ref_type ref; // ref for this entry. Saves a reverse translate / representing links as refs - FreeBlock* prev; // circular doubly linked list - FreeBlock* next; - void clear_links() - { - prev = next = nullptr; - } - void unlink(); - }; - struct BetweenBlocks { // stores sizes and used/free status of blocks before and after. - int32_t block_before_size; // negated if block is in use, - int32_t block_after_size; // positive if block is free - and zero at end - }; - - Config m_cfg; - using FreeListMap = std::map; // log(N) addressing for larger blocks - FreeListMap m_block_map; - - // abstract notion of a freelist - used to hide whether a freelist - // is residing in the small blocks or the large blocks structures. - struct FreeList { - int size = 0; // size of every element in the list, 0 if not found - FreeListMap::iterator it; - bool found_something() - { - return size != 0; - } - bool found_exact(int sz) - { - return size == sz; - } - }; - - // simple helper functions for accessing/navigating blocks and betweenblocks (TM) - BetweenBlocks* bb_before(FreeBlock* entry) const { - return reinterpret_cast(entry) - 1; - } - BetweenBlocks* bb_after(FreeBlock* entry) const { - auto bb = bb_before(entry); - size_t sz = bb->block_after_size; - char* addr = reinterpret_cast(entry) + sz; - return reinterpret_cast(addr); - } - FreeBlock* block_before(BetweenBlocks* bb) const { - size_t sz = bb->block_before_size; - if (sz <= 0) - return nullptr; // only blocks that are not in use - char* addr = reinterpret_cast(bb) - sz; - return reinterpret_cast(addr); - } - FreeBlock* block_after(BetweenBlocks* bb) const { - if (bb->block_after_size <= 0) - return nullptr; - return reinterpret_cast(bb + 1); - } - int size_from_block(FreeBlock* entry) const { - return bb_before(entry)->block_after_size; - } - void mark_allocated(FreeBlock* entry); - // mark the entry freed in bordering BetweenBlocks. Also validate size. - void mark_freed(FreeBlock* entry, int size); - - // hook for the memory verifier in Group. - template - void for_all_free_entries(Func f) const; - - // Main entry points for alloc/free: - FreeBlock* allocate_block(int size); - void free_block(ref_type ref, FreeBlock* addr); - - // Searching/manipulating freelists - FreeList find(int size); - FreeList find_larger(FreeList hint, int size); - FreeBlock* pop_freelist_entry(FreeList list); - void push_freelist_entry(FreeBlock* entry); - void remove_freelist_entry(FreeBlock* element); - void rebuild_freelists_from_slab(); - void clear_freelists(); - - // grow the slab area to accommodate the requested size. - // returns a free block large enough to handle the request. - FreeBlock* grow_slab_for(int request_size); - // create a single free chunk with "BetweenBlocks" at both ends and a - // single free chunk between them. This free chunk will be of size: - // slab_size - 2 * sizeof(BetweenBlocks) - FreeBlock* slab_to_entry(const Slab& slab, ref_type ref_start); - - // breaking/merging of blocks - FreeBlock* get_prev_block_if_mergeable(FreeBlock* block); - FreeBlock* get_next_block_if_mergeable(FreeBlock* block); - // break 'block' to give it 'new_size'. Return remaining block. - // If the block is too small to split, return nullptr. - FreeBlock* break_block(FreeBlock* block, int new_size); - FreeBlock* merge_blocks(FreeBlock* first, FreeBlock* second); - - // Values of each used bit in m_flags - enum { - flags_SelectBit = 1, - }; - - // 24 bytes - struct Header { - uint64_t m_top_ref[2]; // 2 * 8 bytes - // Info-block 8-bytes - uint8_t m_mnemonic[4]; // "T-DB" - uint8_t m_file_format[2]; // See `library_file_format` - uint8_t m_reserved; - // bit 0 of m_flags is used to select between the two top refs. - uint8_t m_flags; - }; - - // 16 bytes - struct StreamingFooter { - uint64_t m_top_ref; - uint64_t m_magic_cookie; - }; - - static_assert(sizeof(Header) == 24, "Bad header size"); - static_assert(sizeof(StreamingFooter) == 16, "Bad footer size"); - - static const Header empty_file_header; - static void init_streaming_header(Header*, int file_format_version); - - static const uint_fast64_t footer_magic_cookie = 0x3034125237E526C8ULL; - - // The mappings are shared, if they are from a file - std::shared_ptr m_file_mappings; - - // We are caching local copies of all the additional mappings to allow - // for lock-free lookup during ref->address translation (we do not need - // to cache the first mapping, because it is immutable) (well, all the - // mappings are immutable, but the array holding them is not - it may - // have to be relocated) - std::unique_ptr>[]> m_local_mappings; - size_t m_num_local_mappings = 0; - - const char* m_data = nullptr; - size_t m_initial_chunk_size = 0; - size_t m_initial_section_size = 0; - int m_section_shifts = 0; - std::unique_ptr m_section_bases; - size_t m_num_section_bases = 0; - AttachMode m_attach_mode = attach_None; - enum FeeeSpaceState { - free_space_Clean, - free_space_Dirty, - free_space_Invalid, - }; - - /// When set to free_space_Invalid, the free lists are no longer - /// up-to-date. This happens if do_free() or - /// reset_free_space_tracking() fails, presumably due to - /// std::bad_alloc being thrown during updating of the free space - /// list. In this this case, alloc(), realloc_(), and - /// get_free_read_only() must throw. This member is deliberately - /// placed here (after m_attach_mode) in the hope that it leads to - /// less padding between members due to alignment requirements. - FeeeSpaceState m_free_space_state = free_space_Clean; - - typedef std::vector Slabs; - using Chunks = std::map; - Slabs m_slabs; - Chunks m_free_read_only; - size_t m_commit_size = 0; - - bool m_debug_out = false; - struct hash_entry { - ref_type ref = 0; - const char* addr = nullptr; - size_t version = 0; - }; - mutable hash_entry cache[256]; - mutable size_t version = 1; - - /// Throws if free-lists are no longer valid. - size_t consolidate_free_read_only(); - /// Throws if free-lists are no longer valid. - const Chunks& get_free_read_only() const; - - /// Throws InvalidDatabase if the file is not a Realm file, if the file is - /// corrupted, or if the specified encryption key is incorrect. This - /// function will not detect all forms of corruption, though. - void validate_buffer(const char* data, size_t len, const std::string& path); - void throw_header_exception(std::string msg, const Header& header, const std::string& path); - - static bool is_file_on_streaming_form(const Header& header); - /// Read the top_ref from the given buffer and set m_file_on_streaming_form - /// if the buffer contains a file in streaming form - static ref_type get_top_ref(const char* data, size_t len); - - // Gets the path of the attached file, or other relevant debugging info. - std::string get_file_path_for_assertions() const; - - class ChunkRefEq; - class ChunkRefEndEq; - class SlabRefEndEq; - static bool ref_less_than_slab_ref_end(ref_type, const Slab&) noexcept; - - Replication* get_replication() const noexcept - { - return m_replication; - } - void set_replication(Replication* r) noexcept - { - m_replication = r; - } - - friend class Group; - friend class SharedGroup; - friend class GroupWriter; -}; - -inline void SlabAlloc::internal_invalidate_cache() noexcept -{ - ++version; -} - -class SlabAlloc::DetachGuard { -public: - DetachGuard(SlabAlloc& alloc) noexcept - : m_alloc(&alloc) - { - } - ~DetachGuard() noexcept; - SlabAlloc* release() noexcept; - -private: - SlabAlloc* m_alloc; -}; - - -// Implementation: - -struct InvalidDatabase : util::File::AccessError { - InvalidDatabase(const std::string& msg, const std::string& path) - : util::File::AccessError(msg, path) - { - } -}; - -inline void SlabAlloc::own_buffer() noexcept -{ - REALM_ASSERT_3(m_attach_mode, ==, attach_UsersBuffer); - REALM_ASSERT(m_data); - REALM_ASSERT(m_file_mappings == nullptr); - m_attach_mode = attach_OwnedBuffer; -} - -inline bool SlabAlloc::is_attached() const noexcept -{ - return m_attach_mode != attach_None; -} - -inline bool SlabAlloc::nonempty_attachment() const noexcept -{ - return is_attached() && m_data; -} - -inline size_t SlabAlloc::get_baseline() const noexcept -{ - REALM_ASSERT_DEBUG(is_attached()); - return m_baseline; -} - -inline bool SlabAlloc::is_free_space_clean() const noexcept -{ - return m_free_space_state == free_space_Clean; -} - -inline SlabAlloc::DetachGuard::~DetachGuard() noexcept -{ - if (m_alloc) - m_alloc->detach(); -} - -inline SlabAlloc* SlabAlloc::DetachGuard::release() noexcept -{ - SlabAlloc* alloc = m_alloc; - m_alloc = nullptr; - return alloc; -} - -inline bool SlabAlloc::ref_less_than_slab_ref_end(ref_type ref, const Slab& slab) noexcept -{ - return ref < slab.ref_end; -} - -inline size_t SlabAlloc::get_upper_section_boundary(size_t start_pos) const noexcept -{ - return get_section_base(1 + get_section_index(start_pos)); -} - -inline size_t SlabAlloc::get_lower_section_boundary(size_t start_pos) const noexcept -{ - return get_section_base(get_section_index(start_pos)); -} - -inline bool SlabAlloc::matches_section_boundary(size_t pos) const noexcept -{ - return pos == get_lower_section_boundary(pos); -} - -inline size_t SlabAlloc::get_section_base(size_t index) const noexcept -{ - return m_section_bases[index]; -} - -template -void SlabAlloc::for_all_free_entries(Func f) const -{ - ref_type ref = m_baseline; - for (auto& e : m_slabs) { - BetweenBlocks* bb = reinterpret_cast(e.addr.get()); - REALM_ASSERT(bb->block_before_size == 0); - while (1) { - int size = bb->block_after_size; - f(ref, sizeof(BetweenBlocks)); - ref += sizeof(BetweenBlocks); - if (size == 0) { - break; - } - if (size > 0) { // freeblock. - f(ref, size); - bb = reinterpret_cast(reinterpret_cast(bb) + sizeof(BetweenBlocks) + size); - ref += size; - } - else { - bb = reinterpret_cast(reinterpret_cast(bb) + sizeof(BetweenBlocks) - size); - ref -= size; - } - } - } -} - -} // namespace realm - -#endif // REALM_ALLOC_SLAB_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array.hpp b/Lesson14/Pods/Realm/include/core/realm/array.hpp deleted file mode 100644 index a948943..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array.hpp +++ /dev/null @@ -1,3128 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -/* -Searching: The main finding function is: - template - void find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState *state, Callback callback) const - - cond: One of Equal, NotEqual, Greater, etc. classes - Action: One of act_ReturnFirst, act_FindAll, act_Max, act_CallbackIdx, etc, constants - Callback: Optional function to call for each search result. Will be called if action == act_CallbackIdx - - find() will call find_action_pattern() or find_action() that again calls match() for each search result which - optionally calls callback(): - - find() -> find_action() -------> bool match() -> bool callback() - | ^ - +-> find_action_pattern()----+ - - If callback() returns false, find() will exit, otherwise it will keep searching remaining items in array. -*/ - -#ifndef REALM_ARRAY_HPP -#define REALM_ARRAY_HPP - -#include -#include // size_t -#include -#include -#include -#include - -#include // unint8_t etc - -#include -#include -#include -#include -#include -#include -#include -#include - -/* - MMX: mmintrin.h - SSE: xmmintrin.h - SSE2: emmintrin.h - SSE3: pmmintrin.h - SSSE3: tmmintrin.h - SSE4A: ammintrin.h - SSE4.1: smmintrin.h - SSE4.2: nmmintrin.h -*/ -#ifdef REALM_COMPILER_SSE -#include // SSE2 -#include // SSE42 -#endif - -namespace realm { - -enum Action { - act_ReturnFirst, - act_Sum, - act_Max, - act_Min, - act_Count, - act_FindAll, - act_CallIdx, - act_CallbackIdx, - act_CallbackVal, - act_CallbackNone, - act_CallbackBoth, - act_Average -}; - -template -inline T no0(T v) -{ - return v == 0 ? 1 : v; -} - -/// Special index value. It has various meanings depending on -/// context. It is returned by some search functions to indicate 'not -/// found'. It is similar in function to std::string::npos. -const size_t npos = size_t(-1); - -const size_t max_array_size = 0x00ffffffL; // Maximum number of elements in an array -const size_t max_array_payload_aligned = 0x07ffffc0L; // Maximum number of bytes that the payload of an array can be - -/// Alias for realm::npos. -const size_t not_found = npos; - -// Pre-definitions -class Array; -class StringColumn; -class GroupWriter; -template -class QueryState; -namespace _impl { -class ArrayWriterBase; -} - - -struct MemStats { - size_t allocated = 0; - size_t used = 0; - size_t array_count = 0; -}; - -#ifdef REALM_DEBUG -template -std::basic_ostream& operator<<(std::basic_ostream& out, MemStats stats); -#endif - - -// Stores a value obtained from Array::get(). It is a ref if the least -// significant bit is clear, otherwise it is a tagged integer. A tagged interger -// is obtained from a logical integer value by left shifting by one bit position -// (multiplying by two), and then setting the least significant bit to -// one. Clearly, this means that the maximum value that can be stored as a -// tagged integer is 2**63 - 1. -class RefOrTagged { -public: - bool is_ref() const noexcept; - bool is_tagged() const noexcept; - ref_type get_as_ref() const noexcept; - uint_fast64_t get_as_int() const noexcept; - - static RefOrTagged make_ref(ref_type) noexcept; - static RefOrTagged make_tagged(uint_fast64_t) noexcept; - -private: - int_fast64_t m_value; - RefOrTagged(int_fast64_t) noexcept; - friend class Array; -}; - - -class ArrayParent { -public: - virtual ~ArrayParent() noexcept - { - } - -protected: - virtual void update_child_ref(size_t child_ndx, ref_type new_ref) = 0; - - virtual ref_type get_child_ref(size_t child_ndx) const noexcept = 0; - - // Used only by Array::to_dot(). - virtual std::pair get_to_dot_parent(size_t ndx_in_parent) const = 0; - - friend class Array; -}; - -struct TreeInsertBase { - size_t m_split_offset; - size_t m_split_size; -}; - -/// Provides access to individual array nodes of the database. -/// -/// This class serves purely as an accessor, it assumes no ownership of the -/// referenced memory. -/// -/// An array accessor can be in one of two states: attached or unattached. It is -/// in the attached state if, and only if is_attached() returns true. Most -/// non-static member functions of this class have undefined behaviour if the -/// accessor is in the unattached state. The exceptions are: is_attached(), -/// detach(), create(), init_from_ref(), init_from_mem(), init_from_parent(), -/// has_parent(), get_parent(), set_parent(), get_ndx_in_parent(), -/// set_ndx_in_parent(), adjust_ndx_in_parent(), and get_ref_from_parent(). -/// -/// An array accessor contains information about the parent of the referenced -/// array node. This 'reverse' reference is not explicitely present in the -/// underlying node hierarchy, but it is needed when modifying an array. A -/// modification may lead to relocation of the underlying array node, and the -/// parent must be updated accordingly. Since this applies recursivly all the -/// way to the root node, it is essential that the entire chain of parent -/// accessors is constructed and propperly maintained when a particular array is -/// modified. -/// -/// The parent reference (`pointer to parent`, `index in parent`) is updated -/// independently from the state of attachment to an underlying node. In -/// particular, the parent reference remains valid and is unannfected by changes -/// in attachment. These two aspects of the state of the accessor is updated -/// independently, and it is entirely the responsibility of the caller to update -/// them such that they are consistent with the underlying node hierarchy before -/// calling any method that modifies the underlying array node. -/// -/// FIXME: This class currently has fragments of ownership, in particular the -/// constructors that allocate underlying memory. On the other hand, the -/// destructor never frees the memory. This is a problematic situation, because -/// it so easily becomes an obscure source of leaks. There are three options for -/// a fix of which the third is most attractive but hardest to implement: (1) -/// Remove all traces of ownership semantics, that is, remove the constructors -/// that allocate memory, but keep the trivial copy constructor. For this to -/// work, it is important that the constness of the accessor has nothing to do -/// with the constness of the underlying memory, otherwise constness can be -/// violated simply by copying the accessor. (2) Disallov copying but associate -/// the constness of the accessor with the constness of the underlying -/// memory. (3) Provide full ownership semantics like is done for Table -/// accessors, and provide a proper copy constructor that really produces a copy -/// of the array. For this to work, the class should assume ownership if, and -/// only if there is no parent. A copy produced by a copy constructor will not -/// have a parent. Even if the original was part of a database, the copy will be -/// free-standing, that is, not be part of any database. For intra, or inter -/// database copying, one would have to also specify the target allocator. -class Array : public ArrayParent { -public: - // void state_init(int action, QueryState *state); - // bool match(int action, size_t index, int64_t value, QueryState *state); - - /// Create an array accessor in the unattached state. - explicit Array(Allocator&) noexcept; - - ~Array() noexcept override - { - } - - enum Type { - type_Normal, - - /// This array is the main array of an innner node of a B+-tree as used - /// in table columns. - type_InnerBptreeNode, - - /// This array may contain refs to subarrays. An element whose least - /// significant bit is zero, is a ref pointing to a subarray. An element - /// whose least significant bit is one, is just a value. It is the - /// responsibility of the application to ensure that non-ref values have - /// their least significant bit set. This will generally be done by - /// shifting the desired vlue to the left by one bit position, and then - /// setting the vacated bit to one. - type_HasRefs - }; - - /// Create a new integer array of the specified type and size, and filled - /// with the specified value, and attach this accessor to it. This does not - /// modify the parent reference information of this accessor. - /// - /// Note that the caller assumes ownership of the allocated underlying - /// node. It is not owned by the accessor. - void create(Type, bool context_flag = false, size_t size = 0, int_fast64_t value = 0); - - /// Reinitialize this array accessor to point to the specified new - /// underlying memory. This does not modify the parent reference information - /// of this accessor. - void init_from_ref(ref_type) noexcept; - - /// Same as init_from_ref(ref_type) but avoid the mapping of 'ref' to memory - /// pointer. - void init_from_mem(MemRef) noexcept; - - /// Same as `init_from_ref(get_ref_from_parent())`. - void init_from_parent() noexcept; - - /// Update the parents reference to this child. This requires, of course, - /// that the parent information stored in this child is up to date. If the - /// parent pointer is set to null, this function has no effect. - void update_parent(); - - /// Called in the context of Group::commit() to ensure that attached - /// accessors stay valid across a commit. Please note that this works only - /// for non-transactional commits. Accessors obtained during a transaction - /// are always detached when the transaction ends. - /// - /// Returns true if, and only if the array has changed. If the array has not - /// changed, then its children are guaranteed to also not have changed. - bool update_from_parent(size_t old_baseline) noexcept; - - /// Change the type of an already attached array node. - /// - /// The effect of calling this function on an unattached accessor is - /// undefined. - void set_type(Type); - - /// Construct a complete copy of this array (including its subarrays) using - /// the specified target allocator and return just the reference to the - /// underlying memory. - MemRef clone_deep(Allocator& target_alloc) const; - - /// Construct an empty integer array of the specified type, and return just - /// the reference to the underlying memory. - static MemRef create_empty_array(Type, bool context_flag, Allocator&); - - /// Construct an integer array of the specified type and size, and return - /// just the reference to the underlying memory. All elements will be - /// initialized to the specified value. - static MemRef create_array(Type, bool context_flag, size_t size, int_fast64_t value, Allocator&); - - /// Construct a shallow copy of the specified slice of this array using the - /// specified target allocator. Subarrays will **not** be cloned. See - /// slice_and_clone_children() for an alternative. - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - - /// Construct a deep copy of the specified slice of this array using the - /// specified target allocator. Subarrays will be cloned. - MemRef slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const; - - // Parent tracking - bool has_parent() const noexcept; - ArrayParent* get_parent() const noexcept; - - /// Setting a new parent affects ownership of the attached array node, if - /// any. If a non-null parent is specified, and there was no parent - /// originally, then the caller passes ownership to the parent, and vice - /// versa. This assumes, of course, that the change in parentship reflects a - /// corresponding change in the list of children in the affected parents. - void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; - - size_t get_ndx_in_parent() const noexcept; - void set_ndx_in_parent(size_t) noexcept; - void adjust_ndx_in_parent(int diff) noexcept; - - /// Get the ref of this array as known to the parent. The caller must ensure - /// that the parent information ('pointer to parent' and 'index in parent') - /// is correct before calling this function. - ref_type get_ref_from_parent() const noexcept; - - bool is_attached() const noexcept; - - /// Detach from the underlying array node. This method has no effect if the - /// accessor is currently unattached (idempotency). - void detach() noexcept; - - size_t size() const noexcept; - bool is_empty() const noexcept; - Type get_type() const noexcept; - - - static void add_to_column(IntegerColumn* column, int64_t value); - - void insert(size_t ndx, int_fast64_t value); - void add(int_fast64_t value); - - // Used from ArrayBlob - size_t blob_size() const noexcept; - ref_type blob_replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term); - - /// This function is guaranteed to not throw if the current width is - /// sufficient for the specified value (e.g. if you have called - /// ensure_minimum_width(value)) and get_alloc().is_read_only(get_ref()) - /// returns false (noexcept:array-set). Note that for a value of zero, the - /// first criterion is trivially satisfied. - void set(size_t ndx, int64_t value); - - void set_as_ref(size_t ndx, ref_type ref); - - template - void set(size_t ndx, int64_t value); - - int64_t get(size_t ndx) const noexcept; - - template - int64_t get(size_t ndx) const noexcept; - - void get_chunk(size_t ndx, int64_t res[8]) const noexcept; - - template - void get_chunk(size_t ndx, int64_t res[8]) const noexcept; - - ref_type get_as_ref(size_t ndx) const noexcept; - - RefOrTagged get_as_ref_or_tagged(size_t ndx) const noexcept; - void set(size_t ndx, RefOrTagged); - void add(RefOrTagged); - void ensure_minimum_width(RefOrTagged); - - int64_t front() const noexcept; - int64_t back() const noexcept; - - /// Remove the element at the specified index, and move elements at higher - /// indexes to the next lower index. - /// - /// This function does **not** destroy removed subarrays. That is, if the - /// erased element is a 'ref' pointing to a subarray, then that subarray - /// will not be destroyed automatically. - /// - /// This function guarantees that no exceptions will be thrown if - /// get_alloc().is_read_only(get_ref()) would return false before the - /// call. This is automatically guaranteed if the array is used in a - /// non-transactional context, or if the array has already been successfully - /// modified within the current write transaction. - void erase(size_t ndx); - - /// Same as erase(size_t), but remove all elements in the specified - /// range. - /// - /// Please note that this function does **not** destroy removed subarrays. - /// - /// This function guarantees that no exceptions will be thrown if - /// get_alloc().is_read_only(get_ref()) would return false before the call. - void erase(size_t begin, size_t end); - - /// Reduce the size of this array to the specified number of elements. It is - /// an error to specify a size that is greater than the current size of this - /// array. The effect of doing so is undefined. This is just a shorthand for - /// calling the ranged erase() function with appropriate arguments. - /// - /// Please note that this function does **not** destroy removed - /// subarrays. See clear_and_destroy_children() for an alternative. - /// - /// This function guarantees that no exceptions will be thrown if - /// get_alloc().is_read_only(get_ref()) would return false before the call. - void truncate(size_t new_size); - - /// Reduce the size of this array to the specified number of elements. It is - /// an error to specify a size that is greater than the current size of this - /// array. The effect of doing so is undefined. Subarrays will be destroyed - /// recursively, as if by a call to `destroy_deep(subarray_ref, alloc)`. - /// - /// This function is guaranteed not to throw if - /// get_alloc().is_read_only(get_ref()) returns false. - void truncate_and_destroy_children(size_t new_size); - - /// Remove every element from this array. This is just a shorthand for - /// calling truncate(0). - /// - /// Please note that this function does **not** destroy removed - /// subarrays. See clear_and_destroy_children() for an alternative. - /// - /// This function guarantees that no exceptions will be thrown if - /// get_alloc().is_read_only(get_ref()) would return false before the call. - void clear(); - - /// Remove every element in this array. Subarrays will be destroyed - /// recursively, as if by a call to `destroy_deep(subarray_ref, - /// alloc)`. This is just a shorthand for calling - /// truncate_and_destroy_children(0). - /// - /// This function guarantees that no exceptions will be thrown if - /// get_alloc().is_read_only(get_ref()) would return false before the call. - void clear_and_destroy_children(); - - /// If neccessary, expand the representation so that it can store the - /// specified value. - void ensure_minimum_width(int_fast64_t value); - - /// This one may change the represenation of the array, so be carefull if - /// you call it after ensure_minimum_width(). - void set_all_to_zero(); - - /// Add \a diff to the element at the specified index. - void adjust(size_t ndx, int_fast64_t diff); - - /// Add \a diff to all the elements in the specified index range. - void adjust(size_t begin, size_t end, int_fast64_t diff); - - /// Add signed \a diff to all elements that are greater than, or equal to \a - /// limit. - void adjust_ge(int_fast64_t limit, int_fast64_t diff); - - //@{ - /// These are similar in spirit to std::move() and std::move_backward from - /// ``. \a dest_begin must not be in the range [`begin`,`end`), and - /// \a dest_end must not be in the range (`begin`,`end`]. - /// - /// These functions are guaranteed to not throw if - /// `get_alloc().is_read_only(get_ref())` returns false. - void move(size_t begin, size_t end, size_t dest_begin); - void move_backward(size_t begin, size_t end, size_t dest_end); - //@} - - /// move_rotate moves one element from \a from to be located at index \a to, - /// shifting all elements inbetween by one. - /// - /// If \a from is larger than \a to, the elements inbetween are shifted down. - /// If \a to is larger than \a from, the elements inbetween are shifted up. - /// - /// This function is guaranteed to not throw if - /// `get_alloc().is_read_only(get_ref())` returns false. - void move_rotate(size_t from, size_t to, size_t num_elems = 1); - - //@{ - /// Find the lower/upper bound of the specified value in a sequence of - /// integers which must already be sorted ascendingly. - /// - /// For an integer value '`v`', lower_bound_int(v) returns the index '`l`' - /// of the first element such that `get(l) ≥ v`, and upper_bound_int(v) - /// returns the index '`u`' of the first element such that `get(u) > - /// v`. In both cases, if no such element is found, the returned value is - /// the number of elements in the array. - /// - /// 3 3 3 4 4 4 5 6 7 9 9 9 - /// ^ ^ ^ ^ ^ - /// | | | | | - /// | | | | -- Lower and upper bound of 15 - /// | | | | - /// | | | -- Lower and upper bound of 8 - /// | | | - /// | | -- Upper bound of 4 - /// | | - /// | -- Lower bound of 4 - /// | - /// -- Lower and upper bound of 1 - /// - /// These functions are similar to std::lower_bound() and - /// std::upper_bound(). - /// - /// We currently use binary search. See for example - /// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary. - /// - /// FIXME: It may be worth considering if overall efficiency can be improved - /// by doing a linear search for short sequences. - size_t lower_bound_int(int64_t value) const noexcept; - size_t upper_bound_int(int64_t value) const noexcept; - //@} - - /// \brief Search the \c Array for a value greater or equal than \a target, - /// starting the search at the \a start index. If \a indirection is - /// provided, use it as a look-up table to iterate over the \c Array. - /// - /// If \a indirection is not provided, then the \c Array must be sorted in - /// ascending order. If \a indirection is provided, then its values should - /// point to indices in this \c Array in such a way that iteration happens - /// in ascending order. - /// - /// Behaviour is undefined if: - /// - a value in \a indirection is out of bounds for this \c Array; - /// - \a indirection does not contain at least as many elements as this \c - /// Array; - /// - sorting conditions are not respected; - /// - \a start is greater than the number of elements in this \c Array or - /// \a indirection (if provided). - /// - /// \param target the smallest value to search for - /// \param start the offset at which to start searching in the array - /// \param indirection an \c Array containing valid indices of values in - /// this \c Array, sorted in ascending order - /// \return the index of the value if found, or realm::not_found otherwise - size_t find_gte(const int64_t target, size_t start, size_t end = size_t(-1)) const; - - void preset(int64_t min, int64_t max, size_t num_items); - void preset(size_t bitwidth, size_t num_items); - - int64_t sum(size_t start = 0, size_t end = size_t(-1)) const; - size_t count(int64_t value) const noexcept; - - bool maximum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; - - bool minimum(int64_t& result, size_t start = 0, size_t end = size_t(-1), size_t* return_ndx = nullptr) const; - - /// This information is guaranteed to be cached in the array accessor. - bool is_inner_bptree_node() const noexcept; - - /// Returns true if type is either type_HasRefs or type_InnerColumnNode. - /// - /// This information is guaranteed to be cached in the array accessor. - bool has_refs() const noexcept; - void set_has_refs(bool) noexcept; - - /// This information is guaranteed to be cached in the array accessor. - /// - /// Columns and indexes can use the context bit to differentiate leaf types. - bool get_context_flag() const noexcept; - void set_context_flag(bool) noexcept; - - ref_type get_ref() const noexcept; - MemRef get_mem() const noexcept; - - /// Destroy only the array that this accessor is attached to, not the - /// children of that array. See non-static destroy_deep() for an - /// alternative. If this accessor is already in the detached state, this - /// function has no effect (idempotency). - void destroy() noexcept; - - /// Recursively destroy children (as if calling - /// clear_and_destroy_children()), then put this accessor into the detached - /// state (as if calling detach()), then free the allocated memory. If this - /// accessor is already in the detached state, this function has no effect - /// (idempotency). - void destroy_deep() noexcept; - - /// Shorthand for `destroy(MemRef(ref, alloc), alloc)`. - static void destroy(ref_type ref, Allocator& alloc) noexcept; - - /// Destroy only the specified array node, not its children. See also - /// destroy_deep(MemRef, Allocator&). - static void destroy(MemRef, Allocator&) noexcept; - - /// Shorthand for `destroy_deep(MemRef(ref, alloc), alloc)`. - static void destroy_deep(ref_type ref, Allocator& alloc) noexcept; - - /// Destroy the specified array node and all of its children, recursively. - /// - /// This is done by freeing the specified array node after calling - /// destroy_deep() for every contained 'ref' element. - static void destroy_deep(MemRef, Allocator&) noexcept; - - Allocator& get_alloc() const noexcept - { - return m_alloc; - } - - // Serialization - - /// Returns the ref (position in the target stream) of the written copy of - /// this array, or the ref of the original array if \a only_if_modified is - /// true, and this array is unmodified (Alloc::is_read_only()). - /// - /// The number of bytes that will be written by a non-recursive invocation - /// of this function is exactly the number returned by get_byte_size(). - /// - /// \param out The destination stream (writer). - /// - /// \param deep If true, recursively write out subarrays, but still subject - /// to \a only_if_modified. - /// - /// \param only_if_modified Set to `false` to always write, or to `true` to - /// only write the array if it has been modified. - ref_type write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const; - - /// Same as non-static write() with `deep` set to true. This is for the - /// cases where you do not already have an array accessor available. - static ref_type write(ref_type, Allocator&, _impl::ArrayWriterBase&, bool only_if_modified); - - // Main finding function - used for find_first, find_all, sum, max, min, etc. - bool find(int cond, Action action, int64_t value, size_t start, size_t end, size_t baseindex, - QueryState* state, bool nullable_array = false, bool find_null = false) const; - - // Templated find function to avoid conversion to and from integer represenation of condition - template - bool find(Action action, int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - bool nullable_array = false, bool find_null = false) const - { - if (action == act_ReturnFirst) { - REALM_TEMPEX3(return find, cond, act_ReturnFirst, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_Sum) { - REALM_TEMPEX3(return find, cond, act_Sum, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_Min) { - REALM_TEMPEX3(return find, cond, act_Min, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_Max) { - REALM_TEMPEX3(return find, cond, act_Max, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_Count) { - REALM_TEMPEX3(return find, cond, act_Count, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_FindAll) { - REALM_TEMPEX3(return find, cond, act_FindAll, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - else if (action == act_CallbackIdx) { - REALM_TEMPEX3(return find, cond, act_CallbackIdx, m_width, - (value, start, end, baseindex, state, CallbackDummy(), nullable_array, find_null)) - } - REALM_ASSERT_DEBUG(false); - return false; - } - - - /* - bool find(int cond, Action action, null, size_t start, size_t end, size_t baseindex, - QueryState* state) const; - */ - - template - bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array = false, bool find_null = false) const; - - // This is the one installed into the m_vtable->finder slots. - template - bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const; - - template - bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array = false, bool find_null = false) const; - - /* - template - bool find(null, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const; - */ - - // Optimized implementation for release mode - template - bool find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array = false, bool find_null = false) const; - - // Called for each search result - template - bool find_action(size_t index, util::Optional value, QueryState* state, - Callback callback) const; - - template - bool find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const; - - // Wrappers for backwards compatibility and for simple use without - // setting up state initialization etc - template - size_t find_first(int64_t value, size_t start = 0, size_t end = size_t(-1)) const; - - void find_all(IntegerColumn* result, int64_t value, size_t col_offset = 0, size_t begin = 0, - size_t end = size_t(-1)) const; - - size_t find_first(int64_t value, size_t begin = 0, size_t end = size_t(-1)) const; - - // Non-SSE find for the four functions Equal/NotEqual/Less/Greater - template - bool compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - // Non-SSE find for Equal/NotEqual - template - inline bool compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const; - - // Non-SSE find for Less/Greater - template - bool compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - template - bool compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - template - bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - template - bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - template - bool compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - -// SSE find for the four functions Equal/NotEqual/Less/Greater -#ifdef REALM_COMPILER_SSE - template - bool find_sse(int64_t value, __m128i* data, size_t items, QueryState* state, size_t baseindex, - Callback callback) const; - - template - REALM_FORCEINLINE bool find_sse_intern(__m128i* action_data, __m128i* data, size_t items, - QueryState* state, size_t baseindex, Callback callback) const; - -#endif - - template - inline bool test_zero(uint64_t value) const; // Tests value for 0-elements - - template - size_t find_zero(uint64_t v) const; // Finds position of 0/non-zero element - - template - uint64_t cascade(uint64_t a) const; // Sets lowermost bits of zero or non-zero elements - - template - int64_t - find_gtlt_magic(int64_t v) const; // Compute magic constant needed for searching for value 'v' using bit hacks - - template - inline int64_t lower_bits() const; // Return chunk with lower bit set in each element - - size_t first_set_bit(unsigned int v) const; - size_t first_set_bit64(int64_t v) const; - - template - int64_t get_universal(const char* const data, const size_t ndx) const; - - // Find value greater/less in 64-bit chunk - only works for positive values - template - bool find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState* state, size_t baseindex, - Callback callback) const; - - // Find value greater/less in 64-bit chunk - no constraints - template - bool find_gtlt(int64_t v, uint64_t chunk, QueryState* state, size_t baseindex, Callback callback) const; - - ref_type bptree_leaf_insert(size_t ndx, int64_t, TreeInsertBase& state); - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static int_fast64_t get(const char* header, size_t ndx) noexcept; - - /// Like get(const char*, size_t) but gets two consecutive - /// elements. - static std::pair get_two(const char* header, size_t ndx) noexcept; - - static void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept; - - /// The meaning of 'width' depends on the context in which this - /// array is used. - size_t get_width() const noexcept - { - return m_width; - } - - static char* get_data_from_header(char*) noexcept; - static char* get_header_from_data(char*) noexcept; - static const char* get_data_from_header(const char*) noexcept; - - enum WidthType { - wtype_Bits = 0, - wtype_Multiply = 1, - wtype_Ignore = 2, - }; - - static bool get_is_inner_bptree_node_from_header(const char*) noexcept; - static bool get_hasrefs_from_header(const char*) noexcept; - static bool get_context_flag_from_header(const char*) noexcept; - static WidthType get_wtype_from_header(const char*) noexcept; - static uint_least8_t get_width_from_header(const char*) noexcept; - static size_t get_size_from_header(const char*) noexcept; - - static Type get_type_from_header(const char*) noexcept; - - /// Get the number of bytes currently in use by this array. This - /// includes the array header, but it does not include allocated - /// bytes corresponding to excess capacity. The result is - /// guaranteed to be a multiple of 8 (i.e., 64-bit aligned). - /// - /// This number is exactly the number of bytes that will be - /// written by a non-recursive invocation of write(). - size_t get_byte_size() const noexcept; - - /// Get the maximum number of bytes that can be written by a - /// non-recursive invocation of write() on an array with the - /// specified number of elements, that is, the maximum value that - /// can be returned by get_byte_size(). - static size_t get_max_byte_size(size_t num_elems) noexcept; - - /// FIXME: Belongs in IntegerArray - static size_t calc_aligned_byte_size(size_t size, int width); - - class MemUsageHandler { - public: - virtual void handle(ref_type ref, size_t allocated, size_t used) = 0; - }; - - void report_memory_usage(MemUsageHandler&) const; - - void stats(MemStats& stats_dest) const noexcept; - -#ifdef REALM_DEBUG - void print() const; - void verify() const; - typedef size_t (*LeafVerifier)(MemRef, Allocator&); - void verify_bptree(LeafVerifier) const; - typedef void (*LeafDumper)(MemRef, Allocator&, std::ostream&, int level); - void dump_bptree_structure(std::ostream&, int level, LeafDumper) const; - void to_dot(std::ostream&, StringData title = StringData()) const; - class ToDotHandler { - public: - virtual void to_dot(MemRef leaf_mem, ArrayParent*, size_t ndx_in_parent, std::ostream&) = 0; - ~ToDotHandler() - { - } - }; - void bptree_to_dot(std::ostream&, ToDotHandler&) const; - void to_dot_parent_edge(std::ostream&) const; -#endif - - static const int header_size = 8; // Number of bytes used by header - - // The encryption layer relies on headers always fitting within a single page. - static_assert(header_size == 8, "Header must always fit in entirely on a page"); - - Array& operator=(const Array&) = delete; // not allowed - Array(const Array&) = delete; // not allowed -protected: - typedef bool (*CallbackDummy)(int64_t); - -protected: - // Includes array header. Not necessarily 8-byte aligned. - virtual size_t calc_byte_len(size_t num_items, size_t width) const; - - virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept; - - bool get_is_inner_bptree_node_from_header() const noexcept; - bool get_hasrefs_from_header() const noexcept; - bool get_context_flag_from_header() const noexcept; - WidthType get_wtype_from_header() const noexcept; - uint_least8_t get_width_from_header() const noexcept; - size_t get_size_from_header() const noexcept; - - // Undefined behavior if m_alloc.is_read_only(m_ref) returns true - size_t get_capacity_from_header() const noexcept; - - void set_header_is_inner_bptree_node(bool value) noexcept; - void set_header_hasrefs(bool value) noexcept; - void set_header_context_flag(bool value) noexcept; - void set_header_wtype(WidthType value) noexcept; - void set_header_width(int value) noexcept; - void set_header_size(size_t value) noexcept; - void set_header_capacity(size_t value) noexcept; - - static void set_header_is_inner_bptree_node(bool value, char* header) noexcept; - static void set_header_hasrefs(bool value, char* header) noexcept; - static void set_header_context_flag(bool value, char* header) noexcept; - static void set_header_wtype(WidthType value, char* header) noexcept; - static void set_header_width(int value, char* header) noexcept; - static void set_header_size(size_t value, char* header) noexcept; - static void set_header_capacity(size_t value, char* header) noexcept; - - static void init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, - WidthType width_type, int width, size_t size, size_t capacity) noexcept; - - - // This returns the minimum value ("lower bound") of the representable values - // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. - template - static int_fast64_t lbound_for_width() noexcept; - - static int_fast64_t lbound_for_width(size_t width) noexcept; - - // This returns the maximum value ("inclusive upper bound") of the representable values - // for the given bit width. Valid widths are 0, 1, 2, 4, 8, 16, 32, and 64. - template - static int_fast64_t ubound_for_width() noexcept; - - static int_fast64_t ubound_for_width(size_t width) noexcept; - - template - void set_width() noexcept; - void set_width(size_t) noexcept; - void alloc(size_t init_size, size_t width); - void copy_on_write(); - -private: - void do_copy_on_write(size_t minimum_size = 0); - void do_ensure_minimum_width(int_fast64_t); - - template - int64_t sum(size_t start, size_t end) const; - - template - bool minmax(int64_t& result, size_t start, size_t end, size_t* return_ndx) const; - - template - size_t find_gte(const int64_t target, size_t start, size_t end) const; - - template - size_t adjust_ge(size_t start, size_t end, int_fast64_t limit, int_fast64_t diff); - -protected: - /// The total size in bytes (including the header) of a new empty - /// array. Must be a multiple of 8 (i.e., 64-bit aligned). - static const size_t initial_capacity = 128; - - /// It is an error to specify a non-zero value unless the width - /// type is wtype_Bits. It is also an error to specify a non-zero - /// size if the width type is wtype_Ignore. - static MemRef create(Type, bool context_flag, WidthType, size_t size, int_fast64_t value, Allocator&); - - static MemRef clone(MemRef header, Allocator& alloc, Allocator& target_alloc); - - /// Get the address of the header of this array. - char* get_header() noexcept; - - /// Same as get_byte_size(). - static size_t get_byte_size_from_header(const char*) noexcept; - - // Undefined behavior if array is in immutable memory - static size_t get_capacity_from_header(const char*) noexcept; - - // Overriding method in ArrayParent - void update_child_ref(size_t, ref_type) override; - - // Overriding method in ArrayParent - ref_type get_child_ref(size_t) const noexcept override; - - void destroy_children(size_t offset = 0) noexcept; - - std::pair get_to_dot_parent(size_t ndx_in_parent) const override; - - bool is_read_only() const noexcept; - -protected: - // Getters and Setters for adaptive-packed arrays - typedef int64_t (Array::*Getter)(size_t) const; // Note: getters must not throw - typedef void (Array::*Setter)(size_t, int64_t); - typedef bool (Array::*Finder)(int64_t, size_t, size_t, size_t, QueryState*) const; - typedef void (Array::*ChunkGetter)(size_t, int64_t res[8]) const; // Note: getters must not throw - - struct VTable { - Getter getter; - ChunkGetter chunk_getter; - Setter setter; - Finder finder[cond_VTABLE_FINDER_COUNT]; // one for each active function pointer - }; - template - struct VTableForWidth; - -protected: - /// Takes a 64-bit value and returns the minimum number of bits needed - /// to fit the value. For alignment this is rounded up to nearest - /// log2. Posssible results {0, 1, 2, 4, 8, 16, 32, 64} - static size_t bit_width(int64_t value); - - void report_memory_usage_2(MemUsageHandler&) const; - -private: - Getter m_getter = nullptr; // cached to avoid indirection - const VTable* m_vtable = nullptr; - -public: - // FIXME: Should not be public - char* m_data = nullptr; // Points to first byte after header - -#if REALM_ENABLE_MEMDEBUG - // If m_no_relocation is false, then copy_on_write() will always relocate this array, regardless if it's - // required or not. If it's true, then it will never relocate, which is currently only expeted inside - // GroupWriter::write_group() due to a unique chicken/egg problem (see description there). - bool m_no_relocation = false; -#endif - -protected: - int64_t m_lbound; // min number that can be stored with current m_width - int64_t m_ubound; // max number that can be stored with current m_width - - size_t m_size = 0; // Number of elements currently stored. - size_t m_capacity = 0; // Number of elements that fit inside the allocated memory. - - Allocator& m_alloc; - -private: - size_t m_ref; - ArrayParent* m_parent = nullptr; - size_t m_ndx_in_parent = 0; // Ignored if m_parent is null. - -protected: - uint_least8_t m_width = 0; // Size of an element (meaning depend on type of array). - bool m_is_inner_bptree_node; // This array is an inner node of B+-tree. - bool m_has_refs; // Elements whose first bit is zero are refs to subarrays. - bool m_context_flag; // Meaning depends on context. - -private: - ref_type do_write_shallow(_impl::ArrayWriterBase&) const; - ref_type do_write_deep(_impl::ArrayWriterBase&, bool only_if_modified) const; - static size_t calc_byte_size(WidthType wtype, size_t size, uint_least8_t width) noexcept; - - friend class SlabAlloc; - friend class GroupWriter; - friend class StringColumn; -}; - - -// Implementation: - -class QueryStateBase { - virtual void dyncast() - { - } -}; - -template <> -class QueryState : public QueryStateBase { -public: - int64_t m_state; - size_t m_match_count; - size_t m_limit; - size_t m_minmax_index; // used only for min/max, to save index of current min/max value - - template - bool uses_val() - { - if (action == act_Max || action == act_Min || action == act_Sum) - return true; - else - return false; - } - - void init(Action action, IntegerColumn* akku, size_t limit) - { - m_match_count = 0; - m_limit = limit; - m_minmax_index = not_found; - - if (action == act_Max) - m_state = -0x7fffffffffffffffLL - 1LL; - else if (action == act_Min) - m_state = 0x7fffffffffffffffLL; - else if (action == act_ReturnFirst) - m_state = not_found; - else if (action == act_Sum) - m_state = 0; - else if (action == act_Count) - m_state = 0; - else if (action == act_FindAll) - m_state = reinterpret_cast(akku); - else if (action == act_CallbackIdx) { - } - else { - REALM_ASSERT_DEBUG(false); - } - } - - template - inline bool match(size_t index, uint64_t indexpattern, int64_t value) - { - if (pattern) { - if (action == act_Count) { - // If we are close to 'limit' argument in query, we cannot count-up a complete chunk. Count up single - // elements instead - if (m_match_count + 64 >= m_limit) - return false; - - m_state += fast_popcount64(indexpattern); - m_match_count = size_t(m_state); - return true; - } - // Other aggregates cannot (yet) use bit pattern for anything. Make Array-finder call with pattern = false - // instead - return false; - } - - ++m_match_count; - - if (action == act_Max) { - if (value > m_state) { - m_state = value; - m_minmax_index = index; - } - } - else if (action == act_Min) { - if (value < m_state) { - m_state = value; - m_minmax_index = index; - } - } - else if (action == act_Sum) - m_state += value; - else if (action == act_Count) { - m_state++; - m_match_count = size_t(m_state); - } - else if (action == act_FindAll) { - Array::add_to_column(reinterpret_cast(m_state), index); - } - else if (action == act_ReturnFirst) { - m_state = index; - return false; - } - else { - REALM_ASSERT_DEBUG(false); - } - return (m_limit > m_match_count); - } - - template - inline bool match(size_t index, uint64_t indexpattern, util::Optional value) - { - // FIXME: This is a temporary hack for nullable integers. - if (value) { - return match(index, indexpattern, *value); - } - - // If value is null, the only sensible actions are count, find_all, and return first. - // Max, min, and sum should all have no effect. - if (action == act_Count) { - m_state++; - m_match_count = size_t(m_state); - } - else if (action == act_FindAll) { - Array::add_to_column(reinterpret_cast(m_state), index); - } - else if (action == act_ReturnFirst) { - m_match_count++; - m_state = index; - return false; - } - return m_limit > m_match_count; - } -}; - -// Used only for Basic-types: currently float and double -template -class QueryState : public QueryStateBase { -public: - R m_state; - size_t m_match_count; - size_t m_limit; - size_t m_minmax_index; // used only for min/max, to save index of current min/max value - - template - bool uses_val() - { - return (action == act_Max || action == act_Min || action == act_Sum || action == act_Count); - } - - void init(Action action, Array*, size_t limit) - { - REALM_ASSERT((std::is_same::value || std::is_same::value)); - m_match_count = 0; - m_limit = limit; - m_minmax_index = not_found; - - if (action == act_Max) - m_state = -std::numeric_limits::infinity(); - else if (action == act_Min) - m_state = std::numeric_limits::infinity(); - else if (action == act_Sum) - m_state = 0.0; - else { - REALM_ASSERT_DEBUG(false); - } - } - - template - inline bool match(size_t index, uint64_t /*indexpattern*/, resulttype value) - { - if (pattern) - return false; - - static_assert(action == act_Sum || action == act_Max || action == act_Min || action == act_Count, - "Search action not supported"); - - if (action == act_Count) { - ++m_match_count; - } - else if (!null::is_null_float(value)) { - ++m_match_count; - if (action == act_Max) { - if (value > m_state) { - m_state = value; - m_minmax_index = index; - } - } - else if (action == act_Min) { - if (value < m_state) { - m_state = value; - m_minmax_index = index; - } - } - else if (action == act_Sum) - m_state += value; - else { - REALM_ASSERT_DEBUG(false); - } - } - - return (m_limit > m_match_count); - } -}; - -inline bool RefOrTagged::is_ref() const noexcept -{ - return (m_value & 1) == 0; -} - -inline bool RefOrTagged::is_tagged() const noexcept -{ - return !is_ref(); -} - -inline ref_type RefOrTagged::get_as_ref() const noexcept -{ - // to_ref() is defined in - return to_ref(m_value); -} - -inline uint_fast64_t RefOrTagged::get_as_int() const noexcept -{ - // The bitwise AND is there in case uint_fast64_t is wider than 64 bits. - return (uint_fast64_t(m_value) & 0xFFFFFFFFFFFFFFFFULL) >> 1; -} - -inline RefOrTagged RefOrTagged::make_ref(ref_type ref) noexcept -{ - // from_ref() is defined in - int_fast64_t value = from_ref(ref); - return RefOrTagged(value); -} - -inline RefOrTagged RefOrTagged::make_tagged(uint_fast64_t i) noexcept -{ - REALM_ASSERT(i < (1ULL << 63)); - int_fast64_t value = util::from_twos_compl((i << 1) | 1); - return RefOrTagged(value); -} - -inline RefOrTagged::RefOrTagged(int_fast64_t value) noexcept - : m_value(value) -{ -} - -inline Array::Array(Allocator& allocator) noexcept - : m_alloc(allocator) -{ -} - -inline void Array::create(Type type, bool context_flag, size_t length, int_fast64_t value) -{ - MemRef mem = create_array(type, context_flag, length, value, m_alloc); // Throws - init_from_mem(mem); -} - - -inline void Array::init_from_ref(ref_type ref) noexcept -{ - REALM_ASSERT_DEBUG(ref); - char* header = m_alloc.translate(ref); - init_from_mem(MemRef(header, ref, m_alloc)); -} - - -inline void Array::init_from_parent() noexcept -{ - ref_type ref = get_ref_from_parent(); - init_from_ref(ref); -} - - -inline Array::Type Array::get_type() const noexcept -{ - if (m_is_inner_bptree_node) { - REALM_ASSERT_DEBUG(m_has_refs); - return type_InnerBptreeNode; - } - if (m_has_refs) - return type_HasRefs; - return type_Normal; -} - - -inline void Array::get_chunk(size_t ndx, int64_t res[8]) const noexcept -{ - REALM_ASSERT_DEBUG(ndx < m_size); - (this->*(m_vtable->chunk_getter))(ndx, res); -} - - -inline int64_t Array::get(size_t ndx) const noexcept -{ - REALM_ASSERT_DEBUG(is_attached()); - REALM_ASSERT_DEBUG(ndx < m_size); - return (this->*m_getter)(ndx); - - // Two ideas that are not efficient but may be worth looking into again: - /* - // Assume correct width is found early in REALM_TEMPEX, which is the case for B tree offsets that - // are probably either 2^16 long. Turns out to be 25% faster if found immediately, but 50-300% slower - // if found later - REALM_TEMPEX(return get, (ndx)); - */ - /* - // Slightly slower in both of the if-cases. Also needs an matchcount m_size check too, to avoid - // reading beyond array. - if (m_width >= 8 && m_size > ndx + 7) - return get<64>(ndx >> m_shift) & m_widthmask; - else - return (this->*(m_vtable->getter))(ndx); - */ -} - -inline int64_t Array::front() const noexcept -{ - return get(0); -} - -inline int64_t Array::back() const noexcept -{ - return get(m_size - 1); -} - -inline ref_type Array::get_as_ref(size_t ndx) const noexcept -{ - REALM_ASSERT_DEBUG(is_attached()); - REALM_ASSERT_DEBUG(m_has_refs); - int64_t v = get(ndx); - return to_ref(v); -} - -inline RefOrTagged Array::get_as_ref_or_tagged(size_t ndx) const noexcept -{ - REALM_ASSERT(has_refs()); - return RefOrTagged(get(ndx)); -} - -inline void Array::set(size_t ndx, RefOrTagged ref_or_tagged) -{ - REALM_ASSERT(has_refs()); - set(ndx, ref_or_tagged.m_value); // Throws -} - -inline void Array::add(RefOrTagged ref_or_tagged) -{ - REALM_ASSERT(has_refs()); - add(ref_or_tagged.m_value); // Throws -} - -inline void Array::ensure_minimum_width(RefOrTagged ref_or_tagged) -{ - REALM_ASSERT(has_refs()); - ensure_minimum_width(ref_or_tagged.m_value); // Throws -} - -inline bool Array::is_inner_bptree_node() const noexcept -{ - return m_is_inner_bptree_node; -} - -inline bool Array::has_refs() const noexcept -{ - return m_has_refs; -} - -inline void Array::set_has_refs(bool value) noexcept -{ - if (m_has_refs != value) { - REALM_ASSERT(!is_read_only()); - m_has_refs = value; - set_header_hasrefs(value); - } -} - -inline bool Array::get_context_flag() const noexcept -{ - return m_context_flag; -} - -inline void Array::set_context_flag(bool value) noexcept -{ - if (m_context_flag != value) { - REALM_ASSERT(!is_read_only()); - m_context_flag = value; - set_header_context_flag(value); - } -} - -inline ref_type Array::get_ref() const noexcept -{ - return m_ref; -} - -inline MemRef Array::get_mem() const noexcept -{ - return MemRef(get_header_from_data(m_data), m_ref, m_alloc); -} - -inline void Array::destroy() noexcept -{ - if (!is_attached()) - return; - char* header = get_header_from_data(m_data); - m_alloc.free_(m_ref, header); - m_data = nullptr; -} - -inline void Array::destroy_deep() noexcept -{ - if (!is_attached()) - return; - - if (m_has_refs) - destroy_children(); - - char* header = get_header_from_data(m_data); - m_alloc.free_(m_ref, header); - m_data = nullptr; -} - -inline ref_type Array::write(_impl::ArrayWriterBase& out, bool deep, bool only_if_modified) const -{ - REALM_ASSERT(is_attached()); - - if (only_if_modified && m_alloc.is_read_only(m_ref)) - return m_ref; - - if (!deep || !m_has_refs) - return do_write_shallow(out); // Throws - - return do_write_deep(out, only_if_modified); // Throws -} - -inline ref_type Array::write(ref_type ref, Allocator& alloc, _impl::ArrayWriterBase& out, bool only_if_modified) -{ - if (only_if_modified && alloc.is_read_only(ref)) - return ref; - - Array array(alloc); - array.init_from_ref(ref); - - if (!array.m_has_refs) - return array.do_write_shallow(out); // Throws - - return array.do_write_deep(out, only_if_modified); // Throws -} - -inline void Array::add(int_fast64_t value) -{ - insert(m_size, value); -} - -inline void Array::erase(size_t ndx) -{ - // This can throw, but only if array is currently in read-only - // memory. - move(ndx + 1, size(), ndx); - - // Update size (also in header) - --m_size; - set_header_size(m_size); -} - - -inline void Array::erase(size_t begin, size_t end) -{ - if (begin != end) { - // This can throw, but only if array is currently in read-only memory. - move(end, size(), begin); // Throws - - // Update size (also in header) - m_size -= end - begin; - set_header_size(m_size); - } -} - -inline void Array::clear() -{ - truncate(0); // Throws -} - -inline void Array::clear_and_destroy_children() -{ - truncate_and_destroy_children(0); -} - -inline void Array::destroy(ref_type ref, Allocator& alloc) noexcept -{ - destroy(MemRef(ref, alloc), alloc); -} - -inline void Array::destroy(MemRef mem, Allocator& alloc) noexcept -{ - alloc.free_(mem); -} - -inline void Array::destroy_deep(ref_type ref, Allocator& alloc) noexcept -{ - destroy_deep(MemRef(ref, alloc), alloc); -} - -inline void Array::destroy_deep(MemRef mem, Allocator& alloc) noexcept -{ - if (!get_hasrefs_from_header(mem.get_addr())) { - alloc.free_(mem); - return; - } - Array array(alloc); - array.init_from_mem(mem); - array.destroy_deep(); -} - - -inline void Array::adjust(size_t ndx, int_fast64_t diff) -{ - REALM_ASSERT_3(ndx, <=, m_size); - if (diff != 0) { - // FIXME: Should be optimized - int_fast64_t v = get(ndx); - set(ndx, int64_t(v + diff)); // Throws - } -} - -inline void Array::adjust(size_t begin, size_t end, int_fast64_t diff) -{ - if (diff != 0) { - // FIXME: Should be optimized - for (size_t i = begin; i != end; ++i) - adjust(i, diff); // Throws - } -} - - -//------------------------------------------------- - -inline bool Array::get_is_inner_bptree_node_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return (int(h[4]) & 0x80) != 0; -} -inline bool Array::get_hasrefs_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return (int(h[4]) & 0x40) != 0; -} -inline bool Array::get_context_flag_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return (int(h[4]) & 0x20) != 0; -} -inline Array::WidthType Array::get_wtype_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return WidthType((int(h[4]) & 0x18) >> 3); -} -inline uint_least8_t Array::get_width_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return uint_least8_t((1 << (int(h[4]) & 0x07)) >> 1); -} -inline size_t Array::get_size_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return (size_t(h[5]) << 16) + (size_t(h[6]) << 8) + h[7]; -} -inline size_t Array::get_capacity_from_header(const char* header) noexcept -{ - typedef unsigned char uchar; - const uchar* h = reinterpret_cast(header); - return (size_t(h[0]) << 19) + (size_t(h[1]) << 11) + (h[2] << 3); -} - - -inline char* Array::get_data_from_header(char* header) noexcept -{ - return header + header_size; -} -inline char* Array::get_header_from_data(char* data) noexcept -{ - return data - header_size; -} -inline const char* Array::get_data_from_header(const char* header) noexcept -{ - return get_data_from_header(const_cast(header)); -} - - -inline bool Array::get_is_inner_bptree_node_from_header() const noexcept -{ - return get_is_inner_bptree_node_from_header(get_header_from_data(m_data)); -} -inline bool Array::get_hasrefs_from_header() const noexcept -{ - return get_hasrefs_from_header(get_header_from_data(m_data)); -} -inline bool Array::get_context_flag_from_header() const noexcept -{ - return get_context_flag_from_header(get_header_from_data(m_data)); -} -inline Array::WidthType Array::get_wtype_from_header() const noexcept -{ - return get_wtype_from_header(get_header_from_data(m_data)); -} -inline uint_least8_t Array::get_width_from_header() const noexcept -{ - return get_width_from_header(get_header_from_data(m_data)); -} -inline size_t Array::get_size_from_header() const noexcept -{ - return get_size_from_header(get_header_from_data(m_data)); -} -inline size_t Array::get_capacity_from_header() const noexcept -{ - return get_capacity_from_header(get_header_from_data(m_data)); -} - - -inline void Array::set_header_is_inner_bptree_node(bool value, char* header) noexcept -{ - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[4] = uchar((int(h[4]) & ~0x80) | int(value) << 7); -} - -inline void Array::set_header_hasrefs(bool value, char* header) noexcept -{ - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[4] = uchar((int(h[4]) & ~0x40) | int(value) << 6); -} - -inline void Array::set_header_context_flag(bool value, char* header) noexcept -{ - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[4] = uchar((int(h[4]) & ~0x20) | int(value) << 5); -} - -inline void Array::set_header_wtype(WidthType value, char* header) noexcept -{ - // Indicates how to calculate size in bytes based on width - // 0: bits (width/8) * size - // 1: multiply width * size - // 2: ignore 1 * size - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[4] = uchar((int(h[4]) & ~0x18) | int(value) << 3); -} - -inline void Array::set_header_width(int value, char* header) noexcept -{ - // Pack width in 3 bits (log2) - int w = 0; - while (value) { - ++w; - value >>= 1; - } - REALM_ASSERT_3(w, <, 8); - - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[4] = uchar((int(h[4]) & ~0x7) | w); -} - -inline void Array::set_header_size(size_t value, char* header) noexcept -{ - REALM_ASSERT_3(value, <=, max_array_size); - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[5] = uchar((value >> 16) & 0x000000FF); - h[6] = uchar((value >> 8) & 0x000000FF); - h[7] = uchar(value & 0x000000FF); -} - -// Note: There is a copy of this function is test_alloc.cpp -inline void Array::set_header_capacity(size_t value, char* header) noexcept -{ - REALM_ASSERT_3(value, <=, (0xffffff << 3)); - typedef unsigned char uchar; - uchar* h = reinterpret_cast(header); - h[0] = uchar((value >> 19) & 0x000000FF); - h[1] = uchar((value >> 11) & 0x000000FF); - h[2] = uchar(value >> 3 & 0x000000FF); -} - - -inline void Array::set_header_is_inner_bptree_node(bool value) noexcept -{ - set_header_is_inner_bptree_node(value, get_header_from_data(m_data)); -} -inline void Array::set_header_hasrefs(bool value) noexcept -{ - set_header_hasrefs(value, get_header_from_data(m_data)); -} -inline void Array::set_header_context_flag(bool value) noexcept -{ - set_header_context_flag(value, get_header_from_data(m_data)); -} -inline void Array::set_header_wtype(WidthType value) noexcept -{ - set_header_wtype(value, get_header_from_data(m_data)); -} -inline void Array::set_header_width(int value) noexcept -{ - set_header_width(value, get_header_from_data(m_data)); -} -inline void Array::set_header_size(size_t value) noexcept -{ - set_header_size(value, get_header_from_data(m_data)); -} -inline void Array::set_header_capacity(size_t value) noexcept -{ - set_header_capacity(value, get_header_from_data(m_data)); -} - - -inline Array::Type Array::get_type_from_header(const char* header) noexcept -{ - if (get_is_inner_bptree_node_from_header(header)) - return type_InnerBptreeNode; - if (get_hasrefs_from_header(header)) - return type_HasRefs; - return type_Normal; -} - - -inline char* Array::get_header() noexcept -{ - return get_header_from_data(m_data); -} - -inline size_t Array::calc_byte_size(WidthType wtype, size_t size, uint_least8_t width) noexcept -{ - size_t num_bytes = 0; - switch (wtype) { - case wtype_Bits: { - // Current assumption is that size is at most 2^24 and that width is at most 64. - // In that case the following will never overflow. (Assuming that size_t is at least 32 bits) - REALM_ASSERT_3(size, <, 0x1000000); - size_t num_bits = size * width; - num_bytes = (num_bits + 7) >> 3; - break; - } - case wtype_Multiply: { - num_bytes = size * width; - break; - } - case wtype_Ignore: - num_bytes = size; - break; - } - - // Ensure 8-byte alignment - num_bytes = (num_bytes + 7) & ~size_t(7); - - num_bytes += header_size; - - return num_bytes; -} - -inline size_t Array::get_byte_size() const noexcept -{ - const char* header = get_header_from_data(m_data); - WidthType wtype = get_wtype_from_header(header); - size_t num_bytes = calc_byte_size(wtype, m_size, m_width); - - REALM_ASSERT_7(m_alloc.is_read_only(m_ref), ==, true, ||, num_bytes, <=, get_capacity_from_header(header)); - - return num_bytes; -} - - -inline size_t Array::get_byte_size_from_header(const char* header) noexcept -{ - size_t size = get_size_from_header(header); - uint_least8_t width = get_width_from_header(header); - WidthType wtype = get_wtype_from_header(header); - size_t num_bytes = calc_byte_size(wtype, size, width); - - return num_bytes; -} - - -inline void Array::init_header(char* header, bool is_inner_bptree_node, bool has_refs, bool context_flag, - WidthType width_type, int width, size_t size, size_t capacity) noexcept -{ - // Note: Since the header layout contains unallocated bit and/or - // bytes, it is important that we put the entire header into a - // well defined state initially. - std::fill(header, header + header_size, 0); - set_header_is_inner_bptree_node(is_inner_bptree_node, header); - set_header_hasrefs(has_refs, header); - set_header_context_flag(context_flag, header); - set_header_wtype(width_type, header); - set_header_width(width, header); - set_header_size(size, header); - set_header_capacity(capacity, header); -} - - -//------------------------------------------------- - -inline MemRef Array::clone_deep(Allocator& target_alloc) const -{ - char* header = get_header_from_data(m_data); - return clone(MemRef(header, m_ref, m_alloc), m_alloc, target_alloc); // Throws -} - -inline MemRef Array::create_empty_array(Type type, bool context_flag, Allocator& alloc) -{ - size_t size = 0; - int_fast64_t value = 0; - return create_array(type, context_flag, size, value, alloc); // Throws -} - -inline MemRef Array::create_array(Type type, bool context_flag, size_t size, int_fast64_t value, Allocator& alloc) -{ - return create(type, context_flag, wtype_Bits, size, value, alloc); // Throws -} - -inline bool Array::has_parent() const noexcept -{ - return m_parent != nullptr; -} - -inline ArrayParent* Array::get_parent() const noexcept -{ - return m_parent; -} - -inline void Array::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept -{ - m_parent = parent; - m_ndx_in_parent = ndx_in_parent; -} - -inline size_t Array::get_ndx_in_parent() const noexcept -{ - return m_ndx_in_parent; -} - -inline void Array::set_ndx_in_parent(size_t ndx) noexcept -{ - m_ndx_in_parent = ndx; -} - -inline void Array::adjust_ndx_in_parent(int diff) noexcept -{ - // Note that `diff` is promoted to an unsigned type, and that - // C++03 still guarantees the expected result regardless of the - // sizes of `int` and `decltype(m_ndx_in_parent)`. - m_ndx_in_parent += diff; -} - -inline ref_type Array::get_ref_from_parent() const noexcept -{ - ref_type ref = m_parent->get_child_ref(m_ndx_in_parent); - return ref; -} - -inline bool Array::is_attached() const noexcept -{ - return m_data != nullptr; -} - -inline void Array::detach() noexcept -{ - m_data = nullptr; -} - -inline size_t Array::size() const noexcept -{ - REALM_ASSERT_DEBUG(is_attached()); - return m_size; -} - -inline bool Array::is_empty() const noexcept -{ - return size() == 0; -} - -inline size_t Array::get_max_byte_size(size_t num_elems) noexcept -{ - int max_bytes_per_elem = 8; - return header_size + num_elems * max_bytes_per_elem; -} - -inline void Array::update_parent() -{ - if (m_parent) - m_parent->update_child_ref(m_ndx_in_parent, m_ref); -} - - -inline void Array::update_child_ref(size_t child_ndx, ref_type new_ref) -{ - set(child_ndx, new_ref); -} - -inline ref_type Array::get_child_ref(size_t child_ndx) const noexcept -{ - return get_as_ref(child_ndx); -} - -inline bool Array::is_read_only() const noexcept -{ - REALM_ASSERT_DEBUG(is_attached()); - return m_alloc.is_read_only(m_ref); -} - -inline void Array::copy_on_write() -{ -#if REALM_ENABLE_MEMDEBUG - // We want to relocate this array regardless if there is a need or not, in order to catch use-after-free bugs. - // Only exception is inside GroupWriter::write_group() (see explanation at the definition of the m_no_relocation - // member) - if (!m_no_relocation) { -#else - if (is_read_only()) { -#endif - do_copy_on_write(); - } -} - -inline void Array::ensure_minimum_width(int_fast64_t value) -{ - if (value >= m_lbound && value <= m_ubound) - return; - do_ensure_minimum_width(value); -} - - -//************************************************************************************* -// Finding code * -//************************************************************************************* - -template -int64_t Array::get(size_t ndx) const noexcept -{ - return get_universal(m_data, ndx); -} - -template -int64_t Array::get_universal(const char* data, size_t ndx) const -{ - if (w == 0) { - return 0; - } - else if (w == 1) { - size_t offset = ndx >> 3; - return (data[offset] >> (ndx & 7)) & 0x01; - } - else if (w == 2) { - size_t offset = ndx >> 2; - return (data[offset] >> ((ndx & 3) << 1)) & 0x03; - } - else if (w == 4) { - size_t offset = ndx >> 1; - return (data[offset] >> ((ndx & 1) << 2)) & 0x0F; - } - else if (w == 8) { - return *reinterpret_cast(data + ndx); - } - else if (w == 16) { - size_t offset = ndx * 2; - return *reinterpret_cast(data + offset); - } - else if (w == 32) { - size_t offset = ndx * 4; - return *reinterpret_cast(data + offset); - } - else if (w == 64) { - size_t offset = ndx * 8; - return *reinterpret_cast(data + offset); - } - else { - REALM_ASSERT_DEBUG(false); - return int64_t(-1); - } -} - -/* -find() (calls find_optimized()) will call match() for each search result. - -If pattern == true: - 'indexpattern' contains a 64-bit chunk of elements, each of 'width' bits in size where each element indicates a - match if its lower bit is set, otherwise it indicates a non-match. 'index' tells the database row index of the - first element. You must return true if you chose to 'consume' the chunk or false if not. If not, then Array-finder - will afterwards call match() successive times with pattern == false. - -If pattern == false: - 'index' tells the row index of a single match and 'value' tells its value. Return false to make Array-finder break - its search or return true to let it continue until 'end' or 'limit'. - -Array-finder decides itself if - and when - it wants to pass you an indexpattern. It depends on array bit width, match -frequency, and whether the arithemetic and computations for the given search criteria makes it feasible to construct -such a pattern. -*/ - -// These wrapper functions only exist to enable a possibility to make the compiler see that 'value' and/or 'index' are -// unused, such that caller's computation of these values will not be made. Only works if find_action() and -// find_action_pattern() rewritten as macros. Note: This problem has been fixed in next upcoming array.hpp version -template -bool Array::find_action(size_t index, util::Optional value, QueryState* state, - Callback callback) const -{ - if (action == act_CallbackIdx) - return callback(index); - else - return state->match(index, 0, value); -} -template -bool Array::find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const -{ - static_cast(callback); - if (action == act_CallbackIdx) { - // Possible future optimization: call callback(index) like in above find_action(), in a loop for each bit set - // in 'pattern' - return false; - } - return state->match(index, pattern, 0); -} - - -template -uint64_t Array::cascade(uint64_t a) const -{ - // Takes a chunk of values as argument and sets the least significant bit for each - // element which is zero or non-zero, depending on the template parameter. - // Example for zero=true: - // width == 4 and a = 0x5fd07a107610f610 - // will return: 0x0001000100010001 - - // static values needed for fast population count - const uint64_t m1 = 0x5555555555555555ULL; - - if (width == 1) { - return zero ? ~a : a; - } - else if (width == 2) { - // Masks to avoid spillover between segments in cascades - const uint64_t c1 = ~0ULL / 0x3 * 0x1; - - a |= (a >> 1) & c1; // cascade ones in non-zeroed segments - a &= m1; // isolate single bit in each segment - if (zero) - a ^= m1; // reverse isolated bits if checking for zeroed segments - - return a; - } - else if (width == 4) { - const uint64_t m = ~0ULL / 0xF * 0x1; - - // Masks to avoid spillover between segments in cascades - const uint64_t c1 = ~0ULL / 0xF * 0x7; - const uint64_t c2 = ~0ULL / 0xF * 0x3; - - a |= (a >> 1) & c1; // cascade ones in non-zeroed segments - a |= (a >> 2) & c2; - a &= m; // isolate single bit in each segment - if (zero) - a ^= m; // reverse isolated bits if checking for zeroed segments - - return a; - } - else if (width == 8) { - const uint64_t m = ~0ULL / 0xFF * 0x1; - - // Masks to avoid spillover between segments in cascades - const uint64_t c1 = ~0ULL / 0xFF * 0x7F; - const uint64_t c2 = ~0ULL / 0xFF * 0x3F; - const uint64_t c3 = ~0ULL / 0xFF * 0x0F; - - a |= (a >> 1) & c1; // cascade ones in non-zeroed segments - a |= (a >> 2) & c2; - a |= (a >> 4) & c3; - a &= m; // isolate single bit in each segment - if (zero) - a ^= m; // reverse isolated bits if checking for zeroed segments - - return a; - } - else if (width == 16) { - const uint64_t m = ~0ULL / 0xFFFF * 0x1; - - // Masks to avoid spillover between segments in cascades - const uint64_t c1 = ~0ULL / 0xFFFF * 0x7FFF; - const uint64_t c2 = ~0ULL / 0xFFFF * 0x3FFF; - const uint64_t c3 = ~0ULL / 0xFFFF * 0x0FFF; - const uint64_t c4 = ~0ULL / 0xFFFF * 0x00FF; - - a |= (a >> 1) & c1; // cascade ones in non-zeroed segments - a |= (a >> 2) & c2; - a |= (a >> 4) & c3; - a |= (a >> 8) & c4; - a &= m; // isolate single bit in each segment - if (zero) - a ^= m; // reverse isolated bits if checking for zeroed segments - - return a; - } - - else if (width == 32) { - const uint64_t m = ~0ULL / 0xFFFFFFFF * 0x1; - - // Masks to avoid spillover between segments in cascades - const uint64_t c1 = ~0ULL / 0xFFFFFFFF * 0x7FFFFFFF; - const uint64_t c2 = ~0ULL / 0xFFFFFFFF * 0x3FFFFFFF; - const uint64_t c3 = ~0ULL / 0xFFFFFFFF * 0x0FFFFFFF; - const uint64_t c4 = ~0ULL / 0xFFFFFFFF * 0x00FFFFFF; - const uint64_t c5 = ~0ULL / 0xFFFFFFFF * 0x0000FFFF; - - a |= (a >> 1) & c1; // cascade ones in non-zeroed segments - a |= (a >> 2) & c2; - a |= (a >> 4) & c3; - a |= (a >> 8) & c4; - a |= (a >> 16) & c5; - a &= m; // isolate single bit in each segment - if (zero) - a ^= m; // reverse isolated bits if checking for zeroed segments - - return a; - } - else if (width == 64) { - return (a == 0) == zero; - } - else { - REALM_ASSERT_DEBUG(false); - return uint64_t(-1); - } -} - -// This is the main finding function for Array. Other finding functions are just wrappers around this one. -// Search for 'value' using condition cond (Equal, NotEqual, Less, etc) and call find_action() or -// find_action_pattern() for each match. Break and return if find_action() returns false or 'end' is reached. - -// If nullable_array is set, then find_optimized() will treat the array is being nullable, i.e. it will skip the -// first entry and compare correctly against null, etc. -// -// If find_null is set, it means that we search for a null. In that case, `value` is ignored. If find_null is set, -// then nullable_array must be set too. -template -bool Array::find_optimized(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array, bool find_null) const -{ - REALM_ASSERT(!(find_null && !nullable_array)); - REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); - - size_t start2 = start; - cond c; - - if (end == npos) - end = nullable_array ? size() - 1 : size(); - - if (nullable_array) { - if (std::is_same::value) { - // In case of Equal it is safe to use the optimized logic. We just have to fetch the null value - // if this is what we are looking for. And we have to adjust the indexes to compensate for the - // null value at position 0. - if (find_null) { - value = get(0); - } - else { - // If the value to search for is equal to the null value, the value cannot be in the array - if (value == get(0)) { - return true; - } - } - start2++; - end++; - baseindex--; - } - else { - // We were called by find() of a nullable array. So skip first entry, take nulls in count, etc, etc. Fixme: - // Huge speed optimizations are possible here! This is a very simple generic method. - auto null_value = get(0); - for (; start2 < end; start2++) { - int64_t v = get(start2 + 1); - bool value_is_null = (v == null_value); - if (c(v, value, value_is_null, find_null)) { - util::Optional v2(value_is_null ? util::none : util::make_optional(v)); - if (!find_action(start2 + baseindex, v2, state, callback)) - return false; // tell caller to stop aggregating/search - } - } - return true; // tell caller to continue aggregating/search (on next array leafs) - } - } - - - // Test first few items with no initial time overhead - if (start2 > 0) { - if (m_size > start2 && c(get(start2), value) && start2 < end) { - if (!find_action(start2 + baseindex, get(start2), state, callback)) - return false; - } - - ++start2; - - if (m_size > start2 && c(get(start2), value) && start2 < end) { - if (!find_action(start2 + baseindex, get(start2), state, callback)) - return false; - } - - ++start2; - - if (m_size > start2 && c(get(start2), value) && start2 < end) { - if (!find_action(start2 + baseindex, get(start2), state, callback)) - return false; - } - - ++start2; - - if (m_size > start2 && c(get(start2), value) && start2 < end) { - if (!find_action(start2 + baseindex, get(start2), state, callback)) - return false; - } - - ++start2; - } - - if (!(m_size > start2 && start2 < end)) - return true; - - if (end == size_t(-1)) - end = m_size; - - // Return immediately if no items in array can match (such as if cond == Greater && value == 100 && - // m_ubound == 15) - if (!c.can_match(value, m_lbound, m_ubound)) - return true; - - // optimization if all items are guaranteed to match (such as cond == NotEqual && value == 100 && m_ubound == 15) - if (c.will_match(value, m_lbound, m_ubound)) { - size_t end2; - - if (action == act_CallbackIdx) - end2 = end; - else { - REALM_ASSERT_DEBUG(state->m_match_count < state->m_limit); - size_t process = state->m_limit - state->m_match_count; - end2 = end - start2 > process ? start2 + process : end; - } - if (action == act_Sum || action == act_Max || action == act_Min) { - int64_t res; - size_t res_ndx = 0; - if (action == act_Sum) - res = Array::sum(start2, end2); - if (action == act_Max) - Array::maximum(res, start2, end2, &res_ndx); - if (action == act_Min) - Array::minimum(res, start2, end2, &res_ndx); - - find_action(res_ndx + baseindex, res, state, callback); - // find_action will increment match count by 1, so we need to `-1` from the number of elements that - // we performed the fast Array methods on. - state->m_match_count += end2 - start2 - 1; - } - else if (action == act_Count) { - state->m_state += end2 - start2; - } - else { - for (; start2 < end2; start2++) - if (!find_action(start2 + baseindex, get(start2), state, callback)) - return false; - } - return true; - } - - // finder cannot handle this bitwidth - REALM_ASSERT_3(m_width, !=, 0); - -#if defined(REALM_COMPILER_SSE) - // Only use SSE if payload is at least one SSE chunk (128 bits) in size. Also note taht SSE doesn't support - // Less-than comparison for 64-bit values. - if ((!(std::is_same::value && m_width == 64)) && end - start2 >= sizeof(__m128i) && m_width >= 8 && - (sseavx<42>() || (sseavx<30>() && std::is_same::value && m_width < 64))) { - - // find_sse() must start2 at 16-byte boundary, so search area before that using compare_equality() - __m128i* const a = reinterpret_cast<__m128i*>(round_up(m_data + start2 * bitwidth / 8, sizeof(__m128i))); - __m128i* const b = reinterpret_cast<__m128i*>(round_down(m_data + end * bitwidth / 8, sizeof(__m128i))); - - if (!compare( - value, start2, (reinterpret_cast(a) - m_data) * 8 / no0(bitwidth), baseindex, state, callback)) - return false; - - // Search aligned area with SSE - if (b > a) { - if (sseavx<42>()) { - if (!find_sse( - value, a, b - a, state, - baseindex + ((reinterpret_cast(a) - m_data) * 8 / no0(bitwidth)), callback)) - return false; - } - else if (sseavx<30>()) { - - if (!find_sse( - value, a, b - a, state, - baseindex + ((reinterpret_cast(a) - m_data) * 8 / no0(bitwidth)), callback)) - return false; - } - } - - // Search remainder with compare_equality() - if (!compare( - value, (reinterpret_cast(b) - m_data) * 8 / no0(bitwidth), end, baseindex, state, callback)) - return false; - - return true; - } - else { - return compare(value, start2, end, baseindex, state, callback); - } -#else - return compare(value, start2, end, baseindex, state, callback); -#endif -} - -template -inline int64_t Array::lower_bits() const -{ - if (width == 1) - return 0xFFFFFFFFFFFFFFFFULL; - else if (width == 2) - return 0x5555555555555555ULL; - else if (width == 4) - return 0x1111111111111111ULL; - else if (width == 8) - return 0x0101010101010101ULL; - else if (width == 16) - return 0x0001000100010001ULL; - else if (width == 32) - return 0x0000000100000001ULL; - else if (width == 64) - return 0x0000000000000001ULL; - else { - REALM_ASSERT_DEBUG(false); - return int64_t(-1); - } -} - -// Tests if any chunk in 'value' is 0 -template -inline bool Array::test_zero(uint64_t value) const -{ - uint64_t hasZeroByte; - uint64_t lower = lower_bits(); - uint64_t upper = lower_bits() * 1ULL << (width == 0 ? 0 : (width - 1ULL)); - hasZeroByte = (value - lower) & ~value & upper; - return hasZeroByte != 0; -} - -// Finds first zero (if eq == true) or non-zero (if eq == false) element in v and returns its position. -// IMPORTANT: This function assumes that at least 1 item matches (test this with test_zero() or other means first)! -template -size_t Array::find_zero(uint64_t v) const -{ - size_t start = 0; - uint64_t hasZeroByte; - // Warning free way of computing (1ULL << width) - 1 - uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - 1ULL)); - - if (eq == (((v >> (width * start)) & mask) == 0)) { - return 0; - } - - // Bisection optimization, speeds up small bitwidths with high match frequency. More partions than 2 do NOT pay - // off because the work done by test_zero() is wasted for the cases where the value exists in first half, but - // useful if it exists in last half. Sweet spot turns out to be the widths and partitions below. - if (width <= 8) { - hasZeroByte = test_zero(v | 0xffffffff00000000ULL); - if (eq ? !hasZeroByte : (v & 0x00000000ffffffffULL) == 0) { - // 00?? -> increasing - start += 64 / no0(width) / 2; - if (width <= 4) { - hasZeroByte = test_zero(v | 0xffff000000000000ULL); - if (eq ? !hasZeroByte : (v & 0x0000ffffffffffffULL) == 0) { - // 000? - start += 64 / no0(width) / 4; - } - } - } - else { - if (width <= 4) { - // ??00 - hasZeroByte = test_zero(v | 0xffffffffffff0000ULL); - if (eq ? !hasZeroByte : (v & 0x000000000000ffffULL) == 0) { - // 0?00 - start += 64 / no0(width) / 4; - } - } - } - } - - while (eq == (((v >> (width * start)) & mask) != 0)) { - // You must only call find_zero() if you are sure that at least 1 item matches - REALM_ASSERT_3(start, <=, 8 * sizeof(v)); - start++; - } - - return start; -} - -// Generate a magic constant used for later bithacks -template -int64_t Array::find_gtlt_magic(int64_t v) const -{ - uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - - 1ULL)); // Warning free way of computing (1ULL << width) - 1 - uint64_t mask2 = mask1 >> 1; - uint64_t magic = gt ? (~0ULL / no0(mask1) * (mask2 - v)) : (~0ULL / no0(mask1) * v); - return magic; -} - -template -bool Array::find_gtlt_fast(uint64_t chunk, uint64_t magic, QueryState* state, size_t baseindex, - Callback callback) const -{ - // Tests if a a chunk of values contains values that are greater (if gt == true) or less (if gt == false) than v. - // Fast, but limited to work when all values in the chunk are positive. - - uint64_t mask1 = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - - 1ULL)); // Warning free way of computing (1ULL << width) - 1 - uint64_t mask2 = mask1 >> 1; - uint64_t m = gt ? (((chunk + magic) | chunk) & ~0ULL / no0(mask1) * (mask2 + 1)) - : ((chunk - magic) & ~chunk & ~0ULL / no0(mask1) * (mask2 + 1)); - size_t p = 0; - while (m) { - if (find_action_pattern(baseindex, m >> (no0(width) - 1), state, callback)) - break; // consumed, so do not call find_action() - - size_t t = first_set_bit64(m) / no0(width); - p += t; - if (!find_action(p + baseindex, (chunk >> (p * width)) & mask1, state, callback)) - return false; - - if ((t + 1) * width == 64) - m = 0; - else - m >>= (t + 1) * width; - p++; - } - - return true; -} - -// clang-format off -template -bool Array::find_gtlt(int64_t v, uint64_t chunk, QueryState* state, size_t baseindex, Callback callback) const -{ - // Find items in 'chunk' that are greater (if gt == true) or smaller (if gt == false) than 'v'. Fixme, __forceinline can make it crash in vS2010 - find out why - if (width == 1) { - for (size_t t = 0; t < 64; t++) { - if (gt ? static_cast(chunk & 0x1) > v : static_cast(chunk & 0x1) < v) {if (!find_action( t + baseindex, static_cast(chunk & 0x1), state, callback)) return false;} - chunk >>= 1; - } - } - else if (width == 2) { - // Alot (50% +) faster than loop/compiler-unrolled loop - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 0 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 1 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 2 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 3 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 4 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 5 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 6 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 7 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 8 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 9 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 10 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 11 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 12 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 13 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 14 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 15 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 16 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 17 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 18 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 19 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 20 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 21 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 22 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 23 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 24 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 25 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 26 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 27 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 28 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 29 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 30 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - if (gt ? static_cast(chunk & 0x3) > v : static_cast(chunk & 0x3) < v) {if (!find_action( 31 + baseindex, static_cast(chunk & 0x3), state, callback)) return false;} - chunk >>= 2; - } - else if (width == 4) { - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 0 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 1 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 2 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 3 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 4 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 5 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 6 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 7 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 8 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 9 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 10 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 11 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 12 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 13 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 14 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - if (gt ? static_cast(chunk & 0xf) > v : static_cast(chunk & 0xf) < v) {if (!find_action( 15 + baseindex, static_cast(chunk & 0xf), state, callback)) return false;} - chunk >>= 4; - } - else if (width == 8) { - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 0 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 1 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 2 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 3 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 4 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 5 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 6 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 7 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 8; - } - else if (width == 16) { - - if (gt ? static_cast(chunk >> 0 * 16) > v : static_cast(chunk >> 0 * 16) < v) {if (!find_action( 0 + baseindex, static_cast(chunk >> 0 * 16), state, callback)) return false;}; - if (gt ? static_cast(chunk >> 1 * 16) > v : static_cast(chunk >> 1 * 16) < v) {if (!find_action( 1 + baseindex, static_cast(chunk >> 1 * 16), state, callback)) return false;}; - if (gt ? static_cast(chunk >> 2 * 16) > v : static_cast(chunk >> 2 * 16) < v) {if (!find_action( 2 + baseindex, static_cast(chunk >> 2 * 16), state, callback)) return false;}; - if (gt ? static_cast(chunk >> 3 * 16) > v : static_cast(chunk >> 3 * 16) < v) {if (!find_action( 3 + baseindex, static_cast(chunk >> 3 * 16), state, callback)) return false;}; - } - else if (width == 32) { - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 0 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 32; - if (gt ? static_cast(chunk) > v : static_cast(chunk) < v) {if (!find_action( 1 + baseindex, static_cast(chunk), state, callback)) return false;} - chunk >>= 32; - } - else if (width == 64) { - if (gt ? static_cast(v) > v : static_cast(v) < v) {if (!find_action( 0 + baseindex, static_cast(v), state, callback)) return false;}; - } - - return true; -} -// clang-format on - -/// Find items in this Array that are equal (eq == true) or different (eq = false) from 'value' -template -inline bool Array::compare_equality(int64_t value, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const -{ - REALM_ASSERT_DEBUG(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); - - size_t ee = round_up(start, 64 / no0(width)); - ee = ee > end ? end : ee; - for (; start < ee; ++start) - if (eq ? (get(start) == value) : (get(start) != value)) { - if (!find_action(start + baseindex, get(start), state, callback)) - return false; - } - - if (start >= end) - return true; - - if (width != 32 && width != 64) { - const int64_t* p = reinterpret_cast(m_data + (start * width / 8)); - const int64_t* const e = reinterpret_cast(m_data + (end * width / 8)) - 1; - const uint64_t mask = (width == 64 ? ~0ULL : ((1ULL << (width == 64 ? 0 : width)) - - 1ULL)); // Warning free way of computing (1ULL << width) - 1 - const uint64_t valuemask = - ~0ULL / no0(mask) * (value & mask); // the "== ? :" is to avoid division by 0 compiler error - - while (p < e) { - uint64_t chunk = *p; - uint64_t v2 = chunk ^ valuemask; - start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(width); - size_t a = 0; - - while (eq ? test_zero(v2) : v2) { - - if (find_action_pattern(start + baseindex, cascade(v2), state, callback)) - break; // consumed - - size_t t = find_zero(v2); - a += t; - - if (a >= 64 / no0(width)) - break; - - if (!find_action(a + start + baseindex, get(start + a), state, callback)) - return false; - v2 >>= (t + 1) * width; - a += 1; - } - - ++p; - } - - // Loop ended because we are near end or end of array. No need to optimize search in remainder in this case - // because end of array means that - // lots of search work has taken place prior to ending here. So time spent searching remainder is relatively - // tiny - start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(width); - } - - while (start < end) { - if (eq ? get(start) == value : get(start) != value) { - if (!find_action(start + baseindex, get(start), state, callback)) - return false; - } - ++start; - } - - return true; -} - -// There exists a couple of find() functions that take more or less template arguments. Always call the one that -// takes as most as possible to get best performance. - -// This is the one installed into the m_vtable->finder slots. -template -bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const -{ - return find(value, start, end, baseindex, state, CallbackDummy()); -} - -template -bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array, bool find_null) const -{ - REALM_TEMPEX4(return find, cond, action, m_width, Callback, - (value, start, end, baseindex, state, callback, nullable_array, find_null)); -} - -template -bool Array::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback, bool nullable_array, bool find_null) const -{ - return find_optimized(value, start, end, baseindex, state, callback, - nullable_array, find_null); -} - -#ifdef REALM_COMPILER_SSE -// 'items' is the number of 16-byte SSE chunks. Returns index of packed element relative to first integer of first -// chunk -template -bool Array::find_sse(int64_t value, __m128i* data, size_t items, QueryState* state, size_t baseindex, - Callback callback) const -{ - __m128i search = {0}; - - if (width == 8) - search = _mm_set1_epi8(static_cast(value)); - else if (width == 16) - search = _mm_set1_epi16(static_cast(value)); - else if (width == 32) - search = _mm_set1_epi32(static_cast(value)); - else if (width == 64) { - if (std::is_same::value) - REALM_ASSERT(false); - else - search = _mm_set_epi64x(value, value); - } - - return find_sse_intern(data, &search, items, state, baseindex, callback); -} - -// Compares packed action_data with packed data (equal, less, etc) and performs aggregate action (max, min, sum, -// find_all, etc) on value inside action_data for first match, if any -template -REALM_FORCEINLINE bool Array::find_sse_intern(__m128i* action_data, __m128i* data, size_t items, - QueryState* state, size_t baseindex, Callback callback) const -{ - size_t i = 0; - __m128i compare_result = {0}; - unsigned int resmask; - - // Search loop. Unrolling it has been tested to NOT increase performance (apparently mem bound) - for (i = 0; i < items; ++i) { - // equal / not-equal - if (std::is_same::value || std::is_same::value) { - if (width == 8) - compare_result = _mm_cmpeq_epi8(action_data[i], *data); - if (width == 16) - compare_result = _mm_cmpeq_epi16(action_data[i], *data); - if (width == 32) - compare_result = _mm_cmpeq_epi32(action_data[i], *data); - if (width == 64) { - compare_result = _mm_cmpeq_epi64(action_data[i], *data); // SSE 4.2 only - } - } - - // greater - else if (std::is_same::value) { - if (width == 8) - compare_result = _mm_cmpgt_epi8(action_data[i], *data); - if (width == 16) - compare_result = _mm_cmpgt_epi16(action_data[i], *data); - if (width == 32) - compare_result = _mm_cmpgt_epi32(action_data[i], *data); - if (width == 64) - compare_result = _mm_cmpgt_epi64(action_data[i], *data); - } - // less - else if (std::is_same::value) { - if (width == 8) - compare_result = _mm_cmplt_epi8(action_data[i], *data); - else if (width == 16) - compare_result = _mm_cmplt_epi16(action_data[i], *data); - else if (width == 32) - compare_result = _mm_cmplt_epi32(action_data[i], *data); - else - REALM_ASSERT(false); - } - - resmask = _mm_movemask_epi8(compare_result); - - if (std::is_same::value) - resmask = ~resmask & 0x0000ffff; - - size_t s = i * sizeof(__m128i) * 8 / no0(width); - - while (resmask != 0) { - - uint64_t upper = lower_bits() << (no0(width / 8) - 1); - uint64_t pattern = - resmask & - upper; // fixme, bits at wrong offsets. Only OK because we only use them in 'count' aggregate - if (find_action_pattern(s + baseindex, pattern, state, callback)) - break; - - size_t idx = first_set_bit(resmask) * 8 / no0(width); - s += idx; - if (!find_action( - s + baseindex, get_universal(reinterpret_cast(action_data), s), state, callback)) - return false; - resmask >>= (idx + 1) * no0(width) / 8; - ++s; - } - } - - return true; -} -#endif // REALM_COMPILER_SSE - -template -bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const -{ - cond c; - REALM_ASSERT_3(start, <=, end); - if (start == end) - return true; - - - int64_t v; - - // We can compare first element without checking for out-of-range - v = get(start); - if (c(v, foreign->get(start))) { - if (!find_action(start + baseindex, v, state, callback)) - return false; - } - - start++; - - if (start + 3 < end) { - v = get(start); - if (c(v, foreign->get(start))) - if (!find_action(start + baseindex, v, state, callback)) - return false; - - v = get(start + 1); - if (c(v, foreign->get(start + 1))) - if (!find_action(start + 1 + baseindex, v, state, callback)) - return false; - - v = get(start + 2); - if (c(v, foreign->get(start + 2))) - if (!find_action(start + 2 + baseindex, v, state, callback)) - return false; - - start += 3; - } - else if (start == end) { - return true; - } - - bool r; - REALM_TEMPEX4(r = compare_leafs, cond, action, m_width, Callback, - (foreign, start, end, baseindex, state, callback)) - return r; -} - - -template -bool Array::compare_leafs(const Array* foreign, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const -{ - size_t fw = foreign->m_width; - bool r; - REALM_TEMPEX5(r = compare_leafs_4, cond, action, width, Callback, fw, - (foreign, start, end, baseindex, state, callback)) - return r; -} - - -template -bool Array::compare_leafs_4(const Array* foreign, size_t start, size_t end, size_t baseindex, - QueryState* state, Callback callback) const -{ - cond c; - char* foreign_m_data = foreign->m_data; - - if (width == 0 && foreign_width == 0) { - if (c(0, 0)) { - while (start < end) { - if (!find_action(start + baseindex, 0, state, callback)) - return false; - start++; - } - } - else { - return true; - } - } - - -#if defined(REALM_COMPILER_SSE) - if (sseavx<42>() && width == foreign_width && (width == 8 || width == 16 || width == 32)) { - // We can only use SSE if both bitwidths are equal and above 8 bits and all values are signed - // and the two arrays are aligned the same way - if ((reinterpret_cast(m_data) & 0xf) == (reinterpret_cast(foreign_m_data) & 0xf)) { - while (start < end && (((reinterpret_cast(m_data) & 0xf) * 8 + start * width) % (128) != 0)) { - int64_t v = get_universal(m_data, start); - int64_t fv = get_universal(foreign_m_data, start); - if (c(v, fv)) { - if (!find_action(start + baseindex, v, state, callback)) - return false; - } - start++; - } - if (start == end) - return true; - - - size_t sse_items = (end - start) * width / 128; - size_t sse_end = start + sse_items * 128 / no0(width); - - while (start < sse_end) { - __m128i* a = reinterpret_cast<__m128i*>(m_data + start * width / 8); - __m128i* b = reinterpret_cast<__m128i*>(foreign_m_data + start * width / 8); - - bool continue_search = - find_sse_intern(a, b, 1, state, baseindex + start, callback); - - if (!continue_search) - return false; - - start += 128 / no0(width); - } - } - } -#endif - - while (start < end) { - int64_t v = get_universal(m_data, start); - int64_t fv = get_universal(foreign_m_data, start); - - if (c(v, fv)) { - if (!find_action(start + baseindex, v, state, callback)) - return false; - } - - start++; - } - - return true; -} - - -template -bool Array::compare(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const -{ - bool ret = false; - - if (std::is_same::value) - ret = compare_equality(value, start, end, baseindex, state, callback); - else if (std::is_same::value) - ret = compare_equality(value, start, end, baseindex, state, callback); - else if (std::is_same::value) - ret = compare_relation(value, start, end, baseindex, state, callback); - else if (std::is_same::value) - ret = compare_relation(value, start, end, baseindex, state, callback); - else - REALM_ASSERT_DEBUG(false); - - return ret; -} - -template -bool Array::compare_relation(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const -{ - REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); - uint64_t mask = (bitwidth == 64 ? ~0ULL : ((1ULL << (bitwidth == 64 ? 0 : bitwidth)) - - 1ULL)); // Warning free way of computing (1ULL << width) - 1 - - size_t ee = round_up(start, 64 / no0(bitwidth)); - ee = ee > end ? end : ee; - for (; start < ee; start++) { - if (gt ? (get(start) > value) : (get(start) < value)) { - if (!find_action(start + baseindex, get(start), state, callback)) - return false; - } - } - - if (start >= end) - return true; // none found, continue (return true) regardless what find_action() would have returned on match - - const int64_t* p = reinterpret_cast(m_data + (start * bitwidth / 8)); - const int64_t* const e = reinterpret_cast(m_data + (end * bitwidth / 8)) - 1; - - // Matches are rare enough to setup fast linear search for remaining items. We use - // bit hacks from http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord - - if (bitwidth == 1 || bitwidth == 2 || bitwidth == 4 || bitwidth == 8 || bitwidth == 16) { - uint64_t magic = find_gtlt_magic(value); - - // Bit hacks only work if searched item has its most significant bit clear for 'greater than' or - // 'item <= 1 << bitwidth' for 'less than' - if (value != int64_t((magic & mask)) && value >= 0 && bitwidth >= 2 && - value <= static_cast((mask >> 1) - (gt ? 1 : 0))) { - // 15 ms - while (p < e) { - uint64_t upper = lower_bits() << (no0(bitwidth) - 1); - - const int64_t v = *p; - size_t idx; - - // Bit hacks only works if all items in chunk have their most significant bit clear. Test this: - upper = upper & v; - - if (!upper) { - idx = find_gtlt_fast( - v, magic, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, - callback); - } - else - idx = find_gtlt( - value, v, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, - callback); - - if (!idx) - return false; - ++p; - } - } - else { - // 24 ms - while (p < e) { - int64_t v = *p; - if (!find_gtlt( - value, v, state, (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth) + baseindex, - callback)) - return false; - ++p; - } - } - start = (p - reinterpret_cast(m_data)) * 8 * 8 / no0(bitwidth); - } - - // matchcount logic in SIMD no longer pays off for 32/64 bit ints because we have just 4/2 elements - - // Test unaligned end and/or values of width > 16 manually - while (start < end) { - if (gt ? get(start) > value : get(start) < value) { - if (!find_action(start + baseindex, get(start), state, callback)) - return false; - } - ++start; - } - return true; -} - -template -size_t Array::find_first(int64_t value, size_t start, size_t end) const -{ - REALM_ASSERT(start <= m_size && (end <= m_size || end == size_t(-1)) && start <= end); - QueryState state; - state.init(act_ReturnFirst, nullptr, - 1); // todo, would be nice to avoid this in order to speed up find_first loops - Finder finder = m_vtable->finder[cond::condition]; - (this->*finder)(value, start, end, 0, &state); - - return static_cast(state.m_state); -} - -//************************************************************************************* -// Finding code ends * -//************************************************************************************* - - -} // namespace realm - -#endif // REALM_ARRAY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_basic.hpp b/Lesson14/Pods/Realm/include/core/realm/array_basic.hpp deleted file mode 100644 index 6b9c212..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_basic.hpp +++ /dev/null @@ -1,120 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_BASIC_HPP -#define REALM_ARRAY_BASIC_HPP - -#include - -namespace realm { - -/// A BasicArray can currently only be used for simple unstructured -/// types like float, double. -template -class BasicArray : public Array { -public: - explicit BasicArray(Allocator&) noexcept; - ~BasicArray() noexcept override - { - } - - // Disable copying, this is not allowed. - BasicArray& operator=(const BasicArray&) = delete; - BasicArray(const BasicArray&) = delete; - - T get(size_t ndx) const noexcept; - bool is_null(size_t ndx) const noexcept; - void add(T value); - void set(size_t ndx, T value); - void set_null(size_t ndx); - void insert(size_t ndx, T value); - void erase(size_t ndx); - void truncate(size_t size); - void clear(); - - size_t find_first(T value, size_t begin = 0, size_t end = npos) const; - void find_all(IntegerColumn* result, T value, size_t add_offset = 0, size_t begin = 0, size_t end = npos) const; - - size_t count(T value, size_t begin = 0, size_t end = npos) const; - bool maximum(T& result, size_t begin = 0, size_t end = npos) const; - bool minimum(T& result, size_t begin = 0, size_t end = npos) const; - - /// Compare two arrays for equality. - bool compare(const BasicArray&) const; - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static T get(const char* header, size_t ndx) noexcept; - - ref_type bptree_leaf_insert(size_t ndx, T, TreeInsertBase& state); - - size_t lower_bound(T value) const noexcept; - size_t upper_bound(T value) const noexcept; - - /// Construct a basic array of the specified size and return just - /// the reference to the underlying memory. All elements will be - /// initialized to `T()`. - static MemRef create_array(size_t size, Allocator&); - - static MemRef create_array(Array::Type leaf_type, bool context_flag, size_t size, T value, Allocator&); - - /// Create a new empty array and attach this accessor to it. This - /// does not modify the parent reference information of this - /// accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(Array::Type = type_Normal, bool context_flag = false); - - /// Construct a copy of the specified slice of this basic array - /// using the specified target allocator. - MemRef slice(size_t offset, size_t size, Allocator& target_alloc) const; - MemRef slice_and_clone_children(size_t offset, size_t size, Allocator& target_alloc) const; - -#ifdef REALM_DEBUG - void to_dot(std::ostream&, StringData title = StringData()) const; -#endif - -private: - size_t find(T target, size_t begin, size_t end) const; - - size_t calc_byte_len(size_t count, size_t width) const override; - virtual size_t calc_item_count(size_t bytes, size_t width) const noexcept override; - - template - bool minmax(T& result, size_t begin, size_t end) const; - - /// Calculate the total number of bytes needed for a basic array - /// with the specified number of elements. This includes the size - /// of the header. The result will be upwards aligned to the - /// closest 8-byte boundary. - static size_t calc_aligned_byte_size(size_t size); -}; - - -// Class typedefs for BasicArray's: ArrayFloat and ArrayDouble -typedef BasicArray ArrayFloat; -typedef BasicArray ArrayDouble; - -} // namespace realm - -#include - -#endif // REALM_ARRAY_BASIC_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_basic_tpl.hpp b/Lesson14/Pods/Realm/include/core/realm/array_basic_tpl.hpp deleted file mode 100644 index 5ce37fd..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_basic_tpl.hpp +++ /dev/null @@ -1,467 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_BASIC_TPL_HPP -#define REALM_ARRAY_BASIC_TPL_HPP - -#include -#include -#include -#include - -#include - -namespace realm { - -template -inline BasicArray::BasicArray(Allocator& allocator) noexcept - : Array(allocator) -{ -} - -template -inline MemRef BasicArray::create_array(size_t init_size, Allocator& allocator) -{ - size_t byte_size_0 = calc_aligned_byte_size(init_size); // Throws - // Adding zero to Array::initial_capacity to avoid taking the - // address of that member - size_t byte_size = std::max(byte_size_0, Array::initial_capacity + 0); // Throws - - MemRef mem = allocator.alloc(byte_size); // Throws - - bool is_inner_bptree_node = false; - bool has_refs = false; - bool context_flag = false; - int width = sizeof(T); - init_header(mem.get_addr(), is_inner_bptree_node, has_refs, context_flag, wtype_Multiply, width, init_size, - byte_size); - - return mem; -} - - -template -inline MemRef BasicArray::create_array(Array::Type type, bool context_flag, size_t init_size, T value, - Allocator& allocator) -{ - REALM_ASSERT(type == Array::type_Normal); - REALM_ASSERT(!context_flag); - MemRef mem = create_array(init_size, allocator); - if (init_size) { - // GCC 7.x emits a false-positive strict aliasing warning for this code. Suppress it, since it - // clutters up the build output. See for details. - REALM_DIAG_PUSH(); - REALM_DIAG(ignored "-Wstrict-aliasing"); - - BasicArray tmp(allocator); - tmp.init_from_mem(mem); - T* p = reinterpret_cast(tmp.m_data); - T* end = p + init_size; - while (p < end) { - *p++ = value; - } - - REALM_DIAG_POP(); - } - return mem; -} - - -template -inline void BasicArray::create(Array::Type type, bool context_flag) -{ - REALM_ASSERT(type == Array::type_Normal); - REALM_ASSERT(!context_flag); - size_t length = 0; - MemRef mem = create_array(length, get_alloc()); // Throws - init_from_mem(mem); -} - - -template -MemRef BasicArray::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const -{ - REALM_ASSERT(is_attached()); - - // FIXME: This can be optimized as a single contiguous copy - // operation. - BasicArray array_slice(target_alloc); - _impl::ShallowArrayDestroyGuard dg(&array_slice); - array_slice.create(); // Throws - size_t begin = offset; - size_t end = offset + slice_size; - for (size_t i = begin; i != end; ++i) { - T value = get(i); - array_slice.add(value); // Throws - } - dg.release(); - return array_slice.get_mem(); -} - -template -MemRef BasicArray::slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const -{ - // BasicArray never contains refs, so never has children. - return slice(offset, slice_size, target_alloc); -} - - -template -inline void BasicArray::add(T value) -{ - insert(m_size, value); -} - - -template -inline T BasicArray::get(size_t ndx) const noexcept -{ - return *(reinterpret_cast(m_data) + ndx); -} - - -template -inline bool BasicArray::is_null(size_t ndx) const noexcept -{ - // FIXME: This assumes BasicArray will only ever be instantiated for float-like T. - static_assert(realm::is_any::value, "T can only be float or double"); - auto x = get(ndx); - return null::is_null_float(x); -} - - -template -inline T BasicArray::get(const char* header, size_t ndx) noexcept -{ - const char* data = get_data_from_header(header); - // This casting assumes that T can be aliged on an 8-bype - // boundary (since data is aligned on an 8-byte boundary.) - return *(reinterpret_cast(data) + ndx); -} - - -template -inline void BasicArray::set(size_t ndx, T value) -{ - REALM_ASSERT_3(ndx, <, m_size); - if (get(ndx) == value) - return; - - // Check if we need to copy before modifying - copy_on_write(); // Throws - - // Set the value - T* data = reinterpret_cast(m_data) + ndx; - *data = value; -} - -template -inline void BasicArray::set_null(size_t ndx) -{ - // FIXME: This assumes BasicArray will only ever be instantiated for float-like T. - set(ndx, null::get_null_float()); -} - -template -void BasicArray::insert(size_t ndx, T value) -{ - REALM_ASSERT_3(ndx, <=, m_size); - - // Check if we need to copy before modifying - copy_on_write(); // Throws - - // Make room for the new value - alloc(m_size + 1, m_width); // Throws - - // Move values below insertion - if (ndx != m_size) { - char* src_begin = m_data + ndx * m_width; - char* src_end = m_data + m_size * m_width; - char* dst_end = src_end + m_width; - std::copy_backward(src_begin, src_end, dst_end); - } - - // Set the value - T* data = reinterpret_cast(m_data) + ndx; - *data = value; - - ++m_size; -} - -template -void BasicArray::erase(size_t ndx) -{ - REALM_ASSERT_3(ndx, <, m_size); - - // Check if we need to copy before modifying - copy_on_write(); // Throws - - // move data under deletion up - if (ndx < m_size - 1) { - char* dst_begin = m_data + ndx * m_width; - const char* src_begin = dst_begin + m_width; - const char* src_end = m_data + m_size * m_width; - realm::safe_copy_n(src_begin, src_end - src_begin, dst_begin); - } - - // Update size (also in header) - --m_size; - set_header_size(m_size); -} - -template -void BasicArray::truncate(size_t to_size) -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT_3(to_size, <=, m_size); - - copy_on_write(); // Throws - - // Update size in accessor and in header. This leaves the capacity - // unchanged. - m_size = to_size; - set_header_size(to_size); -} - -template -inline void BasicArray::clear() -{ - truncate(0); // Throws -} - -template -bool BasicArray::compare(const BasicArray& a) const -{ - size_t n = size(); - if (a.size() != n) - return false; - const T* data_1 = reinterpret_cast(m_data); - const T* data_2 = reinterpret_cast(a.m_data); - return realm::safe_equal(data_1, data_1 + n, data_2); -} - - -template -size_t BasicArray::calc_byte_len(size_t for_size, size_t) const -{ - // FIXME: Consider calling `calc_aligned_byte_size(size)` - // instead. Note however, that calc_byte_len() is supposed to return - // the unaligned byte size. It is probably the case that no harm - // is done by returning the aligned version, and most callers of - // calc_byte_len() will actually benefit if calc_byte_len() was - // changed to always return the aligned byte size. - return header_size + for_size * sizeof(T); -} - -template -size_t BasicArray::calc_item_count(size_t bytes, size_t) const noexcept -{ - size_t bytes_without_header = bytes - header_size; - return bytes_without_header / sizeof(T); -} - -template -size_t BasicArray::find(T value, size_t begin, size_t end) const -{ - if (end == npos) - end = m_size; - REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); - const T* data = reinterpret_cast(m_data); - const T* i = std::find(data + begin, data + end, value); - return i == data + end ? not_found : size_t(i - data); -} - -template -inline size_t BasicArray::find_first(T value, size_t begin, size_t end) const -{ - return this->find(value, begin, end); -} - -template -void BasicArray::find_all(IntegerColumn* result, T value, size_t add_offset, size_t begin, size_t end) const -{ - size_t first = begin - 1; - for (;;) { - first = this->find(value, first + 1, end); - if (first == not_found) - break; - - Array::add_to_column(result, first + add_offset); - } -} - -template -size_t BasicArray::count(T value, size_t begin, size_t end) const -{ - if (end == npos) - end = m_size; - REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); - const T* data = reinterpret_cast(m_data); - return std::count(data + begin, data + end, value); -} - -#if 0 -// currently unused -template -double BasicArray::sum(size_t begin, size_t end) const -{ - if (end == npos) - end = m_size; - REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); - const T* data = reinterpret_cast(m_data); - return std::accumulate(data + begin, data + end, double(0)); -} -#endif - -template -template -bool BasicArray::minmax(T& result, size_t begin, size_t end) const -{ - if (end == npos) - end = m_size; - if (m_size == 0) - return false; - REALM_ASSERT(begin < m_size && end <= m_size && begin < end); - - T m = get(begin); - ++begin; - for (; begin < end; ++begin) { - T val = get(begin); - if (find_max ? val > m : val < m) - m = val; - } - result = m; - return true; -} - -template -bool BasicArray::maximum(T& result, size_t begin, size_t end) const -{ - return minmax(result, begin, end); -} - -template -bool BasicArray::minimum(T& result, size_t begin, size_t end) const -{ - return minmax(result, begin, end); -} - - -template -ref_type BasicArray::bptree_leaf_insert(size_t ndx, T value, TreeInsertBase& state) -{ - size_t leaf_size = size(); - REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE); - if (leaf_size < ndx) - ndx = leaf_size; - if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { - insert(ndx, value); - return 0; // Leaf was not split - } - - // Split leaf node - BasicArray new_leaf(get_alloc()); - new_leaf.create(); // Throws - if (ndx == leaf_size) { - new_leaf.add(value); - state.m_split_offset = ndx; - } - else { - // FIXME: Could be optimized by first resizing the target - // array, then copy elements with std::copy(). - for (size_t i = ndx; i != leaf_size; ++i) - new_leaf.add(get(i)); - truncate(ndx); - add(value); - state.m_split_offset = ndx + 1; - } - state.m_split_size = leaf_size + 1; - return new_leaf.get_ref(); -} - -template -inline size_t BasicArray::lower_bound(T value) const noexcept -{ - const T* begin = reinterpret_cast(m_data); - const T* end = begin + size(); - return std::lower_bound(begin, end, value) - begin; -} - -template -inline size_t BasicArray::upper_bound(T value) const noexcept -{ - const T* begin = reinterpret_cast(m_data); - const T* end = begin + size(); - return std::upper_bound(begin, end, value) - begin; -} - -template -inline size_t BasicArray::calc_aligned_byte_size(size_t size) -{ - size_t max = std::numeric_limits::max(); - size_t max_2 = max & ~size_t(7); // Allow for upwards 8-byte alignment - if (size > (max_2 - header_size) / sizeof(T)) - throw util::overflow_error("Byte size overflow"); - size_t byte_size = header_size + size * sizeof(T); - REALM_ASSERT_3(byte_size, >, 0); - size_t aligned_byte_size = ((byte_size - 1) | 7) + 1; // 8-byte alignment - return aligned_byte_size; -} - - -#ifdef REALM_DEBUG - -// LCOV_EXCL_START -template -void BasicArray::to_dot(std::ostream& out, StringData title) const -{ - ref_type ref = get_ref(); - if (title.size() != 0) { - out << "subgraph cluster_" << ref << " {\n"; - out << " label = \"" << title << "\";\n"; - out << " color = white;\n"; - } - - out << "n" << std::hex << ref << std::dec << "[shape=none,label=<"; - out << "
\n"; - - // Header - out << "\n"; - - // Values - size_t n = m_size; - for (size_t i = 0; i != n; ++i) - out << "\n"; - - out << "
"; - out << "0x" << std::hex << ref << std::dec << "
"; - out << "
" << get(i) << "
>];\n"; - - if (title.size() != 0) - out << "}\n"; - - to_dot_parent_edge(out); -} -// LCOV_EXCL_STOP - -#endif // REALM_DEBUG - - -} // namespace realm - -#endif // REALM_ARRAY_BASIC_TPL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_binary.hpp b/Lesson14/Pods/Realm/include/core/realm/array_binary.hpp deleted file mode 100644 index 347c7be..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_binary.hpp +++ /dev/null @@ -1,259 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_BINARY_HPP -#define REALM_ARRAY_BINARY_HPP - -#include -#include -#include -#include - -namespace realm { - -/* -STORAGE FORMAT ---------------------------------------------------------------------------------------- -ArrayBinary stores binary elements using two ArrayInteger and one ArrayBlob. The ArrayBlob can only store one -single concecutive array of bytes (contrary to its 'Array' name that misleadingly indicates it could store multiple -elements). - -Assume we have the strings "a", "", "abc", null, "ab". Then the three arrays will contain: - -ArrayInteger m_offsets 1, 1, 5, 5, 6 -ArrayBlob m_blob aabcab -ArrayInteger m_nulls 0, 0, 0, 1, 0 // 1 indicates null, 0 indicates non-null - -So for each element the ArrayInteger, the ArrayInteger points into the ArrayBlob at the position of the first -byte of the next element. - -m_nulls is always present (except for old database files; see below), so any ArrayBinary is always nullable! -The nullable property (such as throwing exception upon set(null) on non-nullable column, etc) is handled on -column level only. - -DATABASE FILE VERSION CHANGES ---------------------------------------------------------------------------------------- -Old database files do not have any m_nulls array. To be backwardscompatible, many methods will have tests like -`if(Array::size() == 3)` and have a backwards compatible code paths for these (e.g. avoid writing to m_nulls -in set(), etc). This way no file format upgrade is needed to support nulls for BinaryData. -*/ - -class ArrayBinary : public Array { -public: - explicit ArrayBinary(Allocator&) noexcept; - ~ArrayBinary() noexcept override - { - } - - // Disable copying, this is not allowed. - ArrayBinary& operator=(const ArrayBinary&) = delete; - ArrayBinary(const ArrayBinary&) = delete; - - /// Create a new empty binary array and attach this accessor to - /// it. This does not modify the parent reference information of - /// this accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(); - - // Old database files will not have the m_nulls array, so we need code paths for - // backwards compatibility for these cases. - bool legacy_array_type() const noexcept; - - //@{ - /// Overriding functions of Array - void init_from_ref(ref_type) noexcept; - void init_from_mem(MemRef) noexcept; - void init_from_parent() noexcept; - //@} - - bool is_empty() const noexcept; - size_t size() const noexcept; - - BinaryData get(size_t ndx) const noexcept; - size_t read(size_t ndx, size_t pos, char* buffer, size_t max_size) const noexcept; - - void add(BinaryData value, bool add_zero_term = false); - void set(size_t ndx, BinaryData value, bool add_zero_term = false); - void insert(size_t ndx, BinaryData value, bool add_zero_term = false); - void erase(size_t ndx); - void truncate(size_t new_size); - void clear(); - void destroy(); - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept; - - ref_type bptree_leaf_insert(size_t ndx, BinaryData, bool add_zero_term, TreeInsertBase& state); - - static size_t get_size_from_header(const char*, Allocator&) noexcept; - - /// Construct a binary array of the specified size and return just - /// the reference to the underlying memory. All elements will be - /// initialized to the binary value `defaults`, which can be either - /// null or zero-length non-null (value with size > 0 is not allowed as - /// initialization value). - static MemRef create_array(size_t size, Allocator&, BinaryData defaults); - - /// Construct a copy of the specified slice of this binary array - /// using the specified target allocator. - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - -#ifdef REALM_DEBUG - void to_dot(std::ostream&, bool is_strings, StringData title = StringData()) const; -#endif - bool update_from_parent(size_t old_baseline) noexcept; - -private: - ArrayInteger m_offsets; - ArrayBlob m_blob; - ArrayInteger m_nulls; -}; - - -// Implementation: - -inline ArrayBinary::ArrayBinary(Allocator& allocator) noexcept - : Array(allocator) - , m_offsets(allocator) - , m_blob(allocator) - , m_nulls(allocator) -{ - m_offsets.set_parent(this, 0); - m_blob.set_parent(this, 1); - m_nulls.set_parent(this, 2); -} - -inline void ArrayBinary::create() -{ - size_t init_size = 0; - BinaryData defaults = BinaryData{}; // This init value is ignored because size = 0 - MemRef mem = create_array(init_size, get_alloc(), defaults); // Throws - init_from_mem(mem); -} - -inline void ArrayBinary::init_from_ref(ref_type ref) noexcept -{ - REALM_ASSERT(ref); - char* header = get_alloc().translate(ref); - init_from_mem(MemRef(header, ref, m_alloc)); -} - -inline void ArrayBinary::init_from_parent() noexcept -{ - ref_type ref = get_ref_from_parent(); - init_from_ref(ref); -} - -inline bool ArrayBinary::is_empty() const noexcept -{ - return m_offsets.is_empty(); -} - -// Old database files will not have the m_nulls array, so we need code paths for -// backwards compatibility for these cases. We can test if m_nulls exists by looking -// at number of references in this ArrayBinary. -inline bool ArrayBinary::legacy_array_type() const noexcept -{ - if (Array::size() == 3) - return false; // New database file - else if (Array::size() == 2) - return true; // Old database file - else - REALM_ASSERT(false); // Should never happen - return false; -} - -inline size_t ArrayBinary::size() const noexcept -{ - return m_offsets.size(); -} - -inline BinaryData ArrayBinary::get(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_offsets.size()); - - if (!legacy_array_type() && m_nulls.get(ndx)) { - return BinaryData(); - } - else { - size_t begin = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0; - size_t end = to_size_t(m_offsets.get(ndx)); - - BinaryData bd = BinaryData(m_blob.get(begin), end - begin); - // Old database file (non-nullable column should never return null) - REALM_ASSERT(!bd.is_null()); - return bd; - } -} - -inline void ArrayBinary::truncate(size_t new_size) -{ - REALM_ASSERT_3(new_size, <, m_offsets.size()); - - size_t sz = new_size ? to_size_t(m_offsets.get(new_size - 1)) : 0; - - m_offsets.truncate(new_size); - m_blob.truncate(sz); - if (!legacy_array_type()) - m_nulls.truncate(new_size); -} - -inline void ArrayBinary::clear() -{ - m_blob.clear(); - m_offsets.clear(); - if (!legacy_array_type()) - m_nulls.clear(); -} - -inline void ArrayBinary::destroy() -{ - m_blob.destroy(); - m_offsets.destroy(); - if (!legacy_array_type()) - m_nulls.destroy(); - Array::destroy(); -} - -inline size_t ArrayBinary::get_size_from_header(const char* header, Allocator& alloc) noexcept -{ - ref_type offsets_ref = to_ref(Array::get(header, 0)); - const char* offsets_header = alloc.translate(offsets_ref); - return Array::get_size_from_header(offsets_header); -} - -inline bool ArrayBinary::update_from_parent(size_t old_baseline) noexcept -{ - bool res = Array::update_from_parent(old_baseline); - if (res) { - m_blob.update_from_parent(old_baseline); - m_offsets.update_from_parent(old_baseline); - if (!legacy_array_type()) - m_nulls.update_from_parent(old_baseline); - } - return res; -} - -} // namespace realm - -#endif // REALM_ARRAY_BINARY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_blob.hpp b/Lesson14/Pods/Realm/include/core/realm/array_blob.hpp deleted file mode 100644 index 556d40a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_blob.hpp +++ /dev/null @@ -1,146 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_BLOB_HPP -#define REALM_ARRAY_BLOB_HPP - -#include - -namespace realm { - - -class ArrayBlob : public Array { -public: - static constexpr size_t max_binary_size = 0xFFFFF8 - Array::header_size; - - explicit ArrayBlob(Allocator&) noexcept; - ~ArrayBlob() noexcept override - { - } - - // Disable copying, this is not allowed. - ArrayBlob& operator=(const ArrayBlob&) = delete; - ArrayBlob(const ArrayBlob&) = delete; - - const char* get(size_t index) const noexcept; - BinaryData get_at(size_t& pos) const noexcept; - bool is_null(size_t index) const noexcept; - ref_type add(const char* data, size_t data_size, bool add_zero_term = false); - void insert(size_t pos, const char* data, size_t data_size, bool add_zero_term = false); - ref_type replace(size_t begin, size_t end, const char* data, size_t data_size, bool add_zero_term = false); - void erase(size_t begin, size_t end); - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static const char* get(const char* header, size_t index) noexcept; - - /// Create a new empty blob (binary) array and attach this - /// accessor to it. This does not modify the parent reference - /// information of this accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(); - - /// Construct a blob of the specified size and return just the - /// reference to the underlying memory. All bytes will be - /// initialized to zero. - static MemRef create_array(size_t init_size, Allocator&); - -#ifdef REALM_DEBUG - void verify() const; - void to_dot(std::ostream&, StringData title = StringData()) const; -#endif - -private: - size_t calc_byte_len(size_t for_size, size_t width) const override; - size_t calc_item_count(size_t bytes, size_t width) const noexcept override; -}; - - -// Implementation: - -// Creates new array (but invalid, call init_from_ref() to init) -inline ArrayBlob::ArrayBlob(Allocator& allocator) noexcept - : Array(allocator) -{ -} - -inline bool ArrayBlob::is_null(size_t index) const noexcept -{ - return (get(index) == nullptr); -} - -inline const char* ArrayBlob::get(size_t index) const noexcept -{ - return m_data + index; -} - -inline ref_type ArrayBlob::add(const char* data, size_t data_size, bool add_zero_term) -{ - return replace(m_size, m_size, data, data_size, add_zero_term); -} - -inline void ArrayBlob::insert(size_t pos, const char* data, size_t data_size, bool add_zero_term) -{ - replace(pos, pos, data, data_size, add_zero_term); -} - -inline void ArrayBlob::erase(size_t begin, size_t end) -{ - const char* data = nullptr; - size_t data_size = 0; - replace(begin, end, data, data_size); -} - -inline const char* ArrayBlob::get(const char* header, size_t pos) noexcept -{ - const char* data = get_data_from_header(header); - return data + pos; -} - -inline void ArrayBlob::create() -{ - size_t init_size = 0; - MemRef mem = create_array(init_size, get_alloc()); // Throws - init_from_mem(mem); -} - -inline MemRef ArrayBlob::create_array(size_t init_size, Allocator& allocator) -{ - bool context_flag = false; - int_fast64_t value = 0; - return Array::create(type_Normal, context_flag, wtype_Ignore, init_size, value, allocator); // Throws -} - -inline size_t ArrayBlob::calc_byte_len(size_t for_size, size_t) const -{ - return header_size + for_size; -} - -inline size_t ArrayBlob::calc_item_count(size_t bytes, size_t) const noexcept -{ - return bytes - header_size; -} - - -} // namespace realm - -#endif // REALM_ARRAY_BLOB_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_blobs_big.hpp b/Lesson14/Pods/Realm/include/core/realm/array_blobs_big.hpp deleted file mode 100644 index cc793fb..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_blobs_big.hpp +++ /dev/null @@ -1,222 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_BIG_BLOBS_HPP -#define REALM_ARRAY_BIG_BLOBS_HPP - -#include - -namespace realm { - - -class ArrayBigBlobs : public Array { -public: - typedef BinaryData value_type; - - explicit ArrayBigBlobs(Allocator&, bool nullable) noexcept; - - // Disable copying, this is not allowed. - ArrayBigBlobs& operator=(const ArrayBigBlobs&) = delete; - ArrayBigBlobs(const ArrayBigBlobs&) = delete; - - BinaryData get(size_t ndx) const noexcept; - BinaryData get_at(size_t ndx, size_t& pos) const noexcept; - void set(size_t ndx, BinaryData value, bool add_zero_term = false); - void add(BinaryData value, bool add_zero_term = false); - void insert(size_t ndx, BinaryData value, bool add_zero_term = false); - void erase(size_t ndx); - void truncate(size_t new_size); - void clear(); - void destroy(); - - size_t count(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept; - size_t find_first(BinaryData value, bool is_string = false, size_t begin = 0, size_t end = npos) const noexcept; - void find_all(IntegerColumn& result, BinaryData value, bool is_string = false, size_t add_offset = 0, - size_t begin = 0, size_t end = npos); - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept; - - ref_type bptree_leaf_insert(size_t ndx, BinaryData, bool add_zero_term, TreeInsertBase& state); - - //@{ - /// Those that return a string, discard the terminating zero from - /// the stored value. Those that accept a string argument, add a - /// terminating zero before storing the value. - StringData get_string(size_t ndx) const noexcept; - void add_string(StringData value); - void set_string(size_t ndx, StringData value); - void insert_string(size_t ndx, StringData value); - static StringData get_string(const char* header, size_t ndx, Allocator&, bool nullable) noexcept; - ref_type bptree_leaf_insert_string(size_t ndx, StringData, TreeInsertBase& state); - //@} - - /// Create a new empty big blobs array and attach this accessor to - /// it. This does not modify the parent reference information of - /// this accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(); - - /// Construct a copy of the specified slice of this big blobs - /// array using the specified target allocator. - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - -#ifdef REALM_DEBUG - void verify() const; - void to_dot(std::ostream&, bool is_strings, StringData title = StringData()) const; -#endif - -private: - bool m_nullable; -}; - - -// Implementation: - -inline ArrayBigBlobs::ArrayBigBlobs(Allocator& allocator, bool nullable) noexcept - : Array(allocator) - , m_nullable(nullable) -{ -} - -inline BinaryData ArrayBigBlobs::get(size_t ndx) const noexcept -{ - ref_type ref = get_as_ref(ndx); - if (ref == 0) - return {}; // realm::null(); - - const char* blob_header = get_alloc().translate(ref); - if (!get_context_flag_from_header(blob_header)) { - const char* value = ArrayBlob::get(blob_header, 0); - size_t sz = get_size_from_header(blob_header); - return BinaryData(value, sz); - } - return {}; -} - -inline BinaryData ArrayBigBlobs::get(const char* header, size_t ndx, Allocator& alloc) noexcept -{ - ref_type blob_ref = to_ref(Array::get(header, ndx)); - if (blob_ref == 0) - return {}; - - const char* blob_header = alloc.translate(blob_ref); - if (!get_context_flag_from_header(blob_header)) { - const char* blob_data = Array::get_data_from_header(blob_header); - size_t sz = Array::get_size_from_header(blob_header); - return BinaryData(blob_data, sz); - } - return {}; -} - -inline void ArrayBigBlobs::erase(size_t ndx) -{ - ref_type blob_ref = Array::get_as_ref(ndx); - if (blob_ref != 0) { // nothing to destroy if null - Array::destroy_deep(blob_ref, get_alloc()); // Deep - } - Array::erase(ndx); -} - -inline void ArrayBigBlobs::truncate(size_t new_size) -{ - Array::truncate_and_destroy_children(new_size); -} - -inline void ArrayBigBlobs::clear() -{ - Array::clear_and_destroy_children(); -} - -inline void ArrayBigBlobs::destroy() -{ - Array::destroy_deep(); -} - -inline StringData ArrayBigBlobs::get_string(size_t ndx) const noexcept -{ - BinaryData bin = get(ndx); - if (bin.is_null()) - return realm::null(); - else - return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero -} - -inline void ArrayBigBlobs::set_string(size_t ndx, StringData value) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - BinaryData bin(value.data(), value.size()); - bool add_zero_term = true; - set(ndx, bin, add_zero_term); -} - -inline void ArrayBigBlobs::add_string(StringData value) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - BinaryData bin(value.data(), value.size()); - bool add_zero_term = true; - add(bin, add_zero_term); -} - -inline void ArrayBigBlobs::insert_string(size_t ndx, StringData value) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - BinaryData bin(value.data(), value.size()); - bool add_zero_term = true; - insert(ndx, bin, add_zero_term); -} - -inline StringData ArrayBigBlobs::get_string(const char* header, size_t ndx, Allocator& alloc, bool nullable) noexcept -{ - static_cast(nullable); - BinaryData bin = get(header, ndx, alloc); - REALM_ASSERT_DEBUG(!(!nullable && bin.is_null())); - if (bin.is_null()) - return realm::null(); - else - return StringData(bin.data(), bin.size() - 1); // Do not include terminating zero -} - -inline ref_type ArrayBigBlobs::bptree_leaf_insert_string(size_t ndx, StringData value, TreeInsertBase& state) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - BinaryData bin(value.data(), value.size()); - bool add_zero_term = true; - return bptree_leaf_insert(ndx, bin, add_zero_term, state); -} - -inline void ArrayBigBlobs::create() -{ - bool context_flag = true; - Array::create(type_HasRefs, context_flag); // Throws -} - -inline MemRef ArrayBigBlobs::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const -{ - return slice_and_clone_children(offset, slice_size, target_alloc); -} - - -} // namespace realm - -#endif // REALM_ARRAY_BIG_BLOBS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_direct.hpp b/Lesson14/Pods/Realm/include/core/realm/array_direct.hpp deleted file mode 100644 index e337392..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_direct.hpp +++ /dev/null @@ -1,372 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_DIRECT_HPP -#define REALM_ARRAY_DIRECT_HPP - -#include -#include - -using namespace realm::util; - -// clang-format off -/* wid == 16/32 likely when accessing offsets in B tree */ -#define REALM_TEMPEX(fun, wid, arg) \ - if (wid == 16) {fun<16> arg;} \ - else if (wid == 32) {fun<32> arg;} \ - else if (wid == 0) {fun<0> arg;} \ - else if (wid == 1) {fun<1> arg;} \ - else if (wid == 2) {fun<2> arg;} \ - else if (wid == 4) {fun<4> arg;} \ - else if (wid == 8) {fun<8> arg;} \ - else if (wid == 64) {fun<64> arg;} \ - else {REALM_ASSERT_DEBUG(false); fun<0> arg;} - -#define REALM_TEMPEX2(fun, targ, wid, arg) \ - if (wid == 16) {fun arg;} \ - else if (wid == 32) {fun arg;} \ - else if (wid == 0) {fun arg;} \ - else if (wid == 1) {fun arg;} \ - else if (wid == 2) {fun arg;} \ - else if (wid == 4) {fun arg;} \ - else if (wid == 8) {fun arg;} \ - else if (wid == 64) {fun arg;} \ - else {REALM_ASSERT_DEBUG(false); fun arg;} - -#define REALM_TEMPEX3(fun, targ1, targ2, wid, arg) \ - if (wid == 16) {fun arg;} \ - else if (wid == 32) {fun arg;} \ - else if (wid == 0) {fun arg;} \ - else if (wid == 1) {fun arg;} \ - else if (wid == 2) {fun arg;} \ - else if (wid == 4) {fun arg;} \ - else if (wid == 8) {fun arg;} \ - else if (wid == 64) {fun arg;} \ - else {REALM_ASSERT_DEBUG(false); fun arg;} - -#define REALM_TEMPEX4(fun, targ1, targ2, wid, targ3, arg) \ - if (wid == 16) {fun arg;} \ - else if (wid == 32) {fun arg;} \ - else if (wid == 0) {fun arg;} \ - else if (wid == 1) {fun arg;} \ - else if (wid == 2) {fun arg;} \ - else if (wid == 4) {fun arg;} \ - else if (wid == 8) {fun arg;} \ - else if (wid == 64) {fun arg;} \ - else {REALM_ASSERT_DEBUG(false); fun arg;} - -#define REALM_TEMPEX5(fun, targ1, targ2, targ3, targ4, wid, arg) \ - if (wid == 16) {fun arg;} \ - else if (wid == 32) {fun arg;} \ - else if (wid == 0) {fun arg;} \ - else if (wid == 1) {fun arg;} \ - else if (wid == 2) {fun arg;} \ - else if (wid == 4) {fun arg;} \ - else if (wid == 8) {fun arg;} \ - else if (wid == 64) {fun arg;} \ - else {REALM_ASSERT_DEBUG(false); fun arg;} -// clang-format on - -namespace realm { - -// Direct access methods - -template -void set_direct(char* data, size_t ndx, int_fast64_t value) noexcept -{ - if (width == 0) { - REALM_ASSERT_DEBUG(value == 0); - return; - } - else if (width == 1) { - REALM_ASSERT_DEBUG(0 <= value && value <= 0x01); - size_t byte_ndx = ndx / 8; - size_t bit_ndx = ndx % 8; - typedef unsigned char uchar; - uchar* p = reinterpret_cast(data) + byte_ndx; - *p = uchar((*p & ~(0x01 << bit_ndx)) | (int(value) & 0x01) << bit_ndx); - } - else if (width == 2) { - REALM_ASSERT_DEBUG(0 <= value && value <= 0x03); - size_t byte_ndx = ndx / 4; - size_t bit_ndx = ndx % 4 * 2; - typedef unsigned char uchar; - uchar* p = reinterpret_cast(data) + byte_ndx; - *p = uchar((*p & ~(0x03 << bit_ndx)) | (int(value) & 0x03) << bit_ndx); - } - else if (width == 4) { - REALM_ASSERT_DEBUG(0 <= value && value <= 0x0F); - size_t byte_ndx = ndx / 2; - size_t bit_ndx = ndx % 2 * 4; - typedef unsigned char uchar; - uchar* p = reinterpret_cast(data) + byte_ndx; - *p = uchar((*p & ~(0x0F << bit_ndx)) | (int(value) & 0x0F) << bit_ndx); - } - else if (width == 8) { - REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && - value <= std::numeric_limits::max()); - *(reinterpret_cast(data) + ndx) = int8_t(value); - } - else if (width == 16) { - REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && - value <= std::numeric_limits::max()); - *(reinterpret_cast(data) + ndx) = int16_t(value); - } - else if (width == 32) { - REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && - value <= std::numeric_limits::max()); - *(reinterpret_cast(data) + ndx) = int32_t(value); - } - else if (width == 64) { - REALM_ASSERT_DEBUG(std::numeric_limits::min() <= value && - value <= std::numeric_limits::max()); - *(reinterpret_cast(data) + ndx) = int64_t(value); - } - else { - REALM_ASSERT_DEBUG(false); - } -} - -template -void fill_direct(char* data, size_t begin, size_t end, int_fast64_t value) noexcept -{ - for (size_t i = begin; i != end; ++i) - set_direct(data, i, value); -} - -template -int64_t get_direct(const char* data, size_t ndx) noexcept -{ - if (w == 0) { - return 0; - } - if (w == 1) { - size_t offset = ndx >> 3; - return (data[offset] >> (ndx & 7)) & 0x01; - } - if (w == 2) { - size_t offset = ndx >> 2; - return (data[offset] >> ((ndx & 3) << 1)) & 0x03; - } - if (w == 4) { - size_t offset = ndx >> 1; - return (data[offset] >> ((ndx & 1) << 2)) & 0x0F; - } - if (w == 8) { - return *reinterpret_cast(data + ndx); - } - if (w == 16) { - size_t offset = ndx * 2; - return *reinterpret_cast(data + offset); - } - if (w == 32) { - size_t offset = ndx * 4; - return *reinterpret_cast(data + offset); - } - if (w == 64) { - size_t offset = ndx * 8; - return *reinterpret_cast(data + offset); - } - REALM_ASSERT_DEBUG(false); - return int64_t(-1); -} - -inline int64_t get_direct(const char* data, size_t width, size_t ndx) noexcept -{ - REALM_TEMPEX(return get_direct, width, (data, ndx)); -} - - -template -inline std::pair get_two(const char* data, size_t ndx) noexcept -{ - return std::make_pair(to_size_t(get_direct(data, ndx + 0)), to_size_t(get_direct(data, ndx + 1))); -} - -inline std::pair get_two(const char* data, size_t width, size_t ndx) noexcept -{ - REALM_TEMPEX(return get_two, width, (data, ndx)); -} - - -template -inline void get_three(const char* data, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept -{ - v0 = to_ref(get_direct(data, ndx + 0)); - v1 = to_ref(get_direct(data, ndx + 1)); - v2 = to_ref(get_direct(data, ndx + 2)); -} - -inline void get_three(const char* data, size_t width, size_t ndx, ref_type& v0, ref_type& v1, ref_type& v2) noexcept -{ - REALM_TEMPEX(get_three, width, (data, ndx, v0, v1, v2)); -} - - -// Lower/upper bound in sorted sequence -// ------------------------------------ -// -// 3 3 3 4 4 4 5 6 7 9 9 9 -// ^ ^ ^ ^ ^ -// | | | | | -// | | | | -- Lower and upper bound of 15 -// | | | | -// | | | -- Lower and upper bound of 8 -// | | | -// | | -- Upper bound of 4 -// | | -// | -- Lower bound of 4 -// | -// -- Lower and upper bound of 1 -// -// These functions are semantically identical to std::lower_bound() and -// std::upper_bound(). -// -// We currently use binary search. See for example -// http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary. -template -inline size_t lower_bound(const char* data, size_t size, int64_t value) noexcept -{ - // The binary search used here is carefully optimized. Key trick is to use a single - // loop controlling variable (size) instead of high/low pair, and to keep updates - // to size done inside the loop independent of comparisons. Further key to speed - // is to avoid branching inside the loop, using conditional moves instead. This - // provides robust performance for random searches, though predictable searches - // might be slightly faster if we used branches instead. The loop unrolling yields - // a final 5-20% speedup depending on circumstances. - - size_t low = 0; - - while (size >= 8) { - // The following code (at X, Y and Z) is 3 times manually unrolled instances of (A) below. - // These code blocks must be kept in sync. Meassurements indicate 3 times unrolling to give - // the best performance. See (A) for comments on the loop body. - // (X) - size_t half = size / 2; - size_t other_half = size - half; - size_t probe = low + half; - size_t other_low = low + other_half; - int64_t v = get_direct(data, probe); - size = half; - low = (v < value) ? other_low : low; - - // (Y) - half = size / 2; - other_half = size - half; - probe = low + half; - other_low = low + other_half; - v = get_direct(data, probe); - size = half; - low = (v < value) ? other_low : low; - - // (Z) - half = size / 2; - other_half = size - half; - probe = low + half; - other_low = low + other_half; - v = get_direct(data, probe); - size = half; - low = (v < value) ? other_low : low; - } - while (size > 0) { - // (A) - // To understand the idea in this code, please note that - // for performance, computation of size for the next iteration - // MUST be INDEPENDENT of the conditional. This allows the - // processor to unroll the loop as fast as possible, and it - // minimizes the length of dependence chains leading up to branches. - // Making the unfolding of the loop independent of the data being - // searched, also minimizes the delays incurred by branch - // mispredictions, because they can be determined earlier - // and the speculation corrected earlier. - - // Counterintuitive: - // To make size independent of data, we cannot always split the - // range at the theoretical optimal point. When we determine that - // the key is larger than the probe at some index K, and prepare - // to search the upper part of the range, you would normally start - // the search at the next index, K+1, to get the shortest range. - // We can only do this when splitting a range with odd number of entries. - // If there is an even number of entries we search from K instead of K+1. - // This potentially leads to redundant comparisons, but in practice we - // gain more performance by making the changes to size predictable. - - // if size is even, half and other_half are the same. - // if size is odd, half is one less than other_half. - size_t half = size / 2; - size_t other_half = size - half; - size_t probe = low + half; - size_t other_low = low + other_half; - int64_t v = get_direct(data, probe); - size = half; - // for max performance, the line below should compile into a conditional - // move instruction. Not all compilers do this. To maximize chance - // of succes, no computation should be done in the branches of the - // conditional. - low = (v < value) ? other_low : low; - }; - - return low; -} - -// See lower_bound() -template -inline size_t upper_bound(const char* data, size_t size, int64_t value) noexcept -{ - size_t low = 0; - while (size >= 8) { - size_t half = size / 2; - size_t other_half = size - half; - size_t probe = low + half; - size_t other_low = low + other_half; - int64_t v = get_direct(data, probe); - size = half; - low = (value >= v) ? other_low : low; - - half = size / 2; - other_half = size - half; - probe = low + half; - other_low = low + other_half; - v = get_direct(data, probe); - size = half; - low = (value >= v) ? other_low : low; - - half = size / 2; - other_half = size - half; - probe = low + half; - other_low = low + other_half; - v = get_direct(data, probe); - size = half; - low = (value >= v) ? other_low : low; - } - - while (size > 0) { - size_t half = size / 2; - size_t other_half = size - half; - size_t probe = low + half; - size_t other_low = low + other_half; - int64_t v = get_direct(data, probe); - size = half; - low = (value >= v) ? other_low : low; - }; - - return low; -} -} - -#endif /* ARRAY_TPL_HPP_ */ diff --git a/Lesson14/Pods/Realm/include/core/realm/array_integer.hpp b/Lesson14/Pods/Realm/include/core/realm/array_integer.hpp deleted file mode 100644 index e460c53..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_integer.hpp +++ /dev/null @@ -1,629 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_INTEGER_HPP -#define REALM_ARRAY_INTEGER_HPP - -#include -#include -#include - -namespace realm { - -class ArrayInteger : public Array { -public: - typedef int64_t value_type; - - explicit ArrayInteger(Allocator&) noexcept; - ~ArrayInteger() noexcept override - { - } - - // Disable copying, this is not allowed. - ArrayInteger& operator=(const ArrayInteger&) = delete; - ArrayInteger(const ArrayInteger&) = delete; - - void create(Type type = type_Normal, bool context_flag = false); - - void add(int64_t value); - void set(size_t ndx, int64_t value); - void set_uint(size_t ndx, uint_fast64_t value) noexcept; - int64_t get(size_t ndx) const noexcept; - uint64_t get_uint(size_t ndx) const noexcept; - static int64_t get(const char* header, size_t ndx) noexcept; - bool compare(const ArrayInteger& a) const noexcept; - - /// Add \a diff to the element at the specified index. - void adjust(size_t ndx, int_fast64_t diff); - - /// Add \a diff to all the elements in the specified index range. - void adjust(size_t begin, size_t end, int_fast64_t diff); - - /// Add signed \a diff to all elements that are greater than, or equal to \a - /// limit. - void adjust_ge(int_fast64_t limit, int_fast64_t diff); - - int64_t operator[](size_t ndx) const noexcept - { - return get(ndx); - } - int64_t front() const noexcept; - int64_t back() const noexcept; - - size_t lower_bound(int64_t value) const noexcept; - size_t upper_bound(int64_t value) const noexcept; - - std::vector to_vector() const; - -private: - template - bool minmax(size_t from, size_t to, uint64_t maxdiff, int64_t* min, int64_t* max) const; -}; - -class ArrayIntNull : public Array { -public: - using value_type = util::Optional; - - explicit ArrayIntNull(Allocator&) noexcept; - ~ArrayIntNull() noexcept override; - - /// Construct an array of the specified type and size, and return just the - /// reference to the underlying memory. All elements will be initialized to - /// the specified value. - static MemRef create_array(Type, bool context_flag, size_t size, value_type value, Allocator&); - void create(Type = type_Normal, bool context_flag = false); - - void init_from_ref(ref_type) noexcept; - void init_from_mem(MemRef) noexcept; - void init_from_parent() noexcept; - - size_t size() const noexcept; - bool is_empty() const noexcept; - - void insert(size_t ndx, value_type value); - void add(value_type value); - void set(size_t ndx, value_type value) noexcept; - value_type get(size_t ndx) const noexcept; - static value_type get(const char* header, size_t ndx) noexcept; - void get_chunk(size_t ndx, value_type res[8]) const noexcept; - void set_null(size_t ndx) noexcept; - bool is_null(size_t ndx) const noexcept; - int64_t null_value() const noexcept; - - value_type operator[](size_t ndx) const noexcept; - value_type front() const noexcept; - value_type back() const noexcept; - void erase(size_t ndx); - void erase(size_t begin, size_t end); - void truncate(size_t size); - void clear(); - void set_all_to_zero(); - - void move(size_t begin, size_t end, size_t dest_begin); - void move_backward(size_t begin, size_t end, size_t dest_end); - - size_t lower_bound(int64_t value) const noexcept; - size_t upper_bound(int64_t value) const noexcept; - - int64_t sum(size_t start = 0, size_t end = npos) const; - size_t count(int64_t value) const noexcept; - bool maximum(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; - bool minimum(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; - - bool find(int cond, Action action, value_type value, size_t start, size_t end, size_t baseindex, - QueryState* state) const; - - template - bool find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - // This is the one installed into the m_finder slots. - template - bool find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const; - - template - bool find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - // Optimized implementation for release mode - template - bool find_optimized(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const; - - // Called for each search result - template - bool find_action(size_t index, value_type value, QueryState* state, Callback callback) const; - - template - bool find_action_pattern(size_t index, uint64_t pattern, QueryState* state, Callback callback) const; - - // Wrappers for backwards compatibility and for simple use without - // setting up state initialization etc - template - size_t find_first(value_type value, size_t start = 0, size_t end = npos) const; - - void find_all(IntegerColumn* result, value_type value, size_t col_offset = 0, size_t begin = 0, - size_t end = npos) const; - - - size_t find_first(value_type value, size_t begin = 0, size_t end = npos) const; - - - // Overwrite Array::bptree_leaf_insert to correctly split nodes. - ref_type bptree_leaf_insert(size_t ndx, value_type value, TreeInsertBase& state); - - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - - /// Construct a deep copy of the specified slice of this array using the - /// specified target allocator. Subarrays will be cloned. - MemRef slice_and_clone_children(size_t offset, size_t slice_size, Allocator& target_alloc) const; - -protected: - void avoid_null_collision(int64_t value); - -private: - template - bool minmax_helper(int64_t& result, size_t start = 0, size_t end = npos, size_t* return_ndx = nullptr) const; - - int_fast64_t choose_random_null(int64_t incoming) const; - void replace_nulls_with(int64_t new_null); - bool can_use_as_null(int64_t value) const; -}; - - -// Implementation: - -inline ArrayInteger::ArrayInteger(Allocator& allocator) noexcept - : Array(allocator) -{ - m_is_inner_bptree_node = false; -} - -inline void ArrayInteger::add(int64_t value) -{ - Array::add(value); -} - -inline int64_t ArrayInteger::get(size_t ndx) const noexcept -{ - return Array::get(ndx); -} - -inline int64_t ArrayInteger::get(const char* header, size_t ndx) noexcept -{ - return Array::get(header, ndx); -} - -inline void ArrayInteger::set(size_t ndx, int64_t value) -{ - Array::set(ndx, value); -} - -inline void ArrayInteger::set_uint(size_t ndx, uint_fast64_t value) noexcept -{ - // When a value of a signed type is converted to an unsigned type, the C++ - // standard guarantees that negative values are converted from the native - // representation to 2's complement, but the effect of conversions in the - // opposite direction is left unspecified by the - // standard. `realm::util::from_twos_compl()` is used here to perform the - // correct opposite unsigned-to-signed conversion, which reduces to a no-op - // when 2's complement is the native representation of negative values. - set(ndx, util::from_twos_compl(value)); -} - -inline bool ArrayInteger::compare(const ArrayInteger& a) const noexcept -{ - if (a.size() != size()) - return false; - - for (size_t i = 0; i < size(); ++i) { - if (get(i) != a.get(i)) - return false; - } - - return true; -} - -inline int64_t ArrayInteger::front() const noexcept -{ - return Array::front(); -} - -inline int64_t ArrayInteger::back() const noexcept -{ - return Array::back(); -} - -inline void ArrayInteger::adjust(size_t ndx, int_fast64_t diff) -{ - Array::adjust(ndx, diff); -} - -inline void ArrayInteger::adjust(size_t begin, size_t end, int_fast64_t diff) -{ - Array::adjust(begin, end, diff); -} - -inline void ArrayInteger::adjust_ge(int_fast64_t limit, int_fast64_t diff) -{ - Array::adjust_ge(limit, diff); -} - -inline size_t ArrayInteger::lower_bound(int64_t value) const noexcept -{ - return lower_bound_int(value); -} - -inline size_t ArrayInteger::upper_bound(int64_t value) const noexcept -{ - return upper_bound_int(value); -} - - -inline ArrayIntNull::ArrayIntNull(Allocator& allocator) noexcept - : Array(allocator) -{ -} - -inline ArrayIntNull::~ArrayIntNull() noexcept -{ -} - -inline void ArrayIntNull::create(Type type, bool context_flag) -{ - MemRef r = create_array(type, context_flag, 0, util::none, m_alloc); - init_from_mem(r); -} - - -inline size_t ArrayIntNull::size() const noexcept -{ - return Array::size() - 1; -} - -inline bool ArrayIntNull::is_empty() const noexcept -{ - return size() == 0; -} - -inline void ArrayIntNull::insert(size_t ndx, value_type value) -{ - if (value) { - avoid_null_collision(*value); - Array::insert(ndx + 1, *value); - } - else { - Array::insert(ndx + 1, null_value()); - } -} - -inline void ArrayIntNull::add(value_type value) -{ - if (value) { - avoid_null_collision(*value); - Array::add(*value); - } - else { - Array::add(null_value()); - } -} - -inline void ArrayIntNull::set(size_t ndx, value_type value) noexcept -{ - if (value) { - avoid_null_collision(*value); - Array::set(ndx + 1, *value); - } - else { - Array::set(ndx + 1, null_value()); - } -} - -inline void ArrayIntNull::set_null(size_t ndx) noexcept -{ - Array::set(ndx + 1, null_value()); -} - -inline ArrayIntNull::value_type ArrayIntNull::get(size_t ndx) const noexcept -{ - int64_t value = Array::get(ndx + 1); - if (value == null_value()) { - return util::none; - } - return util::some(value); -} - -inline ArrayIntNull::value_type ArrayIntNull::get(const char* header, size_t ndx) noexcept -{ - int64_t null_value = Array::get(header, 0); - int64_t value = Array::get(header, ndx + 1); - if (value == null_value) { - return util::none; - } - else { - return util::some(value); - } -} - -inline bool ArrayIntNull::is_null(size_t ndx) const noexcept -{ - return !get(ndx); -} - -inline int64_t ArrayIntNull::null_value() const noexcept -{ - return Array::get(0); -} - -inline ArrayIntNull::value_type ArrayIntNull::operator[](size_t ndx) const noexcept -{ - return get(ndx); -} - -inline ArrayIntNull::value_type ArrayIntNull::front() const noexcept -{ - return get(0); -} - -inline ArrayIntNull::value_type ArrayIntNull::back() const noexcept -{ - return Array::back(); -} - -inline void ArrayIntNull::erase(size_t ndx) -{ - Array::erase(ndx + 1); -} - -inline void ArrayIntNull::erase(size_t begin, size_t end) -{ - Array::erase(begin + 1, end + 1); -} - -inline void ArrayIntNull::truncate(size_t to_size) -{ - Array::truncate(to_size + 1); -} - -inline void ArrayIntNull::clear() -{ - truncate(0); -} - -inline void ArrayIntNull::set_all_to_zero() -{ - // FIXME: Array::set_all_to_zero does something else - for (size_t i = 0; i < size(); ++i) { - set(i, 0); - } -} - -inline void ArrayIntNull::move(size_t begin, size_t end, size_t dest_begin) -{ - Array::move(begin + 1, end + 1, dest_begin + 1); -} - -inline void ArrayIntNull::move_backward(size_t begin, size_t end, size_t dest_end) -{ - Array::move_backward(begin + 1, end + 1, dest_end + 1); -} - -inline size_t ArrayIntNull::lower_bound(int64_t value) const noexcept -{ - // FIXME: Consider this behaviour with NULLs. - // Array::lower_bound_int assumes an already sorted array, but - // this array could be sorted with nulls first or last. - return Array::lower_bound_int(value); -} - -inline size_t ArrayIntNull::upper_bound(int64_t value) const noexcept -{ - // FIXME: see lower_bound - return Array::upper_bound_int(value); -} - -inline int64_t ArrayIntNull::sum(size_t start, size_t end) const -{ - // FIXME: Optimize - int64_t sum_of_range = 0; - if (end == npos) - end = size(); - for (size_t i = start; i < end; ++i) { - value_type x = get(i); - if (x) { - sum_of_range += *x; - } - } - return sum_of_range; -} - -inline size_t ArrayIntNull::count(int64_t value) const noexcept -{ - size_t count_of_value = Array::count(value); - if (value == null_value()) { - --count_of_value; - } - return count_of_value; -} - -// FIXME: Optimize -template -inline bool ArrayIntNull::minmax_helper(int64_t& result, size_t start, size_t end, size_t* return_ndx) const -{ - size_t best_index = 1; - - if (end == npos) { - end = m_size; - } - - ++start; - - REALM_ASSERT(start < m_size && end <= m_size && start < end); - - if (m_size == 1) { - // empty array - return false; - } - - if (m_width == 0) { - if (return_ndx) - *return_ndx = best_index - 1; - result = 0; - return true; - } - - int64_t m = Array::get(start); - - const int64_t null_val = null_value(); - for (; start < end; ++start) { - const int64_t v = Array::get(start); - if (find_max ? v > m : v < m) { - if (v == null_val) { - continue; - } - m = v; - best_index = start; - } - } - - result = m; - if (return_ndx) { - *return_ndx = best_index - 1; - } - return true; -} - -inline bool ArrayIntNull::maximum(int64_t& result, size_t start, size_t end, size_t* return_ndx) const -{ - return minmax_helper(result, start, end, return_ndx); -} - -inline bool ArrayIntNull::minimum(int64_t& result, size_t start, size_t end, size_t* return_ndx) const -{ - return minmax_helper(result, start, end, return_ndx); -} - -inline bool ArrayIntNull::find(int cond, Action action, value_type value, size_t start, size_t end, size_t baseindex, - QueryState* state) const -{ - if (value) { - return Array::find(cond, action, *value, start, end, baseindex, state, true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); - } - else { - return Array::find(cond, action, 0 /* unused dummy*/, start, end, baseindex, state, - true /*treat as nullable array*/, true /*search for null, ignore value argument*/); - } -} - -template -bool ArrayIntNull::find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const -{ - if (value) { - return Array::find(*value, start, end, baseindex, state, std::forward(callback), - true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); - } - else { - return Array::find(0 /*ignored*/, start, end, baseindex, state, - std::forward(callback), true /*treat as nullable array*/, - true /*search for null, ignore value argument*/); - } -} - - -template -bool ArrayIntNull::find(int64_t value, size_t start, size_t end, size_t baseindex, QueryState* state) const -{ - return Array::find(value, start, end, baseindex, state, true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); -} - - -template -bool ArrayIntNull::find(value_type value, size_t start, size_t end, size_t baseindex, QueryState* state, - Callback callback) const -{ - if (value) { - return Array::find(*value, start, end, baseindex, state, std::forward(callback), - true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); - } - else { - return Array::find(0 /*ignored*/, start, end, baseindex, state, - std::forward(callback), true /*treat as nullable array*/, - true /*search for null, ignore value argument*/); - } -} - - -template -bool ArrayIntNull::find_action(size_t index, value_type value, QueryState* state, Callback callback) const -{ - if (value) { - return Array::find_action(index, *value, state, callback, true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); - } - else { - return Array::find_action(index, 0 /* ignored */, state, callback, - true /*treat as nullable array*/, - true /*search for null, ignore value argument*/); - } -} - - -template -bool ArrayIntNull::find_action_pattern(size_t index, uint64_t pattern, QueryState* state, - Callback callback) const -{ - return Array::find_action_pattern(index, pattern, state, callback, - true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); -} - - -template -size_t ArrayIntNull::find_first(value_type value, size_t start, size_t end) const -{ - QueryState state; - state.init(act_ReturnFirst, nullptr, 1); - if (value) { - Array::find(*value, start, end, 0, &state, Array::CallbackDummy(), - true /*treat as nullable array*/, - false /*search parameter given in 'value' argument*/); - } - else { - Array::find(0 /*ignored*/, start, end, 0, &state, Array::CallbackDummy(), - true /*treat as nullable array*/, - true /*search for null, ignore value argument*/); - } - - if (state.m_match_count > 0) - return to_size_t(state.m_state); - else - return not_found; -} - -inline size_t ArrayIntNull::find_first(value_type value, size_t begin, size_t end) const -{ - return find_first(value, begin, end); -} -} - -#endif // REALM_ARRAY_INTEGER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_string.hpp b/Lesson14/Pods/Realm/include/core/realm/array_string.hpp deleted file mode 100644 index a533f32..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_string.hpp +++ /dev/null @@ -1,181 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_STRING_HPP -#define REALM_ARRAY_STRING_HPP - -#include - -namespace realm { - -/* -ArrayString stores strings as a concecutive list of fixed-length blocks of m_width bytes. The -longest string it can store is (m_width - 1) bytes before it needs to expand. - -An example of the format for m_width = 4 is following sequence of bytes, where x is payload: - -xxx0 xx01 x002 0003 0004 (strings "xxx",. "xx", "x", "", realm::null()) - -So each string is 0 terminated, and the last byte in a block tells how many 0s are present, except -for a realm::null() which has the byte set to m_width (4). The byte is used to compute the length of a string -in various functions. - -New: If m_witdh = 0, then all elements are realm::null(). So to add an empty string we must expand m_width -New: StringData is null() if-and-only-if StringData::data() == 0. -*/ - -class ArrayString : public Array { -public: - static const size_t max_width = 64; - - typedef StringData value_type; - // Constructor defaults to non-nullable because we use non-nullable ArrayString so many places internally in core - // (data which isn't user payload) where null isn't needed. - explicit ArrayString(Allocator&, bool nullable = false) noexcept; - ~ArrayString() noexcept override - { - } - - bool is_null(size_t ndx) const; - void set_null(size_t ndx); - StringData get(size_t ndx) const noexcept; - StringData get_string(size_t ndx) const noexcept { return get(ndx); } - void add(); - void add(StringData value); - void set(size_t ndx, StringData value); - void insert(size_t ndx, StringData value); - void erase(size_t ndx); - - size_t count(StringData value, size_t begin = 0, size_t end = npos) const noexcept; - size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const noexcept; - void find_all(IntegerColumn& result, StringData value, size_t add_offset = 0, size_t begin = 0, - size_t end = npos); - - /// Compare two string arrays for equality. - bool compare_string(const ArrayString&) const noexcept; - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static StringData get(const char* header, size_t ndx, bool nullable) noexcept; - - ref_type bptree_leaf_insert(size_t ndx, StringData, TreeInsertBase& state); - - /// Construct a string array of the specified size and return just - /// the reference to the underlying memory. All elements will be - /// initialized to the empty string. - static MemRef create_array(size_t size, Allocator&); - - /// Create a new empty string array and attach this accessor to - /// it. This does not modify the parent reference information of - /// this accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(); - - /// Construct a copy of the specified slice of this string array - /// using the specified target allocator. - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - -#ifdef REALM_DEBUG - void string_stats() const; - void to_dot(std::ostream&, StringData title = StringData()) const; -#endif - -private: - size_t calc_byte_len(size_t num_items, size_t width) const override; - size_t calc_item_count(size_t bytes, size_t width) const noexcept override; - - bool m_nullable; -}; - - -// Implementation: - -// Creates new array (but invalid, call init_from_ref() to init) -inline ArrayString::ArrayString(Allocator& allocator, bool nullable) noexcept - : Array(allocator) - , m_nullable(nullable) -{ -} - -inline void ArrayString::create() -{ - size_t init_size = 0; - MemRef mem = create_array(init_size, get_alloc()); // Throws - init_from_mem(mem); -} - -inline MemRef ArrayString::create_array(size_t init_size, Allocator& allocator) -{ - bool context_flag = false; - int_fast64_t value = 0; - return Array::create(type_Normal, context_flag, wtype_Multiply, init_size, value, allocator); // Throws -} - -inline StringData ArrayString::get(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_size); - if (m_width == 0) - return m_nullable ? realm::null() : StringData(""); - - const char* data = m_data + (ndx * m_width); - size_t array_size = (m_width - 1) - data[m_width - 1]; - - if (array_size == static_cast(-1)) - return m_nullable ? realm::null() : StringData(""); - - REALM_ASSERT_EX(data[array_size] == 0, data[array_size], - array_size); // Realm guarantees 0 terminated return strings - return StringData(data, array_size); -} - -inline void ArrayString::add(StringData value) -{ - REALM_ASSERT(!(!m_nullable && value.is_null())); - insert(m_size, value); // Throws -} - -inline void ArrayString::add() -{ - add(m_nullable ? realm::null() : StringData("")); // Throws -} - -inline StringData ArrayString::get(const char* header, size_t ndx, bool nullable) noexcept -{ - REALM_ASSERT(ndx < get_size_from_header(header)); - uint_least8_t width = get_width_from_header(header); - const char* data = get_data_from_header(header) + (ndx * width); - - if (width == 0) - return nullable ? realm::null() : StringData(""); - - size_t size = (width - 1) - data[width - 1]; - - if (size == static_cast(-1)) - return nullable ? realm::null() : StringData(""); - - return StringData(data, size); -} - - -} // namespace realm - -#endif // REALM_ARRAY_STRING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/array_string_long.hpp b/Lesson14/Pods/Realm/include/core/realm/array_string_long.hpp deleted file mode 100644 index b03d8b4..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/array_string_long.hpp +++ /dev/null @@ -1,229 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_STRING_LONG_HPP -#define REALM_ARRAY_STRING_LONG_HPP - -#include -#include - -namespace realm { - - -class ArrayStringLong : public Array { -public: - typedef StringData value_type; - - explicit ArrayStringLong(Allocator&, bool nullable) noexcept; - ~ArrayStringLong() noexcept override - { - } - - // Disable copying, this is not allowed. - ArrayStringLong& operator=(const ArrayStringLong&) = delete; - ArrayStringLong(const ArrayStringLong&) = delete; - - /// Create a new empty long string array and attach this accessor to - /// it. This does not modify the parent reference information of - /// this accessor. - /// - /// Note that the caller assumes ownership of the allocated - /// underlying node. It is not owned by the accessor. - void create(); - - //@{ - /// Overriding functions of Array - void init_from_ref(ref_type) noexcept; - void init_from_mem(MemRef) noexcept; - void init_from_parent() noexcept; - //@} - - bool is_empty() const noexcept; - size_t size() const noexcept; - - StringData get(size_t ndx) const noexcept; - StringData get_string(size_t ndx) const noexcept { return get(ndx); } - - - void add(StringData value); - void set(size_t ndx, StringData value); - void insert(size_t ndx, StringData value); - void erase(size_t ndx); - void truncate(size_t size); - void clear(); - void destroy(); - - bool is_null(size_t ndx) const; - void set_null(size_t ndx); - - size_t count(StringData value, size_t begin = 0, size_t end = npos) const noexcept; - size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const noexcept; - void find_all(IntegerColumn& result, StringData value, size_t add_offset = 0, size_t begin = 0, - size_t end = npos) const; - - /// Get the specified element without the cost of constructing an - /// array instance. If an array instance is already available, or - /// you need to get multiple values, then this method will be - /// slower. - static StringData get(const char* header, size_t ndx, Allocator&, bool nullable) noexcept; - - ref_type bptree_leaf_insert(size_t ndx, StringData, TreeInsertBase&); - - static size_t get_size_from_header(const char*, Allocator&) noexcept; - - /// Construct a long string array of the specified size and return - /// just the reference to the underlying memory. All elements will - /// be initialized to zero size blobs. - static MemRef create_array(size_t size, Allocator&, bool nullable); - - /// Construct a copy of the specified slice of this long string - /// array using the specified target allocator. - MemRef slice(size_t offset, size_t slice_size, Allocator& target_alloc) const; - -#ifdef REALM_DEBUG - void to_dot(std::ostream&, StringData title = StringData()) const; -#endif - - bool update_from_parent(size_t old_baseline) noexcept; - -private: - ArrayInteger m_offsets; - ArrayBlob m_blob; - Array m_nulls; - bool m_nullable; -}; - - -// Implementation: -inline ArrayStringLong::ArrayStringLong(Allocator& allocator, bool nullable) noexcept - : Array(allocator) - , m_offsets(allocator) - , m_blob(allocator) - , m_nulls(nullable ? allocator : Allocator::get_default()) - , m_nullable(nullable) -{ - m_offsets.set_parent(this, 0); - m_blob.set_parent(this, 1); - if (nullable) - m_nulls.set_parent(this, 2); -} - -inline void ArrayStringLong::create() -{ - size_t init_size = 0; - MemRef mem = create_array(init_size, get_alloc(), m_nullable); // Throws - init_from_mem(mem); -} - -inline void ArrayStringLong::init_from_ref(ref_type ref) noexcept -{ - REALM_ASSERT(ref); - char* header = get_alloc().translate(ref); - init_from_mem(MemRef(header, ref, m_alloc)); - m_nullable = (Array::size() == 3); -} - -inline void ArrayStringLong::init_from_parent() noexcept -{ - ref_type ref = get_ref_from_parent(); - init_from_ref(ref); -} - -inline bool ArrayStringLong::is_empty() const noexcept -{ - return m_offsets.is_empty(); -} - -inline size_t ArrayStringLong::size() const noexcept -{ - return m_offsets.size(); -} - -inline StringData ArrayStringLong::get(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_offsets.size()); - - if (m_nullable && m_nulls.get(ndx) == 0) - return realm::null(); - - size_t begin, end; - if (0 < ndx) { - begin = to_size_t(m_offsets.get(ndx - 1)); - end = to_size_t(m_offsets.get(ndx)); - } - else { - begin = 0; - end = to_size_t(m_offsets.get(0)); - } - --end; // Discount the terminating zero - - return StringData(m_blob.get(begin), end - begin); -} - -inline void ArrayStringLong::truncate(size_t new_size) -{ - REALM_ASSERT_3(new_size, <, m_offsets.size()); - - size_t sz = new_size ? to_size_t(m_offsets.get(new_size - 1)) : 0; - - m_offsets.truncate(new_size); - m_blob.truncate(sz); - if (m_nullable) - m_nulls.truncate(new_size); -} - -inline void ArrayStringLong::clear() -{ - m_blob.clear(); - m_offsets.clear(); - if (m_nullable) - m_nulls.clear(); -} - -inline void ArrayStringLong::destroy() -{ - m_blob.destroy(); - m_offsets.destroy(); - if (m_nullable) - m_nulls.destroy(); - Array::destroy(); -} - -inline bool ArrayStringLong::update_from_parent(size_t old_baseline) noexcept -{ - bool res = Array::update_from_parent(old_baseline); - if (res) { - m_blob.update_from_parent(old_baseline); - m_offsets.update_from_parent(old_baseline); - if (m_nullable) - m_nulls.update_from_parent(old_baseline); - } - return res; -} - -inline size_t ArrayStringLong::get_size_from_header(const char* header, Allocator& alloc) noexcept -{ - ref_type offsets_ref = to_ref(Array::get(header, 0)); - const char* offsets_header = alloc.translate(offsets_ref); - return Array::get_size_from_header(offsets_header); -} - - -} // namespace realm - -#endif // REALM_ARRAY_STRING_LONG_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/binary_data.hpp b/Lesson14/Pods/Realm/include/core/realm/binary_data.hpp deleted file mode 100644 index a184f0c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/binary_data.hpp +++ /dev/null @@ -1,239 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_BINARY_DATA_HPP -#define REALM_BINARY_DATA_HPP - -#include -#include -#include - -#include -#include -#include -#include - -namespace realm { - -/// A reference to a chunk of binary data. -/// -/// This class does not own the referenced memory, nor does it in any other way -/// attempt to manage the lifetime of it. -/// -/// \sa StringData -class BinaryData { -public: - BinaryData() noexcept - : m_data(nullptr) - , m_size(0) - { - } - BinaryData(const char* external_data, size_t data_size) noexcept - : m_data(external_data) - , m_size(data_size) - { - } - template - explicit BinaryData(const char (&external_data)[N]) - : m_data(external_data) - , m_size(N) - { - } - template - explicit BinaryData(const std::basic_string&); - - // BinaryData does not store data, callers must manage their own strings. - template - BinaryData(const std::basic_string&&) = delete; - - template - explicit operator std::basic_string() const; - - char operator[](size_t i) const noexcept - { - return m_data[i]; - } - - const char* data() const noexcept - { - return m_data; - } - size_t size() const noexcept - { - return m_size; - } - - /// Is this a null reference? - /// - /// An instance of BinaryData is a null reference when, and only when the - /// stored size is zero (size()) and the stored pointer is the null pointer - /// (data()). - /// - /// In the case of the empty byte sequence, the stored size is still zero, - /// but the stored pointer is **not** the null pointer. Note that the actual - /// value of the pointer is immaterial in this case (as long as it is not - /// zero), because when the size is zero, it is an error to dereference the - /// pointer. - /// - /// Conversion of a BinaryData object to `bool` yields the logical negation - /// of the result of calling this function. In other words, a BinaryData - /// object is converted to true if it is not the null reference, otherwise - /// it is converted to false. - /// - /// It is important to understand that all of the functions and operators in - /// this class, and most of the functions in the Realm API in general - /// makes no distinction between a null reference and a reference to the - /// empty byte sequence. These functions and operators never look at the - /// stored pointer if the stored size is zero. - bool is_null() const noexcept; - - friend bool operator==(const BinaryData&, const BinaryData&) noexcept; - friend bool operator!=(const BinaryData&, const BinaryData&) noexcept; - - //@{ - /// Trivial bytewise lexicographical comparison. - friend bool operator<(const BinaryData&, const BinaryData&) noexcept; - friend bool operator>(const BinaryData&, const BinaryData&) noexcept; - friend bool operator<=(const BinaryData&, const BinaryData&) noexcept; - friend bool operator>=(const BinaryData&, const BinaryData&) noexcept; - //@} - - bool begins_with(BinaryData) const noexcept; - bool ends_with(BinaryData) const noexcept; - bool contains(BinaryData) const noexcept; - - template - friend std::basic_ostream& operator<<(std::basic_ostream&, const BinaryData&); - - explicit operator bool() const noexcept; - -private: - const char* m_data; - size_t m_size; -}; - -/// A read-only chunk of binary data. -class OwnedBinaryData : public OwnedData { -public: - using OwnedData::OwnedData; - - OwnedBinaryData() = default; - OwnedBinaryData(const BinaryData& binary_data) - : OwnedData(binary_data.data(), binary_data.size()) - { - } - - BinaryData get() const - { - return {data(), size()}; - } -}; - - -// Implementation: - -template -inline BinaryData::BinaryData(const std::basic_string& s) - : m_data(s.data()) - , m_size(s.size()) -{ -} - -template -inline BinaryData::operator std::basic_string() const -{ - return std::basic_string(m_data, m_size); -} - -inline bool BinaryData::is_null() const noexcept -{ - return !m_data; -} - -inline bool operator==(const BinaryData& a, const BinaryData& b) noexcept -{ - return a.m_size == b.m_size && a.is_null() == b.is_null() && safe_equal(a.m_data, a.m_data + a.m_size, b.m_data); -} - -inline bool operator!=(const BinaryData& a, const BinaryData& b) noexcept -{ - return !(a == b); -} - -inline bool operator<(const BinaryData& a, const BinaryData& b) noexcept -{ - if (a.is_null() || b.is_null()) - return !a.is_null() < !b.is_null(); - - return std::lexicographical_compare(a.m_data, a.m_data + a.m_size, b.m_data, b.m_data + b.m_size); -} - -inline bool operator>(const BinaryData& a, const BinaryData& b) noexcept -{ - return b < a; -} - -inline bool operator<=(const BinaryData& a, const BinaryData& b) noexcept -{ - return !(b < a); -} - -inline bool operator>=(const BinaryData& a, const BinaryData& b) noexcept -{ - return !(a < b); -} - -inline bool BinaryData::begins_with(BinaryData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - - return d.m_size <= m_size && safe_equal(m_data, m_data + d.m_size, d.m_data); -} - -inline bool BinaryData::ends_with(BinaryData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - - return d.m_size <= m_size && safe_equal(m_data + m_size - d.m_size, m_data + m_size, d.m_data); -} - -inline bool BinaryData::contains(BinaryData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - - return d.m_size == 0 || std::search(m_data, m_data + m_size, d.m_data, d.m_data + d.m_size) != m_data + m_size; -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const BinaryData& d) -{ - out << "BinaryData(" << static_cast(d.m_data) << ", " << d.m_size << ")"; - return out; -} - -inline BinaryData::operator bool() const noexcept -{ - return !is_null(); -} - -} // namespace realm - -#endif // REALM_BINARY_DATA_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/bptree.hpp b/Lesson14/Pods/Realm/include/core/realm/bptree.hpp deleted file mode 100644 index aae64de..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/bptree.hpp +++ /dev/null @@ -1,1271 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_BPTREE_HPP -#define REALM_BPTREE_HPP - -#include // std::unique_ptr -#include -#include -#include -#include -#include - -namespace realm { - -/// Specialize BpTree to implement column types. -template -class BpTree; - -class ArrayInteger; -class ArrayIntNull; - -class BpTreeNode : public Array { -public: - using Array::Array; - /// Get the number of elements in the B+-tree rooted at this array - /// node. The root must not be a leaf. - /// - /// Please avoid using this function (consider it deprecated). It - /// will have to be removed if we choose to get rid of the last - /// element of the main array of an inner B+-tree node that stores - /// the total number of elements in the subtree. The motivation - /// for removing it, is that it will significantly improve the - /// efficiency when inserting after, and erasing the last element. - size_t get_bptree_size() const noexcept; - - /// The root must not be a leaf. - static size_t get_bptree_size_from_header(const char* root_header) noexcept; - - - /// Find the leaf node corresponding to the specified element - /// index index. The specified element index must refer to an - /// element that exists in the tree. This function must be called - /// on an inner B+-tree node, never a leaf. Note that according to - /// invar:bptree-nonempty-inner and invar:bptree-nonempty-leaf, an - /// inner B+-tree node can never be empty. - /// - /// This function is not obliged to instantiate intermediate array - /// accessors. For this reason, this function cannot be used for - /// operations that modify the tree, as that requires an unbroken - /// chain of parent array accessors between the root and the - /// leaf. Thus, despite the fact that the returned MemRef object - /// appears to allow modification of the referenced memory, the - /// caller must handle the memory reference as if it was - /// const-qualified. - /// - /// \return (`leaf_header`, `ndx_in_leaf`) where `leaf_header` - /// points to the the header of the located leaf, and - /// `ndx_in_leaf` is the local index within that leaf - /// corresponding to the specified element index. - std::pair get_bptree_leaf(size_t elem_ndx) const noexcept; - - - class NodeInfo; - class VisitHandler; - - /// Visit leaves of the B+-tree rooted at this inner node, - /// starting with the leaf that contains the element at the - /// specified element index start offset, and ending when the - /// handler returns false. The specified element index offset must - /// refer to an element that exists in the tree. This function - /// must be called on an inner B+-tree node, never a leaf. Note - /// that according to invar:bptree-nonempty-inner and - /// invar:bptree-nonempty-leaf, an inner B+-tree node can never be - /// empty. - /// - /// \param elem_ndx_offset The start position (must be valid). - /// - /// \param elems_in_tree The total number of elements in the tree. - /// - /// \param handler The callback which will get called for each leaf. - /// - /// \return True if, and only if the handler has returned true for - /// all visited leafs. - bool visit_bptree_leaves(size_t elem_ndx_offset, size_t elems_in_tree, VisitHandler& handler); - - - class UpdateHandler; - - /// Call the handler for every leaf. This function must be called - /// on an inner B+-tree node, never a leaf. - void update_bptree_leaves(UpdateHandler&); - - /// Call the handler for the leaf that contains the element at the - /// specified index. This function must be called on an inner - /// B+-tree node, never a leaf. - void update_bptree_elem(size_t elem_ndx, UpdateHandler&); - - - class EraseHandler; - - /// Erase the element at the specified index in the B+-tree with - /// the specified root. When erasing the last element, you must - /// pass npos in place of the index. This function must be called - /// with a root that is an inner B+-tree node, never a leaf. - /// - /// This function is guaranteed to succeed (not throw) if the - /// specified element was inserted during the current transaction, - /// and no other modifying operation has been carried out since - /// then (noexcept:bptree-erase-alt). - /// - /// FIXME: ExceptionSafety: The exception guarantee explained - /// above is not as powerfull as we would like it to be. Here is - /// what we would like: This function is guaranteed to succeed - /// (not throw) if the specified element was inserted during the - /// current transaction (noexcept:bptree-erase). This must be true - /// even if the element is modified after insertion, and/or if - /// other elements are inserted or erased around it. There are two - /// aspects of the current design that stand in the way of this - /// guarantee: (A) The fact that the node accessor, that is cached - /// in the column accessor, has to be reallocated/reinstantiated - /// when the root switches between being a leaf and an inner - /// node. This problem would go away if we always cached the last - /// used leaf accessor in the column accessor instead. (B) The - /// fact that replacing one child ref with another can fail, - /// because it may require reallocation of memory to expand the - /// bit-width. This can be fixed in two ways: Either have the - /// inner B+-tree nodes always have a bit-width of 64, or allow - /// the root node to be discarded and the column ref to be set to - /// zero in Table::m_columns. - static void erase_bptree_elem(BpTreeNode* root, size_t elem_ndx, EraseHandler&); - - template - struct TreeInsert : TreeInsertBase { - typename TreeTraits::value_type m_value; - bool m_nullable; - }; - - /// Same as bptree_insert() but insert after the last element. - template - ref_type bptree_append(TreeInsert& state); - - /// Insert an element into the B+-subtree rooted at this array - /// node. The element is inserted before the specified element - /// index. This function must be called on an inner B+-tree node, - /// never a leaf. If this inner node had to be split, this - /// function returns the `ref` of the new sibling. - template - ref_type bptree_insert(size_t elem_ndx, TreeInsert& state); - -protected: - /// Insert a new child after original. If the parent has to be - /// split, this function returns the `ref` of the new parent node. - ref_type insert_bptree_child(Array& offsets, size_t orig_child_ndx, ref_type new_sibling_ref, - TreeInsertBase& state); - - void ensure_bptree_offsets(Array& offsets); - void create_bptree_offsets(Array& offsets, int_fast64_t first_value); - - bool do_erase_bptree_elem(size_t elem_ndx, EraseHandler&); -}; - -class BpTreeBase { -public: - struct unattached_tag { - }; - - // Disable copying, this is not allowed. - BpTreeBase& operator=(const BpTreeBase&) = delete; - BpTreeBase(const BpTreeBase&) = delete; - - // Accessor concept: - Allocator& get_alloc() const noexcept; - void destroy() noexcept; - void detach(); - bool is_attached() const noexcept; - void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; - size_t get_ndx_in_parent() const noexcept; - void set_ndx_in_parent(size_t ndx) noexcept; - void update_from_parent(size_t old_baseline) noexcept; - MemRef clone_deep(Allocator& alloc) const; - - // BpTree interface: - const Array& root() const noexcept; - Array& root() noexcept; - bool root_is_leaf() const noexcept; - BpTreeNode& root_as_node(); - const BpTreeNode& root_as_node() const; - void introduce_new_root(ref_type new_sibling_ref, TreeInsertBase& state, bool is_append); - void replace_root(std::unique_ptr leaf); - -protected: - explicit BpTreeBase(std::unique_ptr root); - explicit BpTreeBase(BpTreeBase&&) = default; - BpTreeBase& operator=(BpTreeBase&&) = default; - std::unique_ptr m_root; - - struct SliceHandler { - virtual MemRef slice_leaf(MemRef leaf_mem, size_t offset, size_t size, Allocator& target_alloc) = 0; - ~SliceHandler() noexcept - { - } - }; - static ref_type write_subtree(const BpTreeNode& root, size_t slice_offset, size_t slice_size, size_t table_size, - SliceHandler&, _impl::OutputStream&); - friend class ColumnBase; - friend class ColumnBaseSimple; - -private: - struct WriteSliceHandler; - - // FIXME: Move B+Tree functionality from Array to this class. -}; - - -// Default implementation of BpTree. This should work for all types that have monomorphic -// leaves (i.e. all leaves are of the same type). -template -class BpTree : public BpTreeBase { -public: - using value_type = T; - using LeafType = typename ColumnTypeTraits::leaf_type; - - /// LeafInfo is used by get_leaf() to provide access to a leaf - /// without instantiating unnecessary nodes along the way. - /// Upon return, out_leaf with hold a pointer to the leaf containing - /// the index given to get_leaf(). If the index happens to be - /// in the root node (i.e., the root is a leaf), it will point - /// to the root node. - /// If the index isn't in the root node, fallback will be initialized - /// to represent the leaf holding the node, and out_leaf will be set - /// to point to fallback. - struct LeafInfo { - const LeafType** out_leaf; - LeafType* fallback; - }; - - BpTree(); - explicit BpTree(BpTreeBase::unattached_tag); - explicit BpTree(Allocator& alloc); - REALM_DEPRECATED("Initialize with MemRef instead") - explicit BpTree(std::unique_ptr init_root) - : BpTreeBase(std::move(init_root)) - { - } - explicit BpTree(Allocator& alloc, MemRef mem) - : BpTreeBase(std::unique_ptr(new LeafType(alloc))) - { - init_from_mem(alloc, mem); - } - BpTree(BpTree&&) = default; - BpTree& operator=(BpTree&&) = default; - - // Disable copying, this is not allowed. - BpTree& operator=(const BpTree&) = delete; - BpTree(const BpTree&) = delete; - - void init_from_ref(Allocator& alloc, ref_type ref); - void init_from_mem(Allocator& alloc, MemRef mem); - void init_from_parent(); - - size_t size() const noexcept; - bool is_empty() const noexcept - { - return size() == 0; - } - - T get(size_t ndx) const noexcept; - bool is_null(size_t ndx) const noexcept; - void set(size_t, T value); - void set_null(size_t); - void insert(size_t ndx, T value, size_t num_rows = 1); - void erase(size_t ndx, bool is_last = false); - void move_last_over(size_t ndx, size_t last_row_ndx); - void clear(); - T front() const noexcept; - T back() const noexcept; - - size_t find_first(T value, size_t begin = 0, size_t end = npos) const; - void find_all(IntegerColumn& out_indices, T value, size_t begin = 0, size_t end = npos) const; - - static MemRef create_leaf(Array::Type leaf_type, size_t size, T value, Allocator&); - - /// See LeafInfo for information about what to put in the inout_leaf - /// parameter. - /// - /// This function cannot be used for modifying operations as it - /// does not ensure the presence of an unbroken chain of parent - /// accessors. For this reason, the identified leaf should always - /// be accessed through the returned const-qualified reference, - /// and never directly through the specfied fallback accessor. - void get_leaf(size_t ndx, size_t& out_ndx_in_leaf, LeafInfo& inout_leaf) const noexcept; - - void update_each(BpTreeNode::UpdateHandler&); - void update_elem(size_t, BpTreeNode::UpdateHandler&); - - void adjust(size_t ndx, T diff); - void adjust(T diff); - void adjust_ge(T limit, T diff); - - ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const; - -#if defined(REALM_DEBUG) - void verify() const; - static size_t verify_leaf(MemRef mem, Allocator& alloc); -#endif - static void leaf_to_dot(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out, - Allocator& alloc); - -private: - LeafType& root_as_leaf(); - const LeafType& root_as_leaf() const; - - std::unique_ptr create_root_from_ref(Allocator& alloc, ref_type ref); - std::unique_ptr create_root_from_mem(Allocator& alloc, MemRef mem); - - struct EraseHandler; - struct UpdateHandler; - struct SetNullHandler; - struct SliceHandler; - struct AdjustHandler; - struct AdjustGEHandler; - - struct LeafValueInserter; - struct LeafNullInserter; - - template - void bptree_insert(size_t row_ndx, BpTreeNode::TreeInsert& state, size_t num_rows); -}; - - -class BpTreeNode::NodeInfo { -public: - MemRef m_mem; - Array* m_parent; - size_t m_ndx_in_parent; - size_t m_offset, m_size; -}; - -class BpTreeNode::VisitHandler { -public: - virtual bool visit(const NodeInfo& leaf_info) = 0; - virtual ~VisitHandler() noexcept - { - } -}; - - -class BpTreeNode::UpdateHandler { -public: - virtual void update(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; - virtual ~UpdateHandler() noexcept - { - } -}; - - -class BpTreeNode::EraseHandler { -public: - /// If the specified leaf has more than one element, this function - /// must erase the specified element from the leaf and return - /// false. Otherwise, when the leaf has a single element, this - /// function must return true without modifying the leaf. If \a - /// elem_ndx_in_leaf is `npos`, it refers to the last element in - /// the leaf. The implementation of this function must be - /// exception safe. This function is guaranteed to be called at - /// most once during each execution of Array::erase_bptree_elem(), - /// and *exactly* once during each *successful* execution of - /// Array::erase_bptree_elem(). - virtual bool erase_leaf_elem(MemRef, ArrayParent*, size_t leaf_ndx_in_parent, size_t elem_ndx_in_leaf) = 0; - - virtual void destroy_leaf(MemRef leaf_mem) noexcept = 0; - - /// Must replace the current root with the specified leaf. The - /// implementation of this function must not destroy the - /// underlying root node, or any of its children, as that will be - /// done by Array::erase_bptree_elem(). The implementation of this - /// function must be exception safe. - virtual void replace_root_by_leaf(MemRef leaf_mem) = 0; - - /// Same as replace_root_by_leaf(), but must replace the root with - /// an empty leaf. Also, if this function is called during an - /// execution of Array::erase_bptree_elem(), it is guaranteed that - /// it will be preceeded by a call to erase_leaf_elem(). - virtual void replace_root_by_empty_leaf() = 0; - - virtual ~EraseHandler() noexcept - { - } -}; - - -/// Implementation: - -inline BpTreeBase::BpTreeBase(std::unique_ptr init_root) - : m_root(std::move(init_root)) -{ -} - -inline Allocator& BpTreeBase::get_alloc() const noexcept -{ - return m_root->get_alloc(); -} - -inline void BpTreeBase::destroy() noexcept -{ - if (m_root) - m_root->destroy_deep(); -} - -inline void BpTreeBase::detach() -{ - m_root->detach(); -} - -inline bool BpTreeBase::is_attached() const noexcept -{ - return m_root->is_attached(); -} - -inline bool BpTreeBase::root_is_leaf() const noexcept -{ - return !m_root->is_inner_bptree_node(); -} - -inline BpTreeNode& BpTreeBase::root_as_node() -{ - REALM_ASSERT_DEBUG(!root_is_leaf()); - REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); - return static_cast(root()); -} - -inline const BpTreeNode& BpTreeBase::root_as_node() const -{ - Array* arr = m_root.get(); - REALM_ASSERT_DEBUG(!root_is_leaf()); - REALM_ASSERT_DEBUG(dynamic_cast(arr) != nullptr); - return static_cast(*arr); -} - -inline void BpTreeBase::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept -{ - m_root->set_parent(parent, ndx_in_parent); -} - -inline size_t BpTreeBase::get_ndx_in_parent() const noexcept -{ - return m_root->get_ndx_in_parent(); -} - -inline void BpTreeBase::set_ndx_in_parent(size_t ndx) noexcept -{ - m_root->set_ndx_in_parent(ndx); -} - -inline void BpTreeBase::update_from_parent(size_t old_baseline) noexcept -{ - m_root->update_from_parent(old_baseline); -} - -inline MemRef BpTreeBase::clone_deep(Allocator& alloc) const -{ - return m_root->clone_deep(alloc); -} - -inline const Array& BpTreeBase::root() const noexcept -{ - return *m_root; -} - -inline Array& BpTreeBase::root() noexcept -{ - return *m_root; -} - -inline size_t BpTreeNode::get_bptree_size() const noexcept -{ - REALM_ASSERT_DEBUG(is_inner_bptree_node()); - int_fast64_t v = back(); - return size_t(v / 2); // v = 1 + 2*total_elems_in_tree -} - -inline size_t BpTreeNode::get_bptree_size_from_header(const char* root_header) noexcept -{ - REALM_ASSERT_DEBUG(get_is_inner_bptree_node_from_header(root_header)); - size_t root_size = get_size_from_header(root_header); - int_fast64_t v = get(root_header, root_size - 1); - return size_t(v / 2); // v = 1 + 2*total_elems_in_tree -} - -inline void BpTreeNode::ensure_bptree_offsets(Array& offsets) -{ - int_fast64_t first_value = get(0); - if (first_value % 2 == 0) { - offsets.init_from_ref(to_ref(first_value)); - } - else { - create_bptree_offsets(offsets, first_value); // Throws - } - offsets.set_parent(this, 0); -} - - -template -ref_type BpTreeNode::bptree_append(TreeInsert& state) -{ - // FIXME: Consider exception safety. Especially, how can the split - // be carried out in an exception safe manner? - // - // Can split be done as a separate preparation step, such that if - // the actual insert fails, the split will still have occured. - // - // Unfortunately, it requires a rather significant rearrangement - // of the insertion flow. Instead of returning the sibling ref - // from insert functions, the leaf-insert functions must instead - // call the special bptree_insert() function on the parent, which - // will then cascade the split towards the root as required. - // - // At each level where a split is required (starting at the leaf): - // - // 1. Create the new sibling. - // - // 2. Copy relevant entries over such that new sibling is in - // its final state. - // - // 3. Call Array::bptree_insert() on parent with sibling ref. - // - // 4. Rearrange entries in original sibling and truncate as - // required (must not throw). - // - // What about the 'offsets' array? It will always be - // present. Consider this carefully. - - REALM_ASSERT_DEBUG(size() >= 1 + 1 + 1); // At least one child - - ArrayParent& childs_parent = *this; - size_t child_ref_ndx = size() - 2; - ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; - char* child_header = static_cast(m_alloc.translate(child_ref)); - - bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); - if (child_is_leaf) { - size_t elem_ndx_in_child = npos; // Append - new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref, m_alloc), childs_parent, - child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws - } - else { - BpTreeNode child(m_alloc); - child.init_from_mem(MemRef(child_header, child_ref, m_alloc)); - child.set_parent(&childs_parent, child_ref_ndx); - new_sibling_ref = child.bptree_append(state); // Throws - } - - if (REALM_LIKELY(!new_sibling_ref)) { - // +2 because stored value is 1 + 2*total_elems_in_subtree - adjust(size() - 1, +2); // Throws - return 0; // Child was not split, so parent was not split either - } - - Array offsets(m_alloc); - int_fast64_t first_value = get(0); - if (first_value % 2 == 0) { - // Offsets array is present (general form) - offsets.init_from_ref(to_ref(first_value)); - offsets.set_parent(this, 0); - } - size_t child_ndx = child_ref_ndx - 1; - return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws -} - - -template -ref_type BpTreeNode::bptree_insert(size_t elem_ndx, TreeInsert& state) -{ - REALM_ASSERT_3(size(), >=, 1 + 1 + 1); // At least one child - - // Conversion to general form if in compact form. Since this - // conversion will occur from root to leaf, it will maintain - // invar:bptree-node-form. - Array offsets(m_alloc); - ensure_bptree_offsets(offsets); // Throws - - size_t child_ndx, elem_ndx_in_child; - if (elem_ndx == 0) { - // Optimization for prepend - child_ndx = 0; - elem_ndx_in_child = 0; - } - else { - // There is a choice to be made when the element is to be - // inserted between two subtrees. It can either be appended to - // the first subtree, or it can be prepended to the second - // one. We currently always append to the first subtree. It is - // essentially a matter of using the lower vs. the upper bound - // when searching through the offsets array. - child_ndx = offsets.lower_bound_int(elem_ndx); - REALM_ASSERT_3(child_ndx, <, size() - 2); - size_t elem_ndx_offset = child_ndx == 0 ? 0 : to_size_t(offsets.get(child_ndx - 1)); - elem_ndx_in_child = elem_ndx - elem_ndx_offset; - } - - ArrayParent& childs_parent = *this; - size_t child_ref_ndx = child_ndx + 1; - ref_type child_ref = get_as_ref(child_ref_ndx), new_sibling_ref; - char* child_header = static_cast(m_alloc.translate(child_ref)); - bool child_is_leaf = !get_is_inner_bptree_node_from_header(child_header); - if (child_is_leaf) { - REALM_ASSERT_3(elem_ndx_in_child, <=, REALM_MAX_BPNODE_SIZE); - new_sibling_ref = TreeTraits::leaf_insert(MemRef(child_header, child_ref, m_alloc), childs_parent, - child_ref_ndx, m_alloc, elem_ndx_in_child, state); // Throws - } - else { - BpTreeNode child(m_alloc); - child.init_from_mem(MemRef(child_header, child_ref, m_alloc)); - child.set_parent(&childs_parent, child_ref_ndx); - new_sibling_ref = child.bptree_insert(elem_ndx_in_child, state); // Throws - } - - if (REALM_LIKELY(!new_sibling_ref)) { - // +2 because stored value is 1 + 2*total_elems_in_subtree - adjust(size() - 1, +2); // Throws - offsets.adjust(child_ndx, offsets.size(), +1); - return 0; // Child was not split, so parent was not split either - } - - return insert_bptree_child(offsets, child_ndx, new_sibling_ref, state); // Throws -} - -template -BpTree::BpTree() - : BpTree(Allocator::get_default()) -{ -} - -template -BpTree::BpTree(Allocator& alloc) - : BpTreeBase(std::unique_ptr(new LeafType(alloc))) -{ -} - -template -BpTree::BpTree(BpTreeBase::unattached_tag) - : BpTreeBase(nullptr) -{ -} - -template -std::unique_ptr BpTree::create_root_from_mem(Allocator& alloc, MemRef mem) -{ - const char* header = mem.get_addr(); - std::unique_ptr new_root; - bool is_inner_bptree_node = Array::get_is_inner_bptree_node_from_header(header); - - bool can_reuse_root_accessor = - m_root && &m_root->get_alloc() == &alloc && m_root->is_inner_bptree_node() == is_inner_bptree_node; - if (can_reuse_root_accessor) { - if (is_inner_bptree_node) { - m_root->init_from_mem(mem); - } - else { - static_cast(*m_root).init_from_mem(mem); - } - return std::move(m_root); // Same root will be reinstalled. - } - - // Not reusing root note, allocating a new one. - if (is_inner_bptree_node) { - new_root.reset(new BpTreeNode{alloc}); - new_root->init_from_mem(mem); - } - else { - std::unique_ptr leaf{new LeafType{alloc}}; - leaf->init_from_mem(mem); - new_root = std::move(leaf); - } - return new_root; -} - -template -std::unique_ptr BpTree::create_root_from_ref(Allocator& alloc, ref_type ref) -{ - MemRef mem = MemRef{alloc.translate(ref), ref, alloc}; - return create_root_from_mem(alloc, mem); -} - -template -void BpTree::init_from_ref(Allocator& alloc, ref_type ref) -{ - auto new_root = create_root_from_ref(alloc, ref); - replace_root(std::move(new_root)); -} - -template -void BpTree::init_from_mem(Allocator& alloc, MemRef mem) -{ - auto new_root = create_root_from_mem(alloc, mem); - replace_root(std::move(new_root)); -} - -template -void BpTree::init_from_parent() -{ - ref_type ref = root().get_ref_from_parent(); - if (ref) { - ArrayParent* parent = m_root->get_parent(); - size_t ndx_in_parent = m_root->get_ndx_in_parent(); - auto new_root = create_root_from_ref(get_alloc(), ref); - new_root->set_parent(parent, ndx_in_parent); - m_root = std::move(new_root); - } - else { - m_root->detach(); - } -} - -template -typename BpTree::LeafType& BpTree::root_as_leaf() -{ - REALM_ASSERT_DEBUG(root_is_leaf()); - REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); - return static_cast(root()); -} - -template -const typename BpTree::LeafType& BpTree::root_as_leaf() const -{ - REALM_ASSERT_DEBUG(root_is_leaf()); - REALM_ASSERT_DEBUG(dynamic_cast(m_root.get()) != nullptr); - return static_cast(root()); -} - -template -size_t BpTree::size() const noexcept -{ - if (root_is_leaf()) { - return root_as_leaf().size(); - } - return root_as_node().get_bptree_size(); -} - -template -T BpTree::back() const noexcept -{ - // FIXME: slow - return get(size() - 1); -} - -namespace _impl { - -// NullableOrNothing encapsulates the behavior of nullable and -// non-nullable leaf types, so that non-nullable leaf types -// don't have to implement is_null/set_null but BpTree can still -// support the interface (and return false / assert when null -// is not supported). -template -struct NullableOrNothing { - static bool is_null(const Leaf& leaf, size_t ndx) - { - return leaf.is_null(ndx); - } - static void set_null(Leaf& leaf, size_t ndx) - { - leaf.set_null(ndx); - } -}; -template <> -struct NullableOrNothing { - static bool is_null(const ArrayInteger&, size_t) - { - return false; - } - static void set_null(ArrayInteger&, size_t) - { - REALM_ASSERT_RELEASE(false); - } -}; -} - -template -bool BpTree::is_null(size_t ndx) const noexcept -{ - if (root_is_leaf()) { - return _impl::NullableOrNothing::is_null(root_as_leaf(), ndx); - } - LeafType fallback(get_alloc()); - const LeafType* leaf; - LeafInfo leaf_info{&leaf, &fallback}; - size_t ndx_in_leaf; - get_leaf(ndx, ndx_in_leaf, leaf_info); - return _impl::NullableOrNothing::is_null(*leaf, ndx_in_leaf); -} - -template -T BpTree::get(size_t ndx) const noexcept -{ - REALM_ASSERT_DEBUG_EX(ndx < size(), ndx, size()); - if (root_is_leaf()) { - return root_as_leaf().get(ndx); - } - - // Use direct getter to avoid initializing leaf array: - std::pair p = root_as_node().get_bptree_leaf(ndx); - const char* leaf_header = p.first.get_addr(); - size_t ndx_in_leaf = p.second; - return LeafType::get(leaf_header, ndx_in_leaf); -} - -template -template -void BpTree::bptree_insert(size_t row_ndx, BpTreeNode::TreeInsert& state, size_t num_rows) -{ - ref_type new_sibling_ref; - for (size_t i = 0; i < num_rows; ++i) { - size_t row_ndx_2 = row_ndx == realm::npos ? realm::npos : row_ndx + i; - if (root_is_leaf()) { - REALM_ASSERT_DEBUG(row_ndx_2 == realm::npos || row_ndx_2 < REALM_MAX_BPNODE_SIZE); - new_sibling_ref = root_as_leaf().bptree_leaf_insert(row_ndx_2, state.m_value, state); - } - else { - if (row_ndx_2 == realm::npos) { - new_sibling_ref = root_as_node().bptree_append(state); // Throws - } - else { - new_sibling_ref = root_as_node().bptree_insert(row_ndx_2, state); // Throws - } - } - - if (REALM_UNLIKELY(new_sibling_ref)) { - bool is_append = row_ndx_2 == realm::npos; - introduce_new_root(new_sibling_ref, state, is_append); - } - } -} - -template -struct BpTree::LeafValueInserter { - using value_type = T; - T m_value; - LeafValueInserter(T value) - : m_value(std::move(value)) - { - } - - // TreeTraits concept: - static ref_type leaf_insert(MemRef leaf_mem, ArrayParent& parent, size_t ndx_in_parent, Allocator& alloc, - size_t ndx_in_leaf, BpTreeNode::TreeInsert& state) - { - LeafType leaf{alloc}; - leaf.init_from_mem(leaf_mem); - leaf.set_parent(&parent, ndx_in_parent); - // Should not move out of m_value, because the same inserter may be used to perform - // multiple insertions (for example, if num_rows > 1). - return leaf.bptree_leaf_insert(ndx_in_leaf, state.m_value, state); - } -}; - -template -struct BpTree::LeafNullInserter { - using value_type = null; - // TreeTraits concept: - static ref_type leaf_insert(MemRef leaf_mem, ArrayParent& parent, size_t ndx_in_parent, Allocator& alloc, - size_t ndx_in_leaf, BpTreeNode::TreeInsert& state) - { - LeafType leaf{alloc}; - leaf.init_from_mem(leaf_mem); - leaf.set_parent(&parent, ndx_in_parent); - return leaf.bptree_leaf_insert(ndx_in_leaf, null{}, state); - } -}; - -template -void BpTree::insert(size_t row_ndx, T value, size_t num_rows) -{ - REALM_ASSERT_DEBUG(row_ndx == npos || row_ndx < size()); - BpTreeNode::TreeInsert inserter; - inserter.m_value = std::move(value); - inserter.m_nullable = std::is_same>::value; // FIXME - bptree_insert(row_ndx, inserter, num_rows); // Throws -} - -template -struct BpTree::UpdateHandler : BpTreeNode::UpdateHandler { - LeafType m_leaf; - const T m_value; - UpdateHandler(BpTreeBase& tree, T value) noexcept - : m_leaf(tree.get_alloc()) - , m_value(std::move(value)) - { - } - void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t elem_ndx_in_leaf) override - { - m_leaf.init_from_mem(mem); - m_leaf.set_parent(parent, ndx_in_parent); - m_leaf.set(elem_ndx_in_leaf, m_value); // Throws - } -}; - -template -struct BpTree::SetNullHandler : BpTreeNode::UpdateHandler { - LeafType m_leaf; - SetNullHandler(BpTreeBase& tree) noexcept - : m_leaf(tree.get_alloc()) - { - } - void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t elem_ndx_in_leaf) override - { - m_leaf.init_from_mem(mem); - m_leaf.set_parent(parent, ndx_in_parent); - _impl::NullableOrNothing::set_null(m_leaf, elem_ndx_in_leaf); // Throws - } -}; - -template -void BpTree::set(size_t ndx, T value) -{ - if (root_is_leaf()) { - root_as_leaf().set(ndx, std::move(value)); - } - else { - UpdateHandler set_leaf_elem(*this, std::move(value)); - static_cast(m_root.get())->update_bptree_elem(ndx, set_leaf_elem); // Throws - } -} - -template -void BpTree::set_null(size_t ndx) -{ - if (root_is_leaf()) { - _impl::NullableOrNothing::set_null(root_as_leaf(), ndx); - } - else { - SetNullHandler set_leaf_elem(*this); - static_cast(m_root.get())->update_bptree_elem(ndx, set_leaf_elem); // Throws; - } -} - -template -struct BpTree::EraseHandler : BpTreeNode::EraseHandler { - BpTreeBase& m_tree; - LeafType m_leaf; - bool m_leaves_have_refs; // FIXME: Should be able to eliminate this. - EraseHandler(BpTreeBase& tree) noexcept - : m_tree(tree) - , m_leaf(tree.get_alloc()) - , m_leaves_have_refs(false) - { - } - bool erase_leaf_elem(MemRef leaf_mem, ArrayParent* parent, size_t leaf_ndx_in_parent, - size_t elem_ndx_in_leaf) override - { - m_leaf.init_from_mem(leaf_mem); - REALM_ASSERT_3(m_leaf.size(), >=, 1); - size_t last_ndx = m_leaf.size() - 1; - if (last_ndx == 0) { - m_leaves_have_refs = m_leaf.has_refs(); - return true; - } - m_leaf.set_parent(parent, leaf_ndx_in_parent); - size_t ndx = elem_ndx_in_leaf; - if (ndx == npos) - ndx = last_ndx; - m_leaf.erase(ndx); // Throws - return false; - } - void destroy_leaf(MemRef leaf_mem) noexcept override - { - // FIXME: Seems like this would cause file space leaks if - // m_leaves_have_refs is true, but consider carefully how - // m_leaves_have_refs get its value. - m_tree.get_alloc().free_(leaf_mem); - } - void replace_root_by_leaf(MemRef leaf_mem) override - { - std::unique_ptr leaf{new LeafType(m_tree.get_alloc())}; // Throws - leaf->init_from_mem(leaf_mem); - m_tree.replace_root(std::move(leaf)); // Throws - } - void replace_root_by_empty_leaf() override - { - std::unique_ptr leaf{new LeafType(m_tree.get_alloc())}; // Throws - leaf->create(m_leaves_have_refs ? Array::type_HasRefs : Array::type_Normal); // Throws - m_tree.replace_root(std::move(leaf)); // Throws - } -}; - -template -void BpTree::erase(size_t ndx, bool is_last) -{ - REALM_ASSERT_DEBUG_EX(ndx < size(), ndx, size()); - REALM_ASSERT_DEBUG(is_last == (ndx == size() - 1)); - if (root_is_leaf()) { - root_as_leaf().erase(ndx); - } - else { - size_t ndx_2 = is_last ? npos : ndx; - EraseHandler handler(*this); - BpTreeNode::erase_bptree_elem(&root_as_node(), ndx_2, handler); - } -} - -template -void BpTree::move_last_over(size_t row_ndx, size_t last_row_ndx) -{ - // Copy value from last row over - T value = get(last_row_ndx); - set(row_ndx, value); - erase(last_row_ndx, true); -} - -template -void BpTree::clear() -{ - if (root_is_leaf()) { - if (std::is_same::value && root().get_type() == Array::type_HasRefs) { - // FIXME: This is because some column types rely on integer columns - // to contain refs. - root().clear_and_destroy_children(); - } - else { - root_as_leaf().clear(); - } - } - else { - Allocator& alloc = get_alloc(); - root().destroy_deep(); - - std::unique_ptr new_root(new LeafType(alloc)); - new_root->create(); - replace_root(std::move(new_root)); - } -} - - -template -struct BpTree::AdjustHandler : BpTreeNode::UpdateHandler { - LeafType m_leaf; - const T m_diff; - AdjustHandler(BpTreeBase& tree, T diff) - : m_leaf(tree.get_alloc()) - , m_diff(diff) - { - } - - void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t) final - { - m_leaf.init_from_mem(mem); - m_leaf.set_parent(parent, ndx_in_parent); - m_leaf.adjust(0, m_leaf.size(), m_diff); - } -}; - -template -void BpTree::adjust(T diff) -{ - if (root_is_leaf()) { - root_as_leaf().adjust(0, m_root->size(), std::move(diff)); // Throws - } - else { - AdjustHandler adjust_leaf_elem(*this, std::move(diff)); - root_as_node().update_bptree_leaves(adjust_leaf_elem); // Throws - } -} - -template -void BpTree::adjust(size_t ndx, T diff) -{ - static_assert(std::is_arithmetic::value, "adjust is undefined for non-arithmetic trees"); - set(ndx, get(ndx) + diff); -} - -template -struct BpTree::AdjustGEHandler : BpTreeNode::UpdateHandler { - LeafType m_leaf; - const T m_limit, m_diff; - - AdjustGEHandler(BpTreeBase& tree, T limit, T diff) - : m_leaf(tree.get_alloc()) - , m_limit(limit) - , m_diff(diff) - { - } - - void update(MemRef mem, ArrayParent* parent, size_t ndx_in_parent, size_t) final - { - m_leaf.init_from_mem(mem); - m_leaf.set_parent(parent, ndx_in_parent); - m_leaf.adjust_ge(m_limit, m_diff); - } -}; - -template -void BpTree::adjust_ge(T limit, T diff) -{ - if (root_is_leaf()) { - root_as_leaf().adjust_ge(std::move(limit), std::move(diff)); // Throws - } - else { - AdjustGEHandler adjust_leaf_elem(*this, std::move(limit), std::move(diff)); - root_as_node().update_bptree_leaves(adjust_leaf_elem); // Throws - } -} - -template -struct BpTree::SliceHandler : public BpTreeBase::SliceHandler { -public: - SliceHandler(Allocator& alloc) - : m_leaf(alloc) - { - } - MemRef slice_leaf(MemRef leaf_mem, size_t offset, size_t size, Allocator& target_alloc) override - { - m_leaf.init_from_mem(leaf_mem); - return m_leaf.slice_and_clone_children(offset, size, target_alloc); // Throws - } - -private: - LeafType m_leaf; -}; - -template -ref_type BpTree::write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const -{ - ref_type ref; - if (root_is_leaf()) { - Allocator& alloc = Allocator::get_default(); - MemRef mem = root_as_leaf().slice_and_clone_children(slice_offset, slice_size, alloc); // Throws - Array slice(alloc); - _impl::DeepArrayDestroyGuard dg(&slice); - slice.init_from_mem(mem); - bool deep = true; - bool only_when_modified = false; - ref = slice.write(out, deep, only_when_modified); // Throws - } - else { - SliceHandler handler(get_alloc()); - ref = write_subtree(root_as_node(), slice_offset, slice_size, table_size, handler, out); // Throws - } - return ref; -} - -template -MemRef BpTree::create_leaf(Array::Type leaf_type, size_t size, T value, Allocator& alloc) -{ - bool context_flag = false; - MemRef mem = LeafType::create_array(leaf_type, context_flag, size, std::move(value), alloc); - return mem; -} - -template -void BpTree::get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf_info) const noexcept -{ - if (root_is_leaf()) { - ndx_in_leaf = ndx; - *inout_leaf_info.out_leaf = &root_as_leaf(); - return; - } - std::pair p = root_as_node().get_bptree_leaf(ndx); - inout_leaf_info.fallback->init_from_mem(p.first); - ndx_in_leaf = p.second; - *inout_leaf_info.out_leaf = inout_leaf_info.fallback; -} - -template -size_t BpTree::find_first(T value, size_t begin, size_t end) const -{ - if (root_is_leaf()) { - return root_as_leaf().find_first(value, begin, end); - } - - // FIXME: It would be better to always require that 'end' is - // specified explicitly, since Table has the size readily - // available, and Array::get_bptree_size() is deprecated. - if (end == npos) - end = size(); - - LeafType leaf_cache(get_alloc()); - size_t ndx_in_tree = begin; - while (ndx_in_tree < end) { - const LeafType* leaf; - LeafInfo leaf_info{&leaf, &leaf_cache}; - size_t ndx_in_leaf; - get_leaf(ndx_in_tree, ndx_in_leaf, leaf_info); - size_t leaf_offset = ndx_in_tree - ndx_in_leaf; - size_t end_in_leaf = std::min(leaf->size(), end - leaf_offset); - size_t ndx = leaf->find_first(value, ndx_in_leaf, end_in_leaf); // Throws (maybe) - if (ndx != not_found) - return leaf_offset + ndx; - ndx_in_tree = leaf_offset + end_in_leaf; - } - - return not_found; -} - -template -void BpTree::find_all(IntegerColumn& result, T value, size_t begin, size_t end) const -{ - if (root_is_leaf()) { - root_as_leaf().find_all(&result, value, 0, begin, end); // Throws - return; - } - - // FIXME: It would be better to always require that 'end' is - // specified explicitely, since Table has the size readily - // available, and Array::get_bptree_size() is deprecated. - if (end == npos) - end = size(); - - LeafType leaf_cache(get_alloc()); - size_t ndx_in_tree = begin; - while (ndx_in_tree < end) { - const LeafType* leaf; - LeafInfo leaf_info{&leaf, &leaf_cache}; - size_t ndx_in_leaf; - get_leaf(ndx_in_tree, ndx_in_leaf, leaf_info); - size_t leaf_offset = ndx_in_tree - ndx_in_leaf; - size_t end_in_leaf = std::min(leaf->size(), end - leaf_offset); - leaf->find_all(&result, value, leaf_offset, ndx_in_leaf, end_in_leaf); // Throws - ndx_in_tree = leaf_offset + end_in_leaf; - } -} - -#if defined(REALM_DEBUG) -template -size_t BpTree::verify_leaf(MemRef mem, Allocator& alloc) -{ - LeafType leaf(alloc); - leaf.init_from_mem(mem); - leaf.verify(); - return leaf.size(); -} - -template -void BpTree::verify() const -{ - if (root_is_leaf()) { - root_as_leaf().verify(); - } - else { - root().verify_bptree(&verify_leaf); - } -} -#endif // REALM_DEBUG - -template -void BpTree::leaf_to_dot(MemRef leaf_mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out, - Allocator& alloc) -{ - LeafType leaf(alloc); - leaf.init_from_mem(leaf_mem); - leaf.set_parent(parent, ndx_in_parent); - leaf.to_dot(out); -} - -} // namespace realm - -#endif // REALM_BPTREE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/chunked_binary.hpp b/Lesson14/Pods/Realm/include/core/realm/chunked_binary.hpp deleted file mode 100644 index 1e76fa8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/chunked_binary.hpp +++ /dev/null @@ -1,125 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_NOINST_CHUNKED_BINARY_HPP -#define REALM_NOINST_CHUNKED_BINARY_HPP - -#include -#include -#include - -#include -#include - - -namespace realm { - -/// ChunkedBinaryData manages a vector of BinaryData. It is used to facilitate -/// extracting large binaries from binary columns and tables. -class ChunkedBinaryData { -public: - - ChunkedBinaryData(); - ChunkedBinaryData(const BinaryData& bd); - ChunkedBinaryData(const BinaryIterator& bd); - ChunkedBinaryData(const BinaryColumn& col, size_t index); - - /// size() returns the number of bytes in the chunked binary. - /// FIXME: This operation is O(n). - size_t size() const noexcept; - - /// is_null returns true if the chunked binary has zero chunks or if - /// the first chunk points to the nullptr. - bool is_null() const; - - /// FIXME: O(n) - char operator[](size_t index) const; - - std::string hex_dump(const char* separator = " ", int min_digits = -1) const; - - void write_to(util::ResettableExpandableBufferOutputStream& out) const; - - /// copy_to() copies the chunked binary data to \a buffer of size - /// \a buffer_size starting at \a offset in the ChunkedBinary. - /// copy_to() copies until the end of \a buffer or the end of - /// the ChunkedBinary whichever comes first. - /// copy_to() returns the number of copied bytes. - size_t copy_to(char* buffer, size_t buffer_size, size_t offset) const; - - /// copy_to() allocates a buffer of size() in \a dest and - /// copies the chunked binary data to \a dest. - size_t copy_to(std::unique_ptr& dest) const; - - /// get_first_chunk() is used in situations - /// where it is known that there is exactly one - /// chunk. This is the case if the ChunkedBinary - /// has been constructed from BinaryData. - BinaryData get_first_chunk() const; - -private: - BinaryIterator m_begin; - friend class ChunkedBinaryInputStream; -}; - -// FIXME: When ChunkedBinaryData is moved into Core, this should be moved as well. -class ChunkedBinaryInputStream : public _impl::NoCopyInputStream { -public: - explicit ChunkedBinaryInputStream(const ChunkedBinaryData& chunks) - : m_it(chunks.m_begin) - { - } - - bool next_block(const char*& begin, const char*& end) override - { - BinaryData block = m_it.get_next(); - begin = block.data(); - end = begin + block.size(); - return begin != end; - } - -private: - BinaryIterator m_it; -}; - - -/// Implementation: - - -inline ChunkedBinaryData::ChunkedBinaryData() -{ -} - -inline ChunkedBinaryData::ChunkedBinaryData(const BinaryData& bd) : m_begin{bd} -{ -} - -inline ChunkedBinaryData::ChunkedBinaryData(const BinaryIterator& bd) : m_begin{bd} -{ -} - -inline ChunkedBinaryData::ChunkedBinaryData(const BinaryColumn& col, size_t index) - : m_begin{&col, index} -{ -} - - -} // namespace realm - -#endif // REALM_NOINST_CHUNKED_BINARY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column.hpp b/Lesson14/Pods/Realm/include/core/realm/column.hpp deleted file mode 100644 index eda8ca2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column.hpp +++ /dev/null @@ -1,1897 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_HPP -#define REALM_COLUMN_HPP - -#include // unint8_t etc -#include // size_t -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - - -// Pre-definitions -struct CascadeState; -class StringIndex; - -template -struct ImplicitNull; - -template -struct ImplicitNull> { - static constexpr bool value = true; -}; - -template <> -struct ImplicitNull { - static constexpr bool value = false; -}; - -template <> -struct ImplicitNull { - static constexpr bool value = true; -}; - -template <> -struct ImplicitNull { - static constexpr bool value = true; -}; - -// FIXME: Add specialization for ImplicitNull for float, double, StringData, BinaryData. - -template -R aggregate(const ColType& column, T target, size_t start, size_t end, size_t limit, size_t* return_ndx); - - -// Iterator with random access for Columns -template -class ColumnRandIterator : public std::iterator { -public: - ColumnRandIterator(const Column* src_col, size_t ndx = 0); - bool operator==(const ColumnRandIterator& rhs) const; - bool operator!=(const ColumnRandIterator& rhs) const; - bool operator<(const ColumnRandIterator& rhs) const; - bool operator>(const ColumnRandIterator& rhs) const; - bool operator<=(const ColumnRandIterator& rhs) const; - bool operator>=(const ColumnRandIterator& rhs) const; - ColumnRandIterator& operator+=(ptrdiff_t movement); - ColumnRandIterator& operator-=(ptrdiff_t movement); - ColumnRandIterator& operator++(); - ColumnRandIterator& operator--(); - ColumnRandIterator operator++(int); - ColumnRandIterator operator--(int); - ColumnRandIterator operator+(ptrdiff_t movement); - ColumnRandIterator operator-(ptrdiff_t movement); - ptrdiff_t operator-(const ColumnRandIterator& right) const; - const ColumnDataType operator*() const; - const ColumnDataType operator->() const; - const ColumnDataType operator[](ptrdiff_t offset) const; - size_t get_col_ndx() const; - -protected: - size_t m_col_ndx; - const Column* m_col; -}; - -/// Base class for all column types. -class ColumnBase { -public: - /// Get the number of entries in this column. This operation is relatively - /// slow. - virtual size_t size() const noexcept = 0; - - /// \throw LogicError Thrown if this column is not string valued. - virtual void set_string(size_t row_ndx, StringData value); - - /// Whether or not this column is nullable. - virtual bool is_nullable() const noexcept; - - /// Whether or not the value at \a row_ndx is NULL. If the column is not - /// nullable, always returns false. - virtual bool is_null(size_t row_ndx) const noexcept; - - /// Sets the value at \a row_ndx to be NULL. - /// \throw LogicError Thrown if this column is not nullable. - virtual void set_null(size_t row_ndx); - - /// Inserts the specified number of elements into this column - /// starting at the specified row index. The new elements will have the - /// default value for the column type. - /// - /// \param row_ndx The row to start insertion at. If the row_ndx is less - /// than prior_num_rows then previous rows from row_ndx onwards will be - /// moved ahead by num_rows_to_insert. - /// - /// \param num_rows_to_insert The number of rows to insert. There is no - /// restriction on this value. - /// - /// \param prior_num_rows The number of elements in this column prior to the - /// modification. - /// - /// \param nullable Specifies whether or not this column is nullable. This - /// function may assert if nullable does not agree with \a is_nullable() - virtual void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) = 0; - - /// Removes the specified number of consecutive elements from - /// this column, starting at the specified row index. - /// - /// \param row_ndx The row to start removal at (inclusive). This must be - /// less than prior_num_rows. - /// - /// \param num_rows_to_erase The number of rows to erase. - /// The row_ndx + num_rows_to_erase must be less than prior_num_rows. - /// - /// \param prior_num_rows The number of elements in this column prior to the - /// modification. - /// - /// \param broken_reciprocal_backlinks If true, link columns must assume - /// that reciprocal backlinks have already been removed. Non-link columns - /// should ignore this argument. - virtual void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, - bool broken_reciprocal_backlinks) = 0; - - /// Removes the element at the specified row index by - /// moving the element at the last row index over it. This reduces the - /// number of elements by one. - /// - /// \param row_ndx The row to erase. Must be less than prior_num_rows. - /// - /// \param prior_num_rows The number of elements in this column prior to the - /// modification. - /// - /// \param broken_reciprocal_backlinks If true, link columns must assume - /// that reciprocal backlinks have already been removed. Non-link columns - /// should ignore this argument. - virtual void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) = 0; - - /// Remove all elements from this column. - /// - /// \param num_rows The total number of rows in this column. - /// - /// \param broken_reciprocal_backlinks If true, link columns must assume - /// that reciprocal backlinks have already been removed. Non-link columns - /// should ignore this argument. - virtual void clear(size_t num_rows, bool broken_reciprocal_backlinks) = 0; - - /// \brief Swap the elements at the specified indices. - /// - /// Behaviour is undefined if: - /// - \a row_ndx_1 or \a row_ndx_2 point to an invalid element (out-of - /// bounds) - /// - \a row_ndx_1 and \a row_ndx_2 point to the same value - virtual void swap_rows(size_t row_ndx_1, size_t row_ndx_2) = 0; - - virtual void destroy() noexcept = 0; - void move_assign(ColumnBase& col) noexcept; - - virtual ~ColumnBase() noexcept - { - } - - // Disable copying, this is not supported. - ColumnBase& operator=(const ColumnBase&) = delete; - ColumnBase(const ColumnBase&) = delete; - - // Getter function for index. For integer index, the caller must supply a - // buffer that we can store the extracted value in (it may be bitpacked, so - // we cannot return a pointer in to the Array as we do with String index). - virtual StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept = 0; - - // Search index - virtual bool supports_search_index() const noexcept; - virtual bool has_search_index() const noexcept; - virtual StringIndex* create_search_index(); - virtual void destroy_search_index() noexcept; - virtual const StringIndex* get_search_index() const noexcept; - virtual StringIndex* get_search_index() noexcept; - virtual void set_search_index_ref(ref_type, ArrayParent*, size_t ndx_in_parent); - - virtual Allocator& get_alloc() const noexcept = 0; - - /// Returns the 'ref' of the root array. - virtual ref_type get_ref() const noexcept = 0; - virtual MemRef get_mem() const noexcept = 0; - - virtual void replace_root_array(std::unique_ptr leaf) = 0; - virtual MemRef clone_deep(Allocator& alloc) const = 0; - virtual void detach(void) = 0; - virtual bool is_attached(void) const noexcept = 0; - - static size_t get_size_from_type_and_ref(ColumnType, ref_type, Allocator&, bool) noexcept; - - // These assume that the right column compile-time type has been - // figured out. - static size_t get_size_from_ref(ref_type root_ref, Allocator&); - static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator&); - - /// Write a slice of this column to the specified output stream. - virtual ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const = 0; - - /// Get this column's logical index within the containing table, or npos - /// for free-standing or non-top-level columns. - size_t get_column_index() const noexcept - { - return m_column_ndx; - } - - virtual void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept = 0; - virtual size_t get_ndx_in_parent() const noexcept = 0; - virtual void set_ndx_in_parent(size_t ndx_in_parent) noexcept = 0; - - /// Called to update refs and memory pointers of this column accessor and - /// all its nested accessors, but only in cases where the logical contents - /// in strictly unchanged. Group::commit(), and - /// SharedGroup::commit_and_continue_as_read()() are examples of such - /// cases. In both those cases, the purpose is to keep user visible - /// accessors in a valid state across a commit. - virtual void update_from_parent(size_t old_baseline) noexcept = 0; - - //@{ - - /// cascade_break_backlinks_to() is called iteratively for each column by - /// Table::cascade_break_backlinks_to() with the same arguments as are - /// passed to Table::cascade_break_backlinks_to(). Link columns must - /// override it. The same is true for cascade_break_backlinks_to_all_rows(), - /// except that it is called from - /// Table::cascade_break_backlinks_to_all_rows(), and that it expects - /// Table::cascade_break_backlinks_to_all_rows() to pass the number of rows - /// in the table as \a num_rows. - - virtual void cascade_break_backlinks_to(size_t row_ndx, CascadeState&); - virtual void cascade_break_backlinks_to_all_rows(size_t num_rows, CascadeState&); - - //@} - - void discard_child_accessors() noexcept; - - /// For columns that are able to contain subtables, this function returns - /// the pointer to the subtable accessor at the specified row index if it - /// exists, otherwise it returns null. For other column types, this function - /// returns null. - virtual TableRef get_subtable_accessor(size_t row_ndx) const noexcept; - - /// Detach and remove the subtable accessor at the specified row if it - /// exists. For column types that are unable to contain subtable, this - /// function does nothing. - virtual void discard_subtable_accessor(size_t row_ndx) noexcept; - - virtual void adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; - virtual void adj_acc_erase_row(size_t row_ndx) noexcept; - /// See Table::adj_acc_move_over() - virtual void adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - virtual void adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; - virtual void adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; - virtual void adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; - virtual void adj_acc_clear_root_table() noexcept; - - enum { - mark_Recursive = 0x01, - mark_LinkTargets = 0x02, - mark_LinkOrigins = 0x04, - }; - - virtual void mark(int type) noexcept; - - virtual void bump_link_origin_table_version() noexcept; - - virtual int compare_values(size_t row1, size_t row2) const noexcept = 0; - - /// Refresh the dirty part of the accessor subtree rooted at this column - /// accessor. - /// - /// The following conditions are necessary and sufficient for the proper - /// operation of this function: - /// - /// - The parent table accessor (excluding its column accessors) is in a - /// valid state (already refreshed). - /// - /// - Every subtable accessor in the subtree is marked dirty if it needs to - /// be refreshed, or if it has a descendant accessor that needs to be - /// refreshed. - /// - /// - This column accessor, as well as all its descendant accessors, are in - /// structural correspondence with the underlying node hierarchy whose - /// root ref is stored in the parent (`Table::m_columns`) (see - /// AccessorConsistencyLevels). - /// - /// - The 'index in parent' property of the cached root array - /// (`root->m_ndx_in_parent`) is valid. - virtual void refresh_accessor_tree(size_t new_col_ndx, const Spec&); - - virtual void verify() const = 0; - virtual void verify(const Table&, size_t col_ndx) const; - virtual void to_dot(std::ostream&, StringData title = StringData()) const = 0; - virtual void do_dump_node_structure(std::ostream&, int level) const = 0; - -#ifdef REALM_DEBUG - void dump_node_structure() const; // To std::cerr (for GDB) - void bptree_to_dot(const Array* root, std::ostream& out) const; -#endif - -protected: - using SliceHandler = BpTreeBase::SliceHandler; - - ColumnBase(size_t column_ndx = npos) - : m_column_ndx(column_ndx) - { - } - ColumnBase(ColumnBase&&) = default; - - // Must not assume more than minimal consistency (see - // AccessorConsistencyLevels). - virtual void do_discard_child_accessors() noexcept - { - } - - //@{ - /// \tparam L Any type with an appropriate `value_type`, %size(), - /// and %get() members. - template - size_t lower_bound(const L& list, T value) const noexcept; - - template - size_t upper_bound(const L& list, T value) const noexcept; - //@} - - // Node functions - - class CreateHandler { - public: - virtual ref_type create_leaf(size_t size) = 0; - ~CreateHandler() noexcept - { - } - }; - - static ref_type create(Allocator&, size_t size, CreateHandler&); - - class LeafToDot; - virtual void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const = 0; - - template - static int compare_values(const Column* column, size_t row1, size_t row2) noexcept; - -private: - size_t m_column_ndx = npos; - - static ref_type build(size_t* rest_size_ptr, size_t fixed_height, Allocator&, CreateHandler&); -}; - - -// FIXME: Temporary class until all column types have been migrated to use BpTree interface -class ColumnBaseSimple : public ColumnBase { -public: - //@{ - /// Returns the array node at the root of this column, but note - /// that there is no guarantee that this node is an inner B+-tree - /// node or a leaf. This is the case for a MixedColumn in - /// particular. - Array* get_root_array() noexcept - { - return m_array.get(); - } - const Array* get_root_array() const noexcept - { - return m_array.get(); - } - //@} - - Allocator& get_alloc() const noexcept final - { - return m_array->get_alloc(); - } - void destroy() noexcept override - { - if (m_array) - m_array->destroy_deep(); - } - ref_type get_ref() const noexcept final - { - return m_array->get_ref(); - } - MemRef get_mem() const noexcept final - { - return m_array->get_mem(); - } - void detach() noexcept final - { - m_array->detach(); - } - bool is_attached() const noexcept final - { - return m_array->is_attached(); - } - void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept final - { - m_array->set_parent(parent, ndx_in_parent); - } - size_t get_ndx_in_parent() const noexcept final - { - return m_array->get_ndx_in_parent(); - } - void set_ndx_in_parent(size_t ndx_in_parent) noexcept override - { - m_array->set_ndx_in_parent(ndx_in_parent); - } - void update_from_parent(size_t old_baseline) noexcept override - { - m_array->update_from_parent(old_baseline); - } - MemRef clone_deep(Allocator& alloc) const override - { - return m_array->clone_deep(alloc); - } - -protected: - ColumnBaseSimple(size_t column_ndx) - : ColumnBase(column_ndx) - { - } - ColumnBaseSimple(Array* root) - : m_array(root) - { - } - std::unique_ptr m_array; - - void replace_root_array(std::unique_ptr new_root) final; - bool root_is_leaf() const noexcept - { - return !m_array->is_inner_bptree_node(); - } - - /// Introduce a new root node which increments the height of the - /// tree by one. - void introduce_new_root(ref_type new_sibling_ref, TreeInsertBase& state, bool is_append); - - static ref_type write(const Array* root, size_t slice_offset, size_t slice_size, size_t table_size, SliceHandler&, - _impl::OutputStream&); - -#if defined(REALM_DEBUG) - void tree_to_dot(std::ostream&) const; -#endif -}; - -class ColumnBaseWithIndex : public ColumnBase { -public: - ~ColumnBaseWithIndex() noexcept override - { - } - void set_ndx_in_parent(size_t ndx) noexcept override; - void update_from_parent(size_t old_baseline) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - void move_assign(ColumnBaseWithIndex& col) noexcept; - void destroy() noexcept override; - - virtual bool supports_search_index() const noexcept override - { - return true; - } - bool has_search_index() const noexcept final - { - return bool(m_search_index); - } - StringIndex* get_search_index() noexcept final - { - return m_search_index.get(); - } - const StringIndex* get_search_index() const noexcept final - { - return m_search_index.get(); - } - void destroy_search_index() noexcept override; - void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent) final; - StringIndex* create_search_index() override = 0; - -protected: - using ColumnBase::ColumnBase; - ColumnBaseWithIndex(ColumnBaseWithIndex&&) = default; - std::unique_ptr m_search_index; -}; - - -/// A column (Column) is a single B+-tree, and the root of -/// the column is the root of the B+-tree. All leaf nodes are arrays. -template -class Column : public ColumnBaseWithIndex { -public: - using value_type = T; - using LeafInfo = typename BpTree::LeafInfo; - using LeafType = typename BpTree::LeafType; - - static constexpr bool nullable = ImplicitNull::value; - - struct unattached_root_tag { - }; - - explicit Column() noexcept - : ColumnBaseWithIndex(npos) - , m_tree(Allocator::get_default()) - { - } - REALM_DEPRECATED("Initialize with ref instead") explicit Column(std::unique_ptr root) noexcept; - Column(Allocator&, ref_type, size_t column_ndx = npos); - Column(unattached_root_tag, Allocator&); - Column(Column&&) noexcept = default; - ~Column() noexcept override; - - void init_from_parent(); - void init_from_ref(Allocator&, ref_type); - void init_from_mem(Allocator&, MemRef); - // Accessor concept: - void destroy() noexcept override; - Allocator& get_alloc() const noexcept final; - ref_type get_ref() const noexcept final; - MemRef get_mem() const noexcept final; - void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override; - size_t get_ndx_in_parent() const noexcept final; - void set_ndx_in_parent(size_t ndx) noexcept final; - void update_from_parent(size_t old_baseline) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - void detach() noexcept final; - bool is_attached() const noexcept final; - MemRef clone_deep(Allocator&) const override; - - void move_assign(Column&); - - static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) - { - return ColumnBase::get_size_from_ref(root_ref, alloc); - } - - size_t size() const noexcept override; - bool is_empty() const noexcept - { - return size() == 0; - } - bool is_nullable() const noexcept override; - - /// Provides access to the leaf that contains the element at the - /// specified index. Upon return \a ndx_in_leaf will be set to the - /// corresponding index relative to the beginning of the leaf. - /// - /// LeafInfo is a struct defined by the underlying BpTree - /// data structure, that provides a way for the caller to do - /// leaf caching without instantiating too many objects along - /// the way. - /// - /// This function cannot be used for modifying operations as it - /// does not ensure the presence of an unbroken chain of parent - /// accessors. For this reason, the identified leaf should always - /// be accessed through the returned const-qualified reference, - /// and never directly through the specfied fallback accessor. - void get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf) const noexcept; - - // Getting and setting values - T get(size_t ndx) const noexcept; - bool is_null(size_t ndx) const noexcept override; - T back() const noexcept; - void set(size_t, T value); - void set_null(size_t) override; - void add(T value = T{}); - void insert(size_t ndx, T value = T{}, size_t num_rows = 1); - void erase(size_t row_ndx); - void erase(size_t row_ndx, bool is_last); - void move_last_over(size_t row_ndx, size_t last_row_ndx); - void clear(); - - // Index support - StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept override; - - // FIXME: Remove these - uint64_t get_uint(size_t ndx) const noexcept; - ref_type get_as_ref(size_t ndx) const noexcept; - void set_uint(size_t ndx, uint64_t value); - void set_as_ref(size_t ndx, ref_type value); - - template - void adjust(size_t ndx, U diff); - - template - void adjust(U diff); - - template - void adjust_ge(T limit, U diff); - - size_t count(T target) const; - - typename ColumnTypeTraits::sum_type sum(size_t start = 0, size_t end = npos, size_t limit = npos, - size_t* return_ndx = nullptr) const; - - typename ColumnTypeTraits::minmax_type maximum(size_t start = 0, size_t end = npos, size_t limit = npos, - size_t* return_ndx = nullptr) const; - - typename ColumnTypeTraits::minmax_type minimum(size_t start = 0, size_t end = npos, size_t limit = npos, - size_t* return_ndx = nullptr) const; - - double average(size_t start = 0, size_t end = npos, size_t limit = npos, size_t* return_ndx = nullptr) const; - - size_t find_first(T value, size_t begin = 0, size_t end = npos) const; - void find_all(Column& out_indices, T value, size_t begin = 0, size_t end = npos) const; - - void populate_search_index(); - StringIndex* create_search_index() override; - inline bool supports_search_index() const noexcept override - { - if (realm::is_any::value) - return false; - else - return true; - } - - - //@{ - /// Find the lower/upper bound for the specified value assuming - /// that the elements are already sorted in ascending order - /// according to ordinary integer comparison. - size_t lower_bound(T value) const noexcept; - size_t upper_bound(T value) const noexcept; - //@} - - using const_iterator = ColumnRandIterator; - - const_iterator cbegin() const - { - return const_iterator(this, 0); // `this` is const in a const method - } - const_iterator cend() const - { - return const_iterator(this, size()); - } - - size_t find_gte(T target, size_t start) const; - - bool compare(const Column&) const noexcept; - int compare_values(size_t row1, size_t row2) const noexcept override; - - static ref_type create(Allocator&, Array::Type leaf_type = Array::type_Normal, size_t size = 0, T value = T{}); - - // Overriding method in ColumnBase - ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - - /// \brief Swap the elements at the specified indices. - /// - /// If this \c Column has a search index defined, it will be updated to - /// reflect the changes induced by the swap. - /// - /// Behaviour is undefined if: - /// - \a row_ndx_1 or \a row_ndx_2 point to an invalid element (out-of - /// bounds) - /// - \a row_ndx_1 and \a row_ndx_2 point to the same value - void swap_rows(size_t, size_t) override; - void clear(size_t, bool) override; - - /// \param row_ndx Must be `realm::npos` if appending. - /// \param value The value to store at the specified row. - /// \param num_rows The number of rows to insert. - void insert_without_updating_index(size_t row_ndx, T value, size_t num_rows); - - void verify() const override; - void to_dot(std::ostream&, StringData title) const override; - void do_dump_node_structure(std::ostream&, int) const override; -#ifdef REALM_DEBUG - using ColumnBase::verify; - void tree_to_dot(std::ostream&) const; - MemStats stats() const; -#endif - - //@{ - /// Returns the array node at the root of this column, but note - /// that there is no guarantee that this node is an inner B+-tree - /// node or a leaf. This is the case for a MixedColumn in - /// particular. - Array* get_root_array() noexcept - { - return &m_tree.root(); - } - const Array* get_root_array() const noexcept - { - return &m_tree.root(); - } - //@} - -protected: - bool root_is_leaf() const noexcept - { - return m_tree.root_is_leaf(); - } - void replace_root_array(std::unique_ptr leaf) final - { - m_tree.replace_root(std::move(leaf)); - } - - void set_without_updating_index(size_t row_ndx, T value); - void erase_without_updating_index(size_t row_ndx, bool is_last); - void move_last_over_without_updating_index(size_t row_ndx, size_t last_row_ndx); - void swap_rows_without_updating_index(size_t row_ndx_1, size_t row_ndx_2); - - /// If any element points to an array node, this function recursively - /// destroys that array node. Note that the same is **not** true for - /// IntegerColumn::do_erase() and IntegerColumn::do_move_last_over(). - /// - /// FIXME: Be careful, clear_without_updating_index() currently forgets - /// if the leaf type is Array::type_HasRefs. - void clear_without_updating_index(); - - void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; -#ifdef REALM_DEBUG - static void dump_node_structure(const Array& root, std::ostream&, int level); -#endif - std::pair get_to_dot_parent(size_t ndx_in_parent) const; - -private: - class EraseLeafElem; - class CreateHandler; - class SliceHandler; - - friend class Array; - friend class ColumnBase; - friend class StringIndex; - - BpTree m_tree; - - void do_erase(size_t row_ndx, size_t num_rows_to_erase, bool is_last); -}; - -// Implementation: - - -template <> -inline size_t IntNullColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) -{ - // FIXME: Speed improvement possible by not creating instance, but tricky! This slow method is OK so far - // because it's only invoked by Table::get_size_from_ref() which is only used for subtables which we - // currently 2016) do not expose publicly. - IntNullColumn inc(alloc, root_ref); - return inc.size(); -} - - -inline bool ColumnBase::supports_search_index() const noexcept -{ - REALM_ASSERT(!has_search_index()); - return false; -} - -inline bool ColumnBase::has_search_index() const noexcept -{ - return get_search_index() != nullptr; -} - -inline StringIndex* ColumnBase::create_search_index() -{ - return nullptr; -} - -inline void ColumnBase::destroy_search_index() noexcept -{ -} - -inline const StringIndex* ColumnBase::get_search_index() const noexcept -{ - return nullptr; -} - -inline StringIndex* ColumnBase::get_search_index() noexcept -{ - return nullptr; -} - -inline void ColumnBase::set_search_index_ref(ref_type, ArrayParent*, size_t) -{ -} - -inline void ColumnBase::discard_child_accessors() noexcept -{ - do_discard_child_accessors(); -} - -inline void ColumnBase::discard_subtable_accessor(size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_insert_rows(size_t, size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_erase_row(size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_move_over(size_t, size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_swap_rows(size_t, size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_move_row(size_t, size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_merge_rows(size_t, size_t) noexcept -{ - // Noop -} - -inline void ColumnBase::adj_acc_clear_root_table() noexcept -{ - // Noop -} - -inline void ColumnBase::mark(int) noexcept -{ - // Noop -} - -inline void ColumnBase::bump_link_origin_table_version() noexcept -{ - // Noop -} - -template -int ColumnBase::compare_values(const Column* column, size_t row1, size_t row2) noexcept -{ - // we negate nullability such that the two ternary statements in this method can look identical to reduce - // risk of bugs - bool v1 = !column->is_null(row1); - bool v2 = !column->is_null(row2); - - if (!v1 || !v2) - return v1 == v2 ? 0 : v1 < v2 ? 1 : -1; - - auto a = column->get(row1); - auto b = column->get(row2); - return a == b ? 0 : a < b ? 1 : -1; -} - -namespace _impl { -template struct IntTypeForSize; -template <> struct IntTypeForSize<1> { using type = uint8_t; }; -template <> struct IntTypeForSize<2> { using type = uint16_t; }; -template <> struct IntTypeForSize<4> { using type = uint32_t; }; -template <> struct IntTypeForSize<8> { using type = uint64_t; }; - -template -int compare_float(Float a_raw, Float b_raw) -{ - bool a_nan = std::isnan(a_raw); - bool b_nan = std::isnan(b_raw); - if (!a_nan && !b_nan) { - // Just compare as IEEE floats - return a_raw == b_raw ? 0 : a_raw < b_raw ? 1 : -1; - } - if (a_nan && b_nan) { - // Compare the nan values (including nulls) as unsigned - using IntType = typename _impl::IntTypeForSize::type; - IntType a = 0, b = 0; - memcpy(&a, &a_raw, sizeof(Float)); - memcpy(&b, &b_raw, sizeof(Float)); - return a == b ? 0 : a < b ? 1 : -1; - } - // One is nan, the other is not - // nans are treated as being less than all non-nan values - return a_nan ? 1 : -1; -} -} // namespace _impl - -template <> -inline int ColumnBase::compare_values>(const Column* column, size_t row1, size_t row2) noexcept -{ - return _impl::compare_float(column->get(row1), column->get(row2)); -} - -template <> -inline int ColumnBase::compare_values>(const Column* column, size_t row1, size_t row2) noexcept -{ - return _impl::compare_float(column->get(row1), column->get(row2)); -} - -template -void Column::set_without_updating_index(size_t ndx, T value) -{ - m_tree.set(ndx, std::move(value)); -} - -template -void Column::set(size_t ndx, T value) -{ - REALM_ASSERT_DEBUG(ndx < size()); - if (has_search_index()) { - m_search_index->set(ndx, value); - } - set_without_updating_index(ndx, std::move(value)); -} - -template -void Column::set_null(size_t ndx) -{ - REALM_ASSERT_DEBUG(ndx < size()); - if (!is_nullable()) { - throw LogicError{LogicError::column_not_nullable}; - } - if (has_search_index()) { - m_search_index->set(ndx, null{}); - } - m_tree.set_null(ndx); -} - -// When a value of a signed type is converted to an unsigned type, the C++ standard guarantees that negative values -// are converted from the native representation to 2's complement, but the opposite conversion is left as undefined. -// realm::util::from_twos_compl() is used here to perform the correct opposite unsigned-to-signed conversion, -// which reduces to a no-op when 2's complement is the native representation of negative values. -template -void Column::set_uint(size_t ndx, uint64_t value) -{ - set(ndx, util::from_twos_compl(value)); -} - -template -void Column::set_as_ref(size_t ndx, ref_type ref) -{ - set(ndx, from_ref(ref)); -} - -template -template -void Column::adjust(size_t ndx, U diff) -{ - REALM_ASSERT_3(ndx, <, size()); - m_tree.adjust(ndx, diff); -} - -template -template -void Column::adjust(U diff) -{ - m_tree.adjust(diff); -} - -template -template -void Column::adjust_ge(T limit, U diff) -{ - m_tree.adjust_ge(limit, diff); -} - -template -size_t Column::count(T target) const -{ - if (has_search_index()) { - return m_search_index->count(target); - } - return to_size_t(aggregate(*this, target, 0, size(), npos, nullptr)); -} - -template -typename ColumnTypeTraits::sum_type Column::sum(size_t start, size_t end, size_t limit, - size_t* return_ndx) const -{ - using sum_type = typename ColumnTypeTraits::sum_type; - if (nullable) - return aggregate(*this, 0, start, end, limit, return_ndx); - else - return aggregate(*this, 0, start, end, limit, return_ndx); -} - -template -double Column::average(size_t start, size_t end, size_t limit, size_t* return_ndx) const -{ - if (end == size_t(-1)) - end = size(); - - auto s = sum(start, end, limit); - size_t cnt = to_size_t(aggregate(*this, 0, start, end, limit, nullptr)); - if (return_ndx) - *return_ndx = cnt; - double avg = double(s) / (cnt == 0 ? 1 : cnt); - return avg; -} - -template -typename ColumnTypeTraits::minmax_type Column::minimum(size_t start, size_t end, size_t limit, - size_t* return_ndx) const -{ - using R = typename ColumnTypeTraits::minmax_type; - return aggregate(*this, 0, start, end, limit, return_ndx); -} - -template -typename ColumnTypeTraits::minmax_type Column::maximum(size_t start, size_t end, size_t limit, - size_t* return_ndx) const -{ - using R = typename ColumnTypeTraits::minmax_type; - return aggregate(*this, 0, start, end, limit, return_ndx); -} - -template -void Column::get_leaf(size_t ndx, size_t& ndx_in_leaf, LeafInfo& inout_leaf_info) const noexcept -{ - m_tree.get_leaf(ndx, ndx_in_leaf, inout_leaf_info); -} - -template -StringData Column::get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept -{ - T x = get(ndx); - return to_str(x, buffer); -} - -template -void Column::populate_search_index() -{ - REALM_ASSERT(has_search_index()); - // Populate the index - size_t num_rows = size(); - for (size_t row_ndx = 0; row_ndx != num_rows; ++row_ndx) { - bool is_append = true; - if (is_null(row_ndx)) { - m_search_index->insert(row_ndx, null{}, 1, is_append); // Throws - } - else { - T value = get(row_ndx); - m_search_index->insert(row_ndx, value, 1, is_append); // Throws - } - } -} - -template -StringIndex* Column::create_search_index() -{ - if (realm::is_any::value) - return nullptr; - - REALM_ASSERT(!has_search_index()); - REALM_ASSERT(supports_search_index()); - m_search_index.reset(new StringIndex(this, get_alloc())); // Throws - populate_search_index(); - return m_search_index.get(); -} - -template -size_t Column::find_first(T value, size_t begin, size_t end) const -{ - REALM_ASSERT_3(begin, <=, size()); - REALM_ASSERT(end == npos || (begin <= end && end <= size())); - - if (m_search_index && begin == 0 && end == npos) - return m_search_index->find_first(value); - return m_tree.find_first(value, begin, end); -} - -template -void Column::find_all(IntegerColumn& result, T value, size_t begin, size_t end) const -{ - REALM_ASSERT_3(begin, <=, size()); - REALM_ASSERT(end == npos || (begin <= end && end <= size())); - - if (m_search_index && begin == 0 && end == npos) - return m_search_index->find_all(result, value); - return m_tree.find_all(result, value, begin, end); -} - -inline size_t ColumnBase::get_size_from_ref(ref_type root_ref, Allocator& alloc) -{ - const char* root_header = alloc.translate(root_ref); - bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); - if (root_is_leaf) - return Array::get_size_from_header(root_header); - return BpTreeNode::get_bptree_size_from_header(root_header); -} - -template -size_t ColumnBase::lower_bound(const L& list, T value) const noexcept -{ - size_t i = 0; - size_t list_size = list.size(); - while (0 < list_size) { - size_t half = list_size / 2; - size_t mid = i + half; - typename L::value_type probe = list.get(mid); - if (probe < value) { - i = mid + 1; - list_size -= half + 1; - } - else { - list_size = half; - } - } - return i; -} - -template -size_t ColumnBase::upper_bound(const L& list, T value) const noexcept -{ - size_t i = 0; - size_t list_size = list.size(); - while (0 < list_size) { - size_t half = list_size / 2; - size_t mid = i + half; - typename L::value_type probe = list.get(mid); - if (!(value < probe)) { - i = mid + 1; - list_size -= half + 1; - } - else { - list_size = half; - } - } - return i; -} - - -inline ref_type ColumnBase::create(Allocator& alloc, size_t column_size, CreateHandler& handler) -{ - size_t rest_size = column_size; - size_t fixed_height = 0; // Not fixed - return build(&rest_size, fixed_height, alloc, handler); -} - -template -Column::Column(Allocator& alloc, ref_type ref, size_t column_ndx) - : ColumnBaseWithIndex(column_ndx) - , m_tree(BpTreeBase::unattached_tag{}) -{ - // fixme, must m_search_index be copied here? - m_tree.init_from_ref(alloc, ref); -} - -template -Column::Column(unattached_root_tag, Allocator& alloc) - : ColumnBaseWithIndex(npos) - , m_tree(alloc) -{ -} - -template -Column::Column(std::unique_ptr root) noexcept - : m_tree(std::move(root)) -{ -} - -template -Column::~Column() noexcept -{ -} - -template -void Column::init_from_parent() -{ - m_tree.init_from_parent(); -} - -template -void Column::init_from_ref(Allocator& alloc, ref_type ref) -{ - m_tree.init_from_ref(alloc, ref); -} - -template -void Column::init_from_mem(Allocator& alloc, MemRef mem) -{ - m_tree.init_from_mem(alloc, mem); -} - -template -void Column::destroy() noexcept -{ - ColumnBaseWithIndex::destroy(); - m_tree.destroy(); -} - -template -void Column::move_assign(Column& col) -{ - ColumnBaseWithIndex::move_assign(col); - m_tree = std::move(col.m_tree); -} - -template -Allocator& Column::get_alloc() const noexcept -{ - return m_tree.get_alloc(); -} - -template -void Column::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept -{ - m_tree.set_parent(parent, ndx_in_parent); -} - -template -size_t Column::get_ndx_in_parent() const noexcept -{ - return m_tree.get_ndx_in_parent(); -} - -template -void Column::set_ndx_in_parent(size_t ndx_in_parent) noexcept -{ - ColumnBaseWithIndex::set_ndx_in_parent(ndx_in_parent); - m_tree.set_ndx_in_parent(ndx_in_parent); -} - -template -void Column::detach() noexcept -{ - m_tree.detach(); -} - -template -bool Column::is_attached() const noexcept -{ - return m_tree.is_attached(); -} - -template -ref_type Column::get_ref() const noexcept -{ - return get_root_array()->get_ref(); -} - -template -MemRef Column::get_mem() const noexcept -{ - return get_root_array()->get_mem(); -} - -template -void Column::update_from_parent(size_t old_baseline) noexcept -{ - ColumnBaseWithIndex::update_from_parent(old_baseline); - m_tree.update_from_parent(old_baseline); -} - -template -MemRef Column::clone_deep(Allocator& alloc) const -{ - return m_tree.clone_deep(alloc); -} - -template -size_t Column::size() const noexcept -{ - return m_tree.size(); -} - -template -bool Column::is_nullable() const noexcept -{ - return nullable; -} - -template -T Column::get(size_t ndx) const noexcept -{ - return m_tree.get(ndx); -} - -template -bool Column::is_null(size_t ndx) const noexcept -{ - return nullable && m_tree.is_null(ndx); -} - -template -T Column::back() const noexcept -{ - return m_tree.back(); -} - -template -ref_type Column::get_as_ref(size_t ndx) const noexcept -{ - return to_ref(get(ndx)); -} - -template -uint64_t Column::get_uint(size_t ndx) const noexcept -{ - static_assert(std::is_convertible::value, "T is not convertible to uint."); - return static_cast(get(ndx)); -} - -template -void Column::add(T value) -{ - insert(npos, std::move(value)); -} - -template -void Column::insert_without_updating_index(size_t row_ndx, T value, size_t num_rows) -{ - size_t column_size = this->size(); // Slow - bool is_append = row_ndx == column_size || row_ndx == npos; - size_t ndx_or_npos_if_append = is_append ? npos : row_ndx; - - m_tree.insert(ndx_or_npos_if_append, std::move(value), num_rows); // Throws -} - -template -void Column::insert(size_t row_ndx, T value, size_t num_rows) -{ - size_t column_size = this->size(); // Slow - bool is_append = row_ndx == column_size || row_ndx == npos; - size_t ndx_or_npos_if_append = is_append ? npos : row_ndx; - - m_tree.insert(ndx_or_npos_if_append, value, num_rows); // Throws - - if (has_search_index()) { - row_ndx = is_append ? column_size : row_ndx; - m_search_index->insert(row_ndx, value, num_rows, is_append); // Throws - } -} - -template -void Column::erase_without_updating_index(size_t row_ndx, bool is_last) -{ - m_tree.erase(row_ndx, is_last); -} - -template -void Column::erase(size_t row_ndx) -{ - REALM_ASSERT(size() >= 1); - size_t last_row_ndx = size() - 1; // Note that size() is slow - bool is_last = (row_ndx == last_row_ndx); - erase(row_ndx, is_last); // Throws -} - -template -void Column::erase(size_t row_ndx, bool is_last) -{ - size_t num_rows_to_erase = 1; - do_erase(row_ndx, num_rows_to_erase, is_last); // Throws -} - -template -void Column::move_last_over_without_updating_index(size_t row_ndx, size_t last_row_ndx) -{ - m_tree.move_last_over(row_ndx, last_row_ndx); -} - -template -void Column::move_last_over(size_t row_ndx, size_t last_row_ndx) -{ - REALM_ASSERT_3(row_ndx, <=, last_row_ndx); - REALM_ASSERT_DEBUG(last_row_ndx + 1 == size()); - - if (has_search_index()) { - // remove the value to be overwritten from index - bool is_last = true; // This tells StringIndex::erase() to not adjust subsequent indexes - m_search_index->erase(row_ndx, is_last); // Throws - - // update index to point to new location - if (row_ndx != last_row_ndx) { - T moved_value = get(last_row_ndx); - m_search_index->update_ref(moved_value, last_row_ndx, row_ndx); // Throws - } - } - - move_last_over_without_updating_index(row_ndx, last_row_ndx); -} - -template -void Column::swap_rows(size_t row_ndx_1, size_t row_ndx_2) -{ - REALM_ASSERT_3(row_ndx_1, <, size()); - REALM_ASSERT_3(row_ndx_2, <, size()); - REALM_ASSERT_DEBUG(row_ndx_1 != row_ndx_2); - - if (has_search_index()) { - T value_1 = get(row_ndx_1); - T value_2 = get(row_ndx_2); - size_t column_size = this->size(); - bool row_ndx_1_is_last = row_ndx_1 == column_size - 1; - bool row_ndx_2_is_last = row_ndx_2 == column_size - 1; - m_search_index->erase(row_ndx_1, row_ndx_1_is_last); - m_search_index->insert(row_ndx_1, value_2, 1, row_ndx_1_is_last); - - m_search_index->erase(row_ndx_2, row_ndx_2_is_last); - m_search_index->insert(row_ndx_2, value_1, 1, row_ndx_2_is_last); - } - - swap_rows_without_updating_index(row_ndx_1, row_ndx_2); -} - -template -void Column::swap_rows_without_updating_index(size_t row_ndx_1, size_t row_ndx_2) -{ - // FIXME: This can be optimized with direct getters and setters. - T value_1 = get(row_ndx_1); - T value_2 = get(row_ndx_2); - m_tree.set(row_ndx_1, value_2); - m_tree.set(row_ndx_2, value_1); -} - -template -void Column::clear_without_updating_index() -{ - m_tree.clear(); // Throws -} - -template -void Column::clear() -{ - if (has_search_index()) { - m_search_index->clear(); - } - clear_without_updating_index(); -} - -template -struct NullOrDefaultValue; -template -struct NullOrDefaultValue::value>::type> { - static T null_or_default_value(bool is_null) - { - if (is_null) { - return null::get_null_float(); - } - else { - return T{}; - } - } -}; -template -struct NullOrDefaultValue, void> { - static util::Optional null_or_default_value(bool is_null) - { - if (is_null) { - return util::none; - } - else { - return util::some(T{}); - } - } -}; -template -struct NullOrDefaultValue::value>::type> { - static T null_or_default_value(bool is_null) - { - REALM_ASSERT(!is_null); - return T{}; - } -}; - -// Implementing pure virtual method of ColumnBase. -template -void Column::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool insert_nulls) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - - size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); - T value = NullOrDefaultValue::null_or_default_value(insert_nulls); - insert(row_ndx_2, value, num_rows_to_insert); // Throws -} - -// Implementing pure virtual method of ColumnBase. -template -void Column::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(num_rows_to_erase <= prior_num_rows); - REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); - - bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); - do_erase(row_ndx, num_rows_to_erase, is_last); // Throws -} - -// Implementing pure virtual method of ColumnBase. -template -void Column::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx < prior_num_rows); - - size_t last_row_ndx = prior_num_rows - 1; - move_last_over(row_ndx, last_row_ndx); // Throws -} - -// Implementing pure virtual method of ColumnBase. -template -void Column::clear(size_t, bool) -{ - clear(); // Throws -} - - -template -size_t Column::lower_bound(T value) const noexcept -{ - if (root_is_leaf()) { - auto root = static_cast(get_root_array()); - return root->lower_bound(value); - } - return ColumnBase::lower_bound(*this, value); -} - -template -size_t Column::upper_bound(T value) const noexcept -{ - if (root_is_leaf()) { - auto root = static_cast(get_root_array()); - return root->upper_bound(value); - } - return ColumnBase::upper_bound(*this, value); -} - -// For a *sorted* Column, return first element E for which E >= target or return -1 if none -template -size_t Column::find_gte(T target, size_t start) const -{ - // fixme: slow reference implementation. See Array::find_gte for faster version - size_t ref = 0; - size_t idx; - for (idx = start; idx < size(); ++idx) { - if (get(idx) >= target) { - ref = idx; - break; - } - } - if (idx == size()) - ref = not_found; - - return ref; -} - - -template -bool Column::compare(const Column& c) const noexcept -{ - size_t n = size(); - if (c.size() != n) - return false; - for (size_t i = 0; i < n; ++i) { - bool left_is_null = is_null(i); - bool right_is_null = c.is_null(i); - if (left_is_null != right_is_null) { - return false; - } - if (!left_is_null) { - if (get(i) != c.get(i)) - return false; - } - } - return true; -} - -template -int Column::compare_values(size_t row1, size_t row2) const noexcept -{ - return ColumnBase::compare_values(this, row1, row2); -} - -template -class Column::CreateHandler : public ColumnBase::CreateHandler { -public: - CreateHandler(Array::Type leaf_type, T value, Allocator& alloc) - : m_value(value) - , m_alloc(alloc) - , m_leaf_type(leaf_type) - { - } - ref_type create_leaf(size_t size) override - { - MemRef mem = BpTree::create_leaf(m_leaf_type, size, m_value, m_alloc); // Throws - return mem.get_ref(); - } - -private: - const T m_value; - Allocator& m_alloc; - Array::Type m_leaf_type; -}; - -template -ref_type Column::create(Allocator& alloc, Array::Type leaf_type, size_t size, T value) -{ - CreateHandler handler(leaf_type, std::move(value), alloc); - return ColumnBase::create(alloc, size, handler); -} - -template -ref_type Column::write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream& out) const -{ - return m_tree.write(slice_offset, slice_size, table_size, out); -} - -template -void Column::refresh_accessor_tree(size_t new_col_ndx, const Spec& spec) -{ - m_tree.init_from_parent(); - ColumnBaseWithIndex::refresh_accessor_tree(new_col_ndx, spec); -} - -template -void Column::do_erase(size_t row_ndx, size_t num_rows_to_erase, bool is_last) -{ - if (has_search_index()) { - for (size_t i = num_rows_to_erase; i > 0; --i) { - size_t row_ndx_2 = row_ndx + i - 1; - m_search_index->erase(row_ndx_2, is_last); // Throws - } - } - for (size_t i = num_rows_to_erase; i > 0; --i) { - size_t row_ndx_2 = row_ndx + i - 1; - erase_without_updating_index(row_ndx_2, is_last); // Throws - } -} - -template -void Column::verify() const -{ -#ifdef REALM_DEBUG - m_tree.verify(); -#endif -} - -// LCOV_EXCL_START - -template -void Column::to_dot(std::ostream& out, StringData title) const -{ -#ifdef REALM_DEBUG - ref_type ref = get_root_array()->get_ref(); - out << "subgraph cluster_integer_column" << ref << " {" << std::endl; - out << " label = \"Integer column"; - if (title.size() != 0) - out << "\\n'" << title << "'"; - out << "\";" << std::endl; - tree_to_dot(out); - out << "}" << std::endl; -#else - static_cast(out); - static_cast(title); -#endif -} - -template -void Column::leaf_to_dot(MemRef leaf_mem, ArrayParent* parent, size_t ndx_in_parent, std::ostream& out) const -{ -#ifdef REALM_DEBUG - BpTree::leaf_to_dot(leaf_mem, parent, ndx_in_parent, out, get_alloc()); -#else - static_cast(leaf_mem); - static_cast(parent); - static_cast(ndx_in_parent); - static_cast(out); -#endif -} - -template -void Column::do_dump_node_structure(std::ostream& out, int level) const -{ -#ifdef REALM_DEBUG - dump_node_structure(*get_root_array(), out, level); -#else - static_cast(out); - static_cast(level); -#endif -} - -#ifdef REALM_DEBUG - -template -void Column::tree_to_dot(std::ostream& out) const -{ - ColumnBase::bptree_to_dot(get_root_array(), out); -} - - -template -MemStats Column::stats() const -{ - MemStats mem_stats; - get_root_array()->stats(mem_stats); - return mem_stats; -} - -namespace _impl { -void leaf_dumper(MemRef mem, Allocator& alloc, std::ostream& out, int level); -} - -template -void Column::dump_node_structure(const Array& root, std::ostream& out, int level) -{ - root.dump_bptree_structure(out, level, &_impl::leaf_dumper); -} - -#endif - -template -std::pair Column::get_to_dot_parent(size_t ndx_in_parent) const -{ - auto root = get_root_array(); - if (root->is_inner_bptree_node()) { - std::pair p = static_cast(root)->get_bptree_leaf(ndx_in_parent); - return std::make_pair(p.first.get_ref(), p.second); - } - else { - return std::make_pair(root->get_ref(), ndx_in_parent); - } -} - -// LCOV_EXCL_STOP ignore debug functions - - -template -ColumnRandIterator::ColumnRandIterator(const Column* src_col, size_t ndx) - : m_col_ndx(ndx) - , m_col(src_col) -{ -} - -template -bool ColumnRandIterator::operator==(const ColumnRandIterator& rhs) const -{ - return (m_col_ndx == rhs.m_col_ndx); -} - -template -bool ColumnRandIterator::operator!=(const ColumnRandIterator& rhs) const -{ - return !(*this == rhs); -} - -template -bool ColumnRandIterator::operator<(const ColumnRandIterator& rhs) const -{ - return m_col_ndx < rhs.m_col_ndx; -} - -template -bool ColumnRandIterator::operator>(const ColumnRandIterator& rhs) const -{ - return rhs < *this; -} - -template -bool ColumnRandIterator::operator<=(const ColumnRandIterator& rhs) const -{ - return !(rhs < *this); -} - -template -bool ColumnRandIterator::operator>=(const ColumnRandIterator& rhs) const -{ - return !(*this < rhs); -} - -template -ColumnRandIterator& ColumnRandIterator::operator+=(ptrdiff_t movement) -{ - m_col_ndx += movement; - return (*this); -} - -template -ColumnRandIterator& ColumnRandIterator::operator-=(ptrdiff_t movement) -{ - m_col_ndx -= movement; - return (*this); -} - -template -ColumnRandIterator& ColumnRandIterator::operator++() -{ - ++m_col_ndx; - return (*this); -} - -template -ColumnRandIterator& ColumnRandIterator::operator--() -{ - --m_col_ndx; - return (*this); -} - -template -ColumnRandIterator ColumnRandIterator::operator++(int) -{ - auto temp(*this); - ++m_col_ndx; - return temp; -} - -template -ColumnRandIterator ColumnRandIterator::operator--(int) -{ - auto temp(*this); - --m_col_ndx; - return temp; -} - -template -ColumnRandIterator ColumnRandIterator::operator+(ptrdiff_t movement) -{ - return ColumnRandIterator(m_col, m_col_ndx + movement); -} - -template -ColumnRandIterator ColumnRandIterator::operator-(ptrdiff_t movement) -{ - return ColumnRandIterator(m_col, m_col_ndx - movement); -} - -template -ptrdiff_t ColumnRandIterator::operator-(const ColumnRandIterator& right) const -{ - return m_col_ndx - right.m_col_ndx; -} - -template -const ColumnDataType ColumnRandIterator::operator*() const -{ - return m_col->get(m_col_ndx); -} - -template -const ColumnDataType ColumnRandIterator::operator->() const -{ - return m_col->get(m_col_ndx); -} - -template -const ColumnDataType ColumnRandIterator::operator[](ptrdiff_t offset) const -{ - return m_col->get(m_col_ndx + offset); -} - -template -size_t ColumnRandIterator::get_col_ndx() const -{ - return m_col_ndx; -} - -template -std::ostream& operator<<(std::ostream& out, const ColumnRandIterator& it) -{ - out << "ColumnRandIterator at index: " << it.get_col_ndx(); - return out; -} - -} // namespace realm - -#endif // REALM_COLUMN_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_backlink.hpp b/Lesson14/Pods/Realm/include/core/realm/column_backlink.hpp deleted file mode 100644 index cbbe9e6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_backlink.hpp +++ /dev/null @@ -1,246 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_BACKLINK_HPP -#define REALM_COLUMN_BACKLINK_HPP - -#include - -#include -#include -#include - -namespace realm { - -/// A column of backlinks (BacklinkColumn) is a single B+-tree, and the root of -/// the column is the root of the B+-tree. All leaf nodes are single arrays of -/// type Array with the hasRefs bit set. -/// -/// The individual values in the column are either refs to Columns containing -/// the row indexes in the origin table that links to it, or in the case where -/// there is a single link, a tagged ref encoding the origin row position. -class BacklinkColumn : public IntegerColumn, public ArrayParent { -public: - BacklinkColumn(Allocator&, ref_type, size_t col_ndx = npos); - ~BacklinkColumn() noexcept override - { - } - - static ref_type create(Allocator&, size_t size = 0); - - bool has_backlinks(size_t row_ndx) const noexcept; - size_t get_backlink_count(size_t row_ndx) const noexcept; - size_t get_backlink(size_t row_ndx, size_t backlink_ndx) const noexcept; - - void add_backlink(size_t row_ndx, size_t origin_row_ndx); - void remove_one_backlink(size_t row_ndx, size_t origin_row_ndx); - void remove_all_backlinks(size_t num_rows); - void update_backlink(size_t row_ndx, size_t old_origin_row_ndx, size_t new_origin_row_ndx); - void swap_backlinks(size_t row_ndx, size_t origin_row_ndx_1, size_t origin_row_ndx_2); - - void add_row(); - - // Link origination info - Table& get_origin_table() const noexcept; - void set_origin_table(Table&) noexcept; - LinkColumnBase& get_origin_column() const noexcept; - size_t get_origin_column_index() const noexcept; - void set_origin_column(LinkColumnBase& column) noexcept; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void swap_rows(size_t, size_t) override; - void clear(size_t, bool) override; - void adj_acc_insert_rows(size_t, size_t) noexcept override; - void adj_acc_erase_row(size_t) noexcept override; - void adj_acc_move_over(size_t, size_t) noexcept override; - void adj_acc_swap_rows(size_t, size_t) noexcept override; - void adj_acc_move_row(size_t, size_t) noexcept override; - void adj_acc_merge_rows(size_t, size_t) noexcept override; - void adj_acc_clear_root_table() noexcept override; - void mark(int) noexcept override; - - void bump_link_origin_table_version() noexcept override; - - void cascade_break_backlinks_to(size_t row_ndx, CascadeState& state) override; - void cascade_break_backlinks_to_all_rows(size_t num_rows, CascadeState&) override; - - int compare_values(size_t, size_t) const noexcept override; - - void verify() const override; - void verify(const Table&, size_t) const override; -#ifdef REALM_DEBUG - struct VerifyPair { - size_t origin_row_ndx, target_row_ndx; - bool operator<(const VerifyPair&) const noexcept; - }; - void get_backlinks(std::vector&); // Sorts -#endif - -protected: - // ArrayParent overrides - void update_child_ref(size_t child_ndx, ref_type new_ref) override; - ref_type get_child_ref(size_t child_ndx) const noexcept override; - - std::pair get_to_dot_parent(size_t) const override; - -private: - TableRef m_origin_table; - LinkColumnBase* m_origin_column = nullptr; - - template - size_t for_each_link(size_t row_ndx, bool do_destroy, Func&& f); -}; - - -// Implementation - -inline BacklinkColumn::BacklinkColumn(Allocator& alloc, ref_type ref, size_t col_ndx) - : IntegerColumn(alloc, ref, col_ndx) // Throws -{ -} - -inline ref_type BacklinkColumn::create(Allocator& alloc, size_t size) -{ - return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws -} - -inline bool BacklinkColumn::has_backlinks(size_t ndx) const noexcept -{ - return IntegerColumn::get(ndx) != 0; -} - -inline Table& BacklinkColumn::get_origin_table() const noexcept -{ - return *m_origin_table; -} - -inline void BacklinkColumn::set_origin_table(Table& table) noexcept -{ - REALM_ASSERT(!m_origin_table); - m_origin_table = table.get_table_ref(); -} - -inline LinkColumnBase& BacklinkColumn::get_origin_column() const noexcept -{ - return *m_origin_column; -} - -inline size_t BacklinkColumn::get_origin_column_index() const noexcept -{ - return m_origin_column ? m_origin_column->get_column_index() : npos; -} - -inline void BacklinkColumn::set_origin_column(LinkColumnBase& column) noexcept -{ - m_origin_column = &column; -} - -inline void BacklinkColumn::add_row() -{ - IntegerColumn::add(0); -} - -inline void BacklinkColumn::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept -{ - IntegerColumn::adj_acc_insert_rows(row_ndx, num_rows); - - typedef _impl::TableFriend tf; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_erase_row(size_t row_ndx) noexcept -{ - IntegerColumn::adj_acc_erase_row(row_ndx); - - typedef _impl::TableFriend tf; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept -{ - IntegerColumn::adj_acc_move_over(from_row_ndx, to_row_ndx); - - typedef _impl::TableFriend tf; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept -{ - Column::adj_acc_swap_rows(row_ndx_1, row_ndx_2); - - using tf = _impl::TableFriend; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept -{ - Column::adj_acc_move_row(from_ndx, to_ndx); - - using tf = _impl::TableFriend; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept -{ - Column::adj_acc_merge_rows(old_row_ndx, new_row_ndx); - - using tf = _impl::TableFriend; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::adj_acc_clear_root_table() noexcept -{ - IntegerColumn::adj_acc_clear_root_table(); - - typedef _impl::TableFriend tf; - tf::mark(*m_origin_table); -} - -inline void BacklinkColumn::mark(int type) noexcept -{ - if (type & mark_LinkOrigins) { - typedef _impl::TableFriend tf; - tf::mark(*m_origin_table); - } -} - -inline void BacklinkColumn::bump_link_origin_table_version() noexcept -{ - // It is important to mark connected tables as modified. - // Also see LinkColumnBase::bump_link_origin_table_version(). - typedef _impl::TableFriend tf; - if (m_origin_table) { - bool bump_global = false; - tf::bump_version(*m_origin_table, bump_global); - } -} - -#ifdef REALM_DEBUG - -inline bool BacklinkColumn::VerifyPair::operator<(const VerifyPair& p) const noexcept -{ - return origin_row_ndx < p.origin_row_ndx; -} - -#endif // REALM_DEBUG - -} // namespace realm - -#endif // REALM_COLUMN_BACKLINK_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_binary.hpp b/Lesson14/Pods/Realm/include/core/realm/column_binary.hpp deleted file mode 100644 index 48e1d11..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_binary.hpp +++ /dev/null @@ -1,435 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_BINARY_HPP -#define REALM_COLUMN_BINARY_HPP - -#include -#include -#include - -namespace realm { - - -/// A binary column (BinaryColumn) is a single B+-tree, and the root -/// of the column is the root of the B+-tree. Leaf nodes are either of -/// type ArrayBinary (array of small blobs) or ArrayBigBlobs (array of -/// big blobs). -class BinaryColumn : public ColumnBaseSimple { -public: - typedef BinaryData value_type; - - BinaryColumn(Allocator&, ref_type, bool nullable = false, size_t column_ndx = npos); - - size_t size() const noexcept final; - bool is_empty() const noexcept - { - return size() == 0; - } - bool is_nullable() const noexcept override; - - BinaryData get(size_t ndx) const noexcept; - - /// Return data from position 'pos' and onwards. If the blob is distributed - /// across multiple arrays (if bigger than ~ 16M), you will only get data - /// from one array. 'pos' will be updated to be an index to next available - /// data. It will be 0 if no more data. - BinaryData get_at(size_t ndx, size_t& pos) const noexcept; - - bool is_null(size_t ndx) const noexcept override; - StringData get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept final; - - void add(BinaryData value); - void set(size_t ndx, BinaryData value, bool add_zero_term = false); - void set_null(size_t ndx) override; - void insert(size_t ndx, BinaryData value); - void erase(size_t row_ndx); - void erase(size_t row_ndx, bool is_last); - void move_last_over(size_t row_ndx); - void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; - void clear(); - size_t find_first(BinaryData value) const; - - // Requires that the specified entry was inserted as StringData. - StringData get_string(size_t ndx) const noexcept; - - void add_string(StringData value); - void set_string(size_t ndx, StringData value) override; - void insert_string(size_t ndx, StringData value); - - /// Compare two binary columns for equality. - bool compare_binary(const BinaryColumn&) const; - - int compare_values(size_t row1, size_t row2) const noexcept override; - - static ref_type create(Allocator&, size_t size, bool nullable); - - static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; - - // Overrriding method in ColumnBase - ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void clear(size_t, bool) override; - void update_from_parent(size_t) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - - /// In contrast to update_from_parent(), this function is able to handle - /// cases where the accessed payload data has changed. In particular, it - /// handles cases where the B+-tree switches from having one level (root is - /// a leaf node), to having multiple levels (root is an inner node). Note - /// that this is at the expense of loosing the `noexcept` guarantee. - void update_from_ref(ref_type ref); - - void verify() const override; - void to_dot(std::ostream&, StringData title) const override; - void do_dump_node_structure(std::ostream&, int) const override; - void find_all(IntegerColumn&, BinaryData, size_t, size_t) const - { - // Dummy implementation - REALM_ASSERT(false); - } - - -private: - /// \param row_ndx Must be `realm::npos` if appending. - void do_insert(size_t row_ndx, BinaryData value, bool add_zero_term, size_t num_rows); - - // Called by Array::bptree_insert(). - static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, size_t ndx_in_parent, Allocator&, size_t insert_ndx, - BpTreeNode::TreeInsert& state); - - struct InsertState : BpTreeNode::TreeInsert { - bool m_add_zero_term; - }; - - class EraseLeafElem; - class CreateHandler; - class SliceHandler; - - void do_move_last_over(size_t row_ndx, size_t last_row_ndx); - void do_clear(); - - /// Root must be a leaf. Upgrades the root leaf if - /// necessary. Returns true if, and only if the root is a 'big - /// blobs' leaf upon return. - bool upgrade_root_leaf(size_t value_size); - - bool m_nullable = false; - - void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; - - friend class BpTreeNode; - friend class ColumnBase; -}; - -class BinaryIterator { -public: - BinaryIterator() - { - } - // TODO: When WriteLogCollector is removed, there is no need for this - BinaryIterator(BinaryData binary) - : m_binary(binary) - { - } - - BinaryIterator(const BinaryColumn* col, size_t ndx) - : m_binary_col(col) - , m_ndx(ndx) - { - } - - BinaryData get_next() noexcept - { - if (!end_of_data) { - if (m_binary_col) { - BinaryData ret = m_binary_col->get_at(m_ndx, m_pos); - end_of_data = (m_pos == 0); - return ret; - } - else if (!m_binary.is_null()) { - end_of_data = true; - return m_binary; - } - } - return {}; - } - -private: - bool end_of_data = false; - const BinaryColumn* m_binary_col = nullptr; - size_t m_ndx = 0; - size_t m_pos = 0; - BinaryData m_binary; -}; - - -// Implementation - -// LCOV_EXCL_START -inline StringData BinaryColumn::get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept -{ - REALM_ASSERT(false && "Index not implemented for BinaryColumn."); - REALM_UNREACHABLE(); -} -// LCOV_EXCL_STOP - -inline size_t BinaryColumn::size() const noexcept -{ - if (root_is_leaf()) { - bool is_big = m_array->get_context_flag(); - if (!is_big) { - // Small blobs root leaf - ArrayBinary* leaf = static_cast(m_array.get()); - return leaf->size(); - } - // Big blobs root leaf - ArrayBigBlobs* leaf = static_cast(m_array.get()); - return leaf->size(); - } - // Non-leaf root - return static_cast(m_array.get())->get_bptree_size(); -} - -inline bool BinaryColumn::is_nullable() const noexcept -{ - return m_nullable; -} - -inline void BinaryColumn::update_from_parent(size_t old_baseline) noexcept -{ - if (root_is_leaf()) { - bool is_big = m_array->get_context_flag(); - if (!is_big) { - // Small blobs root leaf - REALM_ASSERT(dynamic_cast(m_array.get())); - ArrayBinary* leaf = static_cast(m_array.get()); - leaf->update_from_parent(old_baseline); - return; - } - // Big blobs root leaf - REALM_ASSERT(dynamic_cast(m_array.get())); - ArrayBigBlobs* leaf = static_cast(m_array.get()); - leaf->update_from_parent(old_baseline); - return; - } - // Non-leaf root - m_array->update_from_parent(old_baseline); -} - -inline BinaryData BinaryColumn::get(size_t ndx) const noexcept -{ - REALM_ASSERT_DEBUG(ndx < size()); - if (root_is_leaf()) { - bool is_big = m_array->get_context_flag(); - BinaryData ret; - if (!is_big) { - // Small blobs root leaf - ArrayBinary* leaf = static_cast(m_array.get()); - ret = leaf->get(ndx); - } - else { - // Big blobs root leaf - ArrayBigBlobs* leaf = static_cast(m_array.get()); - ret = leaf->get(ndx); - } - if (!m_nullable && ret.is_null()) - return BinaryData("", 0); // return empty string (non-null) - return ret; - } - - // Non-leaf root - std::pair p = static_cast(m_array.get())->get_bptree_leaf(ndx); - const char* leaf_header = p.first.get_addr(); - size_t ndx_in_leaf = p.second; - Allocator& alloc = m_array->get_alloc(); - bool is_big = Array::get_context_flag_from_header(leaf_header); - if (!is_big) { - // Small blobs - return ArrayBinary::get(leaf_header, ndx_in_leaf, alloc); - } - // Big blobs - return ArrayBigBlobs::get(leaf_header, ndx_in_leaf, alloc); -} - -inline bool BinaryColumn::is_null(size_t ndx) const noexcept -{ - return m_nullable && get(ndx).is_null(); -} - -inline StringData BinaryColumn::get_string(size_t ndx) const noexcept -{ - BinaryData bin = get(ndx); - REALM_ASSERT_3(0, <, bin.size()); - return StringData(bin.data(), bin.size() - 1); -} - -inline void BinaryColumn::set_string(size_t ndx, StringData value) -{ - if (value.is_null() && !m_nullable) - throw LogicError(LogicError::column_not_nullable); - - BinaryData bin(value.data(), value.size()); - bool add_zero_term = true; - set(ndx, bin, add_zero_term); -} - -inline void BinaryColumn::add(BinaryData value) -{ - if (value.is_null() && !m_nullable) - throw LogicError(LogicError::column_not_nullable); - - size_t row_ndx = realm::npos; - bool add_zero_term = false; - size_t num_rows = 1; - do_insert(row_ndx, value, add_zero_term, num_rows); // Throws -} - -inline void BinaryColumn::insert(size_t row_ndx, BinaryData value) -{ - if (value.is_null() && !m_nullable) - throw LogicError(LogicError::column_not_nullable); - - size_t column_size = this->size(); // Slow - REALM_ASSERT_3(row_ndx, <=, column_size); - size_t row_ndx_2 = row_ndx == column_size ? realm::npos : row_ndx; - bool add_zero_term = false; - size_t num_rows = 1; - do_insert(row_ndx_2, value, add_zero_term, num_rows); // Throws -} - -inline void BinaryColumn::set_null(size_t row_ndx) -{ - set(row_ndx, BinaryData{}); -} - -inline size_t BinaryColumn::find_first(BinaryData value) const -{ - for (size_t t = 0; t < size(); t++) - if (get(t) == value) - return t; - - return not_found; -} - - -inline void BinaryColumn::erase(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - bool is_last = row_ndx == last_row_ndx; - erase(row_ndx, is_last); // Throws -} - -inline void BinaryColumn::move_last_over(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -inline void BinaryColumn::clear() -{ - do_clear(); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void BinaryColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, - bool insert_nulls) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - REALM_ASSERT(!insert_nulls || m_nullable); - - size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); - BinaryData value = m_nullable ? BinaryData() : BinaryData("", 0); - bool add_zero_term = false; - do_insert(row_ndx_2, value, add_zero_term, num_rows_to_insert); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void BinaryColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(num_rows_to_erase <= prior_num_rows); - REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); - - bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); - for (size_t i = num_rows_to_erase; i > 0; --i) { - size_t row_ndx_2 = row_ndx + i - 1; - erase(row_ndx_2, is_last); // Throws - } -} - -// Implementing pure virtual method of ColumnBase. -inline void BinaryColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx < prior_num_rows); - - size_t last_row_ndx = prior_num_rows - 1; - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void BinaryColumn::clear(size_t, bool) -{ - do_clear(); // Throws -} - -inline void BinaryColumn::add_string(StringData value) -{ - size_t row_ndx = realm::npos; - BinaryData value_2(value.data(), value.size()); - bool add_zero_term = true; - size_t num_rows = 1; - do_insert(row_ndx, value_2, add_zero_term, num_rows); // Throws -} - -inline void BinaryColumn::insert_string(size_t row_ndx, StringData value) -{ - size_t column_size = this->size(); // Slow - REALM_ASSERT_3(row_ndx, <=, column_size); - size_t row_ndx_2 = row_ndx == column_size ? realm::npos : row_ndx; - BinaryData value_2(value.data(), value.size()); - bool add_zero_term = false; - size_t num_rows = 1; - do_insert(row_ndx_2, value_2, add_zero_term, num_rows); // Throws -} - -inline size_t BinaryColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept -{ - const char* root_header = alloc.translate(root_ref); - bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); - if (root_is_leaf) { - bool is_big = Array::get_context_flag_from_header(root_header); - if (!is_big) { - // Small blobs leaf - return ArrayBinary::get_size_from_header(root_header, alloc); - } - // Big blobs leaf - return ArrayBigBlobs::get_size_from_header(root_header); - } - return BpTreeNode::get_bptree_size_from_header(root_header); -} - - -} // namespace realm - -#endif // REALM_COLUMN_BINARY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_fwd.hpp b/Lesson14/Pods/Realm/include/core/realm/column_fwd.hpp deleted file mode 100644 index 5b93cdc..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_fwd.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_FWD_HPP -#define REALM_COLUMN_FWD_HPP - -#include - -namespace realm { - -// Regular classes -class ColumnBase; -class StringColumn; -class StringEnumColumn; -class BinaryColumn; -class SubtableColumn; -class MixedColumn; -class LinkColumn; -class LinkListColumn; -class TimestampColumn; - -// Templated classes -template -class Column; -template -class BasicColumn; -template -class ColumnRandIterator; - -namespace util { -template -class Optional; -} - -// Shortcuts, aka typedefs. -using IntegerColumn = Column; -using IntNullColumn = Column>; -using DoubleColumn = Column; -using FloatColumn = Column; -using IntegerColumnIterator = ColumnRandIterator; -} // namespace realm - -#endif // REALM_COLUMN_FWD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_link.hpp b/Lesson14/Pods/Realm/include/core/realm/column_link.hpp deleted file mode 100644 index 185a6c3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_link.hpp +++ /dev/null @@ -1,181 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_LINK_HPP -#define REALM_COLUMN_LINK_HPP - -#include -#include -#include - -namespace realm { - -/// A link column is an extension of an integer column (Column) and maintains -/// its node structure. -/// -/// The individual values in a link column are indexes of rows in the target -/// table (offset with one to allow zero to indicate null links.) The target -/// table is specified by the table descriptor. -class LinkColumn : public LinkColumnBase { -public: - using LinkColumnBase::LinkColumnBase; - ~LinkColumn() noexcept override; - - static ref_type create(Allocator&, size_t size = 0); - - bool is_nullable() const noexcept override; - - //@{ - - /// is_null_link() is shorthand for `get_link() == realm::npos`, - /// nullify_link() is shorthand foe `set_link(realm::npos)`, and - /// insert_null_link() is shorthand for - /// `insert_link(realm::npos)`. set_link() returns the original link, with - /// `realm::npos` indicating that it was null. - - size_t get_link(size_t row_ndx) const noexcept; - bool is_null(size_t row_ndx) const noexcept override; - bool is_null_link(size_t row_ndx) const noexcept; - size_t set_link(size_t row_ndx, size_t target_row_ndx); - void set_null(size_t row_ndx) override; - void nullify_link(size_t row_ndx); - void insert_link(size_t row_ndx, size_t target_row_ndx); - void insert_null_link(size_t row_ndx); - - //@} - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void swap_rows(size_t, size_t) override; - void clear(size_t, bool) override; - void cascade_break_backlinks_to(size_t, CascadeState&) override; - void cascade_break_backlinks_to_all_rows(size_t, CascadeState&) override; - - void verify(const Table&, size_t) const override; - -protected: - friend class BacklinkColumn; - void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) override; - void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) override; - void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) override; - -private: - void remove_backlinks(size_t row_ndx); -}; - - -// Implementation - -inline LinkColumn::~LinkColumn() noexcept -{ -} - -inline bool LinkColumn::is_nullable() const noexcept -{ - return true; -} - -inline ref_type LinkColumn::create(Allocator& alloc, size_t size) -{ - return IntegerColumn::create(alloc, Array::type_Normal, size); // Throws -} - -inline bool LinkColumn::is_null(size_t row_ndx) const noexcept -{ - // Null is represented by zero - return LinkColumnBase::get(row_ndx) == 0; -} - -inline size_t LinkColumn::get_link(size_t row_ndx) const noexcept -{ - // Map zero to realm::npos, and `n+1` to `n`, where `n` is a target row index. - return to_size_t(LinkColumnBase::get(row_ndx)) - size_t(1); -} - -inline bool LinkColumn::is_null_link(size_t row_ndx) const noexcept -{ - return is_null(row_ndx); -} - -inline size_t LinkColumn::set_link(size_t row_ndx, size_t target_row_ndx) -{ - int_fast64_t old_value = LinkColumnBase::get(row_ndx); - size_t old_target_row_ndx = to_size_t(old_value) - size_t(1); - if (old_target_row_ndx == target_row_ndx) - return old_target_row_ndx; // Nothing to do - if (old_value != 0) - m_backlink_column->remove_one_backlink(old_target_row_ndx, row_ndx); // Throws - - int_fast64_t new_value = int_fast64_t(size_t(1) + target_row_ndx); - LinkColumnBase::set(row_ndx, new_value); // Throws - - if (target_row_ndx != realm::npos) - m_backlink_column->add_backlink(target_row_ndx, row_ndx); // Throws - - return old_target_row_ndx; -} - -inline void LinkColumn::set_null(size_t row_ndx) -{ - set_link(row_ndx, realm::npos); // Throws -} - -inline void LinkColumn::nullify_link(size_t row_ndx) -{ - set_null(row_ndx); // Throws -} - -inline void LinkColumn::insert_link(size_t row_ndx, size_t target_row_ndx) -{ - int_fast64_t value = int_fast64_t(size_t(1) + target_row_ndx); - LinkColumnBase::insert(row_ndx, value); // Throws - - if (target_row_ndx != realm::npos) - m_backlink_column->add_backlink(target_row_ndx, row_ndx); // Throws -} - -inline void LinkColumn::insert_null_link(size_t row_ndx) -{ - insert_link(row_ndx, realm::npos); // Throws -} - -inline void LinkColumn::do_update_link(size_t row_ndx, size_t, size_t new_target_row_ndx) -{ - // Row pos is offset by one, to allow null refs - LinkColumnBase::set(row_ndx, new_target_row_ndx + 1); -} - -inline void LinkColumn::do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) -{ - // Row pos is offset by one, to allow null refs - ++target_row_ndx_1; - ++target_row_ndx_2; - - uint64_t value = LinkColumnBase::get_uint(row_ndx); - if (value == target_row_ndx_1) { - LinkColumnBase::set_uint(row_ndx, target_row_ndx_2); - } - else if (value == target_row_ndx_2) { - LinkColumnBase::set_uint(row_ndx, target_row_ndx_1); - } -} - -} // namespace realm - -#endif // REALM_COLUMN_LINK_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_linkbase.hpp b/Lesson14/Pods/Realm/include/core/realm/column_linkbase.hpp deleted file mode 100644 index fa67fab..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_linkbase.hpp +++ /dev/null @@ -1,206 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_LINKBASE_HPP -#define REALM_COLUMN_LINKBASE_HPP - -#include - -namespace realm { - -class BacklinkColumn; -class Table; - -// Abstract base class for columns containing links -class LinkColumnBase : public IntegerColumn { -public: - // Create unattached root array aaccessor. - LinkColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); - ~LinkColumnBase() noexcept override; - - bool is_nullable() const noexcept override = 0; - void set_null(size_t) override = 0; - bool is_null(size_t) const noexcept override = 0; - - bool supports_search_index() const noexcept final - { - return false; - } - StringIndex* create_search_index() override; - - bool get_weak_links() const noexcept; - void set_weak_links(bool) noexcept; - - Table& get_target_table() const noexcept; - void set_target_table(Table&) noexcept; - BacklinkColumn& get_backlink_column() const noexcept; - void set_backlink_column(BacklinkColumn&) noexcept; - - void swap_rows(size_t, size_t) override = 0; - - virtual void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) = 0; - virtual void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) = 0; - virtual void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) = 0; - - void adj_acc_insert_rows(size_t, size_t) noexcept override; - void adj_acc_erase_row(size_t) noexcept override; - void adj_acc_move_over(size_t, size_t) noexcept override; - void adj_acc_swap_rows(size_t, size_t) noexcept override; - void adj_acc_move_row(size_t, size_t) noexcept override; - void adj_acc_clear_root_table() noexcept override; - void mark(int) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - void bump_link_origin_table_version() noexcept override; - - void verify(const Table&, size_t) const override; - using IntegerColumn::verify; - -protected: - // A pointer to the table that this column is part of. - Table* const m_table; - - TableRef m_target_table; - BacklinkColumn* m_backlink_column = nullptr; - bool m_weak_links = false; // True if these links are weak (not strong) - - /// Call Table::cascade_break_backlinks_to() for the specified target row if - /// it is not already in \a state.rows, and the number of strong links to it - /// has dropped to zero. - void check_cascade_break_backlinks_to(size_t target_table_ndx, size_t target_row_ndx, CascadeState& state); -}; - - -// Implementation - -inline LinkColumnBase::LinkColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) - : IntegerColumn(alloc, ref, column_ndx) // Throws - , m_table(table) -{ -} - -inline LinkColumnBase::~LinkColumnBase() noexcept -{ -} - -inline StringIndex* LinkColumnBase::create_search_index() -{ - return nullptr; -} - -inline bool LinkColumnBase::get_weak_links() const noexcept -{ - return m_weak_links; -} - -inline void LinkColumnBase::set_weak_links(bool value) noexcept -{ - m_weak_links = value; -} - -inline Table& LinkColumnBase::get_target_table() const noexcept -{ - return *m_target_table; -} - -inline void LinkColumnBase::set_target_table(Table& table) noexcept -{ - REALM_ASSERT(!m_target_table); - m_target_table = table.get_table_ref(); -} - -inline BacklinkColumn& LinkColumnBase::get_backlink_column() const noexcept -{ - return *m_backlink_column; -} - -inline void LinkColumnBase::set_backlink_column(BacklinkColumn& column) noexcept -{ - m_backlink_column = &column; -} - -inline void LinkColumnBase::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept -{ - IntegerColumn::adj_acc_insert_rows(row_ndx, num_rows); - - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::adj_acc_erase_row(size_t row_ndx) noexcept -{ - IntegerColumn::adj_acc_erase_row(row_ndx); - - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept -{ - IntegerColumn::adj_acc_move_over(from_row_ndx, to_row_ndx); - - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept -{ - IntegerColumn::adj_acc_swap_rows(row_ndx_1, row_ndx_2); - - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept -{ - IntegerColumn::adj_acc_move_row(from_ndx, to_ndx); - - using tf = _impl::TableFriend; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::adj_acc_clear_root_table() noexcept -{ - IntegerColumn::adj_acc_clear_root_table(); - - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); -} - -inline void LinkColumnBase::mark(int type) noexcept -{ - if (type & mark_LinkTargets) { - typedef _impl::TableFriend tf; - tf::mark(*m_target_table); - } -} - -inline void LinkColumnBase::bump_link_origin_table_version() noexcept -{ - // It is important to mark connected tables as modified. - // Also see BacklinkColumn::bump_link_origin_table_version(). - typedef _impl::TableFriend tf; - if (m_target_table) { - bool bump_global = false; - tf::bump_version(*m_target_table, bump_global); - } -} - - -} // namespace realm - -#endif // REALM_COLUMN_LINKBASE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_linklist.hpp b/Lesson14/Pods/Realm/include/core/realm/column_linklist.hpp deleted file mode 100644 index 3dab1b3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_linklist.hpp +++ /dev/null @@ -1,248 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_LINKLIST_HPP -#define REALM_COLUMN_LINKLIST_HPP - -#include -#include - -#include -#include -#include -#include -#include - -namespace realm { - -namespace _impl { -class TransactLogConvenientEncoder; -} - - -/// A column of link lists (LinkListColumn) is a single B+-tree, and the root of -/// the column is the root of the B+-tree. All leaf nodes are single arrays of -/// type Array with the hasRefs bit set. -/// -/// The individual values in the column are either refs to Columns containing the -/// row positions in the target table, or in the case where they are empty, a zero -/// ref. -class LinkListColumn : public LinkColumnBase, public ArrayParent { -public: - using LinkColumnBase::LinkColumnBase; - using value_type = ConstLinkViewRef; - LinkListColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); - ~LinkListColumn() noexcept override; - - static ref_type create(Allocator&, size_t size = 0); - - bool is_nullable() const noexcept final; - - bool has_links(size_t row_ndx) const noexcept; - size_t get_link_count(size_t row_ndx) const noexcept; - - ConstLinkViewRef get(size_t row_ndx) const; - LinkViewRef get(size_t row_ndx); - - bool is_null(size_t row_ndx) const noexcept final; - void set_null(size_t row_ndx) final; - - /// Compare two columns for equality. - bool compare_link_list(const LinkListColumn&) const; - - void to_json_row(size_t row_ndx, std::ostream& out) const; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void swap_rows(size_t, size_t) override; - void clear(size_t, bool) override; - void cascade_break_backlinks_to(size_t, CascadeState&) override; - void cascade_break_backlinks_to_all_rows(size_t, CascadeState&) override; - void update_from_parent(size_t) noexcept override; - void adj_acc_clear_root_table() noexcept override; - void adj_acc_insert_rows(size_t, size_t) noexcept override; - void adj_acc_erase_row(size_t) noexcept override; - void adj_acc_move_over(size_t, size_t) noexcept override; - void adj_acc_swap_rows(size_t, size_t) noexcept override; - void adj_acc_move_row(size_t, size_t) noexcept override; - void adj_acc_merge_rows(size_t, size_t) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - - void verify() const override; - void verify(const Table&, size_t) const override; - -protected: - void do_discard_child_accessors() noexcept override; - -private: - struct list_entry { - size_t m_row_ndx; - std::weak_ptr m_list; - bool operator<(const list_entry& other) const - { - return m_row_ndx < other.m_row_ndx; - } - }; - - // The accessors stored in `m_list_accessors` are sorted by their row index. - // When a LinkList accessor is destroyed because the last shared_ptr pointing - // to it dies, its entry is implicitly replaced by a tombstone (an entry with - // an empty `m_list`). These tombstones are pruned at a later time by - // `prune_list_accessor_tombstones`. This is done to amortize the O(n) cost - // of `std::vector::erase` that would otherwise be incurred each time an - // accessor is removed. - mutable std::vector m_list_accessors; - mutable std::atomic m_list_accessors_contains_tombstones; - - std::shared_ptr get_ptr(size_t row_ndx) const; - - void do_nullify_link(size_t row_ndx, size_t old_target_row_ndx) override; - void do_update_link(size_t row_ndx, size_t old_target_row_ndx, size_t new_target_row_ndx) override; - void do_swap_link(size_t row_ndx, size_t target_row_ndx_1, size_t target_row_ndx_2) override; - - void unregister_linkview(); - ref_type get_row_ref(size_t row_ndx) const noexcept; - void set_row_ref(size_t row_ndx, ref_type new_ref); - void add_backlink(size_t target_row, size_t source_row); - void remove_backlink(size_t target_row, size_t source_row); - - // ArrayParent overrides - void update_child_ref(size_t child_ndx, ref_type new_ref) override; - ref_type get_child_ref(size_t child_ndx) const noexcept override; - - // These helpers are needed because of the way the B+-tree of links is - // traversed in cascade_break_backlinks_to() and - // cascade_break_backlinks_to_all_rows(). - void cascade_break_backlinks_to__leaf(size_t row_ndx, const Array& link_list_leaf, CascadeState&); - void cascade_break_backlinks_to_all_rows__leaf(const Array& link_list_leaf, CascadeState&); - - void discard_child_accessors() noexcept; - - template - void adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept; - - template - void adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept; - - template - void adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - - template - void adj_move(size_t from_ndx, size_t to_ndx) noexcept; - - template - void adj_swap(size_t row_ndx_1, size_t row_ndx_2) noexcept; - - void prune_list_accessor_tombstones() noexcept; - void validate_list_accessors() const noexcept; - - std::pair get_to_dot_parent(size_t) const override; - - friend class BacklinkColumn; - friend class LinkView; - friend class _impl::TransactLogConvenientEncoder; -}; - - -// Implementation - -inline LinkListColumn::LinkListColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) - : LinkColumnBase(alloc, ref, table, column_ndx) -{ - m_list_accessors_contains_tombstones.store(false); -} - -inline LinkListColumn::~LinkListColumn() noexcept -{ - discard_child_accessors(); -} - -inline ref_type LinkListColumn::create(Allocator& alloc, size_t size) -{ - return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws -} - -inline bool LinkListColumn::is_nullable() const noexcept -{ - return false; -} - -inline bool LinkListColumn::has_links(size_t row_ndx) const noexcept -{ - ref_type ref = LinkColumnBase::get_as_ref(row_ndx); - return (ref != 0); -} - -inline size_t LinkListColumn::get_link_count(size_t row_ndx) const noexcept -{ - ref_type ref = LinkColumnBase::get_as_ref(row_ndx); - if (ref == 0) - return 0; - return ColumnBase::get_size_from_ref(ref, get_alloc()); -} - -inline ConstLinkViewRef LinkListColumn::get(size_t row_ndx) const -{ - return get_ptr(row_ndx); -} - -inline LinkViewRef LinkListColumn::get(size_t row_ndx) -{ - return get_ptr(row_ndx); -} - -inline bool LinkListColumn::is_null(size_t) const noexcept -{ - return false; -} - -inline void LinkListColumn::set_null(size_t) -{ - throw LogicError{LogicError::column_not_nullable}; -} - -inline void LinkListColumn::do_discard_child_accessors() noexcept -{ - discard_child_accessors(); -} - -inline ref_type LinkListColumn::get_row_ref(size_t row_ndx) const noexcept -{ - return LinkColumnBase::get_as_ref(row_ndx); -} - -inline void LinkListColumn::set_row_ref(size_t row_ndx, ref_type new_ref) -{ - LinkColumnBase::set(row_ndx, new_ref); // Throws -} - -inline void LinkListColumn::add_backlink(size_t target_row, size_t source_row) -{ - m_backlink_column->add_backlink(target_row, source_row); // Throws -} - -inline void LinkListColumn::remove_backlink(size_t target_row, size_t source_row) -{ - m_backlink_column->remove_one_backlink(target_row, source_row); // Throws -} - - -} // namespace realm - -#endif // REALM_COLUMN_LINKLIST_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_mixed.hpp b/Lesson14/Pods/Realm/include/core/realm/column_mixed.hpp deleted file mode 100644 index 5f74c41..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_mixed.hpp +++ /dev/null @@ -1,265 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_MIXED_HPP -#define REALM_COLUMN_MIXED_HPP - -#include - -#include -#include -#include -#include -#include - - -namespace realm { - - -// Pre-declarations -class BinaryColumn; - - -/// A mixed column (MixedColumn) is composed of three subcolumns. The first -/// subcolumn is an integer column (Column) and stores value types. The second -/// one stores values and is a subtable parent column (SubtableColumnBase), -/// which is a subclass of an integer column (Column). The last one is a binary -/// column (BinaryColumn) and stores additional data for values of type string -/// or binary data. The last subcolumn is optional. The root of a mixed column -/// is an array node of type Array that stores the root refs of the subcolumns. -class MixedColumn : public ColumnBaseSimple { -public: - /// Create a mixed column wrapper and attach it to a preexisting - /// underlying structure of arrays. - /// - /// \param alloc The memory allocator to change the underlying - /// structure in memory. - /// - /// \param ref The memory reference of the MixedColumn for which - /// this accessor should be creator for. - /// - /// \param table If this column is used as part of a table you - /// must pass a pointer to that table. Otherwise you must pass - /// null - /// - /// \param column_ndx If this column is used as part of a table - /// you must pass the logical index of the column within that - /// table. Otherwise you should pass zero. - MixedColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); - - ~MixedColumn() noexcept override; - - DataType get_type(size_t ndx) const noexcept; - size_t size() const noexcept final - { - return m_types->size(); - } - bool is_empty() const noexcept - { - return size() == 0; - } - - int64_t get_int(size_t ndx) const noexcept; - bool get_bool(size_t ndx) const noexcept; - OldDateTime get_olddatetime(size_t ndx) const noexcept; - Timestamp get_timestamp(size_t ndx) const noexcept; - float get_float(size_t ndx) const noexcept; - double get_double(size_t ndx) const noexcept; - StringData get_string(size_t ndx) const noexcept; - BinaryData get_binary(size_t ndx) const noexcept; - StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept override; - - /// The returned array ref is zero if the specified row does not - /// contain a subtable. - ref_type get_subtable_ref(size_t row_ndx) const noexcept; - - /// The returned size is zero if the specified row does not - /// contain a subtable. - size_t get_subtable_size(size_t row_ndx) const noexcept; - - TableRef get_subtable_accessor(size_t row_ndx) const noexcept override; - - void discard_subtable_accessor(size_t row_ndx) noexcept override; - - /// If the value at the specified index is a subtable, return a - /// TableRef to that accessor for that subtable. Otherwise return - /// null. The accessor will be created if it does not already - /// exist. - TableRef get_subtable_tableref(size_t row_ndx); - - ConstTableRef get_subtable_tableref(size_t subtable_ndx) const; - - void set_int(size_t ndx, int64_t value); - void set_bool(size_t ndx, bool value); - void set_olddatetime(size_t ndx, OldDateTime value); - void set_timestamp(size_t ndx, Timestamp value); - void set_float(size_t ndx, float value); - void set_double(size_t ndx, double value); - void set_string(size_t ndx, StringData value) override; - void set_binary(size_t ndx, BinaryData value); - void set_subtable(size_t ndx, const Table* value); - - void insert_int(size_t ndx, int_fast64_t value); - void insert_bool(size_t ndx, bool value); - void insert_olddatetime(size_t ndx, OldDateTime value); - void insert_timestamp(size_t ndx, Timestamp value); - void insert_float(size_t ndx, float value); - void insert_double(size_t ndx, double value); - void insert_string(size_t ndx, StringData value); - void insert_binary(size_t ndx, BinaryData value); - void insert_subtable(size_t ndx, const Table* value); - - void erase(size_t row_ndx); - void move_last_over(size_t row_ndx); - void clear(); - - /// Compare two mixed columns for equality. - bool compare_mixed(const MixedColumn&) const; - - int compare_values(size_t row1, size_t row2) const noexcept override; - - void discard_child_accessors() noexcept; - - static ref_type create(Allocator&, size_t size = 0); - - static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; - - // Overriding method in ColumnBase - ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void swap_rows(size_t, size_t) override; - void clear(size_t, bool) override; - void update_from_parent(size_t) noexcept override; - void adj_acc_insert_rows(size_t, size_t) noexcept override; - void adj_acc_erase_row(size_t) noexcept override; - void adj_acc_move_over(size_t, size_t) noexcept override; - void adj_acc_swap_rows(size_t, size_t) noexcept override; - void adj_acc_move_row(size_t, size_t) noexcept override; - void adj_acc_clear_root_table() noexcept override; - void mark(int) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - - void verify() const override; - void verify(const Table&, size_t) const override; - void to_dot(std::ostream&, StringData title) const override; - void do_dump_node_structure(std::ostream&, int) const override; - -private: - enum MixedColType { - // NOTE: below numbers must be kept in sync with ColumnType - // Column types used in Mixed - mixcol_Int = 0, - mixcol_Bool = 1, - mixcol_String = 2, - // 3, used for STRING_ENUM in ColumnType - mixcol_Binary = 4, - mixcol_Table = 5, - mixcol_Mixed = 6, - mixcol_OldDateTime = 7, - mixcol_Timestamp = 8, - mixcol_Float = 9, - mixcol_Double = 10, // Positive Double - mixcol_DoubleNeg = 11, // Negative Double - mixcol_IntNeg = 12 // Negative Integers - }; - - class RefsColumn; - - /// Stores the MixedColType of each value at the given index. For - /// values that uses all 64 bits, the type also encodes the sign - /// bit by having distinct types for positive negative values. - std::unique_ptr m_types; - - /// Stores the data for each entry. For a subtable, the stored - /// value is the ref of the subtable. For string, binary data, - /// the stored value is an index within `m_binary_data`. Likewise, - /// for timestamp, an index into `m_timestamp` is stored. For other - /// types the stored value is itself. Since we only have 63 bits - /// available for a non-ref value, the sign of numeric values is - /// encoded as part of the type in `m_types`. - std::unique_ptr m_data; - - /// For string and binary data types, the bytes are stored here. - std::unique_ptr m_binary_data; - - /// Timestamps are stored here. - std::unique_ptr m_timestamp_data; - - void do_erase(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows); - void do_move_last_over(size_t row_ndx, size_t prior_num_rows); - void do_swap_rows(size_t, size_t); - void do_clear(size_t num_rows); - - void create(Allocator&, ref_type, Table*, size_t column_ndx); - void ensure_binary_data_column(); - void ensure_timestamp_column(); - - MixedColType clear_value(size_t ndx, MixedColType new_type); // Returns old type - void clear_value_and_discard_subtab_acc(size_t ndx, MixedColType new_type); - - // Get/set/insert 64-bit values in m_data/m_types - int64_t get_value(size_t ndx) const noexcept; - void set_value(size_t ndx, int64_t value, MixedColType); - void set_int64(size_t ndx, int64_t value, MixedColType pos_type, MixedColType neg_type); - - void insert_value(size_t row_ndx, int_fast64_t types_value, int_fast64_t data_value); - void insert_int(size_t ndx, int_fast64_t value, MixedColType type); - void insert_pos_neg(size_t ndx, int_fast64_t value, MixedColType pos_type, MixedColType neg_type); - - void do_discard_child_accessors() noexcept override; - -#ifdef REALM_DEBUG - void do_verify(const Table*, size_t col_ndx) const; -#endif - void leaf_to_dot(MemRef, ArrayParent*, size_t, std::ostream&) const override; -}; - -// LCOV_EXCL_START -inline StringData MixedColumn::get_index_data(size_t, StringIndex::StringConversionBuffer&) const noexcept -{ - REALM_ASSERT(false && "Index not supported for MixedColumn yet."); - REALM_UNREACHABLE(); - return {}; -} -// LCOV_EXCL_STOP - - -class MixedColumn::RefsColumn : public SubtableColumnBase { -public: - RefsColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); - ~RefsColumn() noexcept override; - - using SubtableColumnBase::get_subtable_tableref; - - void refresh_accessor_tree(size_t, const Spec&) override; - - friend class MixedColumn; -}; - - -} // namespace realm - - -// Implementation -#include - - -#endif // REALM_COLUMN_MIXED_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_mixed_tpl.hpp b/Lesson14/Pods/Realm/include/core/realm/column_mixed_tpl.hpp deleted file mode 100644 index 5afdddc..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_mixed_tpl.hpp +++ /dev/null @@ -1,514 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -#include -#include - -namespace realm { - -inline MixedColumn::MixedColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) - : ColumnBaseSimple(column_ndx) -{ - create(alloc, ref, table, column_ndx); -} - -inline void MixedColumn::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept -{ - m_data->adj_acc_insert_rows(row_ndx, num_rows); -} - -inline void MixedColumn::adj_acc_erase_row(size_t row_ndx) noexcept -{ - m_data->adj_acc_erase_row(row_ndx); -} - -inline void MixedColumn::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept -{ - m_data->adj_acc_swap_rows(row_ndx_1, row_ndx_2); -} - -inline void MixedColumn::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept -{ - m_data->adj_acc_move_row(from_ndx, to_ndx); -} - -inline void MixedColumn::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept -{ - m_data->adj_acc_move_over(from_row_ndx, to_row_ndx); -} - -inline void MixedColumn::adj_acc_clear_root_table() noexcept -{ - m_data->adj_acc_clear_root_table(); -} - -inline ref_type MixedColumn::get_subtable_ref(size_t row_ndx) const noexcept -{ - REALM_ASSERT_3(row_ndx, <, m_types->size()); - if (m_types->get(row_ndx) != type_Table) - return 0; - return m_data->get_as_ref(row_ndx); -} - -inline size_t MixedColumn::get_subtable_size(size_t row_ndx) const noexcept -{ - ref_type top_ref = get_subtable_ref(row_ndx); - if (top_ref == 0) - return 0; - return _impl::TableFriend::get_size_from_ref(top_ref, m_data->get_alloc()); -} - -inline TableRef MixedColumn::get_subtable_accessor(size_t row_ndx) const noexcept -{ - return m_data->get_subtable_accessor(row_ndx); -} - -inline void MixedColumn::discard_subtable_accessor(size_t row_ndx) noexcept -{ - m_data->discard_subtable_accessor(row_ndx); -} - -inline TableRef MixedColumn::get_subtable_tableref(size_t row_ndx) -{ - REALM_ASSERT_3(row_ndx, <, m_types->size()); - if (m_types->get(row_ndx) != type_Table) - return {}; - return m_data->get_subtable_tableref(row_ndx); // Throws -} - -inline ConstTableRef MixedColumn::get_subtable_tableref(size_t subtable_ndx) const -{ - return const_cast(this)->get_subtable_tableref(subtable_ndx); -} - -inline void MixedColumn::discard_child_accessors() noexcept -{ - m_data->discard_child_accessors(); -} - - -// -// Getters -// - -#define REALM_BIT63 0x8000000000000000ULL - -inline int64_t MixedColumn::get_value(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - - // Shift the unsigned value right - ensuring 0 gets in from left. - // Shifting signed integers right doesn't ensure 0's. - uint64_t value = uint64_t(m_data->get(ndx)) >> 1; - return int64_t(value); -} - -inline int64_t MixedColumn::get_int(size_t ndx) const noexcept -{ - // Get first 63 bits of the integer value - int64_t value = get_value(ndx); - - // restore 'sign'-bit from the column-type - MixedColType col_type = MixedColType(m_types->get(ndx)); - if (col_type == mixcol_IntNeg) { - // FIXME: Bad cast of result of '|' from unsigned to signed - value |= REALM_BIT63; // set sign bit (63) - } - else { - REALM_ASSERT_3(col_type, ==, mixcol_Int); - } - return value; -} - -inline bool MixedColumn::get_bool(size_t ndx) const noexcept -{ - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Bool); - - return (get_value(ndx) != 0); -} - -inline OldDateTime MixedColumn::get_olddatetime(size_t ndx) const noexcept -{ - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_OldDateTime); - - return OldDateTime(get_value(ndx)); -} - -inline float MixedColumn::get_float(size_t ndx) const noexcept -{ - static_assert(std::numeric_limits::is_iec559, "'float' is not IEEE"); - static_assert((sizeof(float) * CHAR_BIT == 32), "Assume 32 bit float."); - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Float); - - return type_punning(get_value(ndx)); -} - -inline double MixedColumn::get_double(size_t ndx) const noexcept -{ - static_assert(std::numeric_limits::is_iec559, "'double' is not IEEE"); - static_assert((sizeof(double) * CHAR_BIT == 64), "Assume 64 bit double."); - - int64_t int_val = get_value(ndx); - - // restore 'sign'-bit from the column-type - MixedColType col_type = MixedColType(m_types->get(ndx)); - if (col_type == mixcol_DoubleNeg) - int_val |= REALM_BIT63; // set sign bit (63) - else { - REALM_ASSERT_3(col_type, ==, mixcol_Double); - } - return type_punning(int_val); -} - -inline StringData MixedColumn::get_string(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_String); - REALM_ASSERT(m_binary_data); - - size_t data_ndx = size_t(int64_t(m_data->get(ndx)) >> 1); - return m_binary_data->get_string(data_ndx); -} - -inline BinaryData MixedColumn::get_binary(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Binary); - REALM_ASSERT(m_binary_data); - - size_t data_ndx = size_t(uint64_t(m_data->get(ndx)) >> 1); - return m_binary_data->get(data_ndx); -} - -inline Timestamp MixedColumn::get_timestamp(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - REALM_ASSERT_3(m_types->get(ndx), ==, mixcol_Timestamp); - REALM_ASSERT(m_timestamp_data); - size_t data_ndx = size_t(uint64_t(m_data->get(ndx)) >> 1); - return m_timestamp_data->get(data_ndx); -} - -// -// Setters -// - -// Set a int64 value. -// Store 63 bit of the value in m_data. Store sign bit in m_types. - -inline void MixedColumn::set_int64(size_t ndx, int64_t value, MixedColType pos_type, MixedColType neg_type) -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - - // If sign-bit is set in value, 'store' it in the column-type - MixedColType coltype = ((value & REALM_BIT63) == 0) ? pos_type : neg_type; - - // Remove refs or binary data (sets type to double) - clear_value_and_discard_subtab_acc(ndx, coltype); // Throws - - // Shift value one bit and set lowest bit to indicate that this is not a ref - value = (value << 1) + 1; - m_data->set(ndx, value); -} - -inline void MixedColumn::set_int(size_t ndx, int64_t value) -{ - set_int64(ndx, value, mixcol_Int, mixcol_IntNeg); // Throws -} - -inline void MixedColumn::set_double(size_t ndx, double value) -{ - int64_t val64 = type_punning(value); - set_int64(ndx, val64, mixcol_Double, mixcol_DoubleNeg); // Throws -} - -inline void MixedColumn::set_value(size_t ndx, int64_t value, MixedColType coltype) -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - - // Remove refs or binary data (sets type to float) - clear_value_and_discard_subtab_acc(ndx, coltype); // Throws - - // Shift value one bit and set lowest bit to indicate that this is not a ref - int64_t v = (value << 1) + 1; - m_data->set(ndx, v); // Throws -} - -inline void MixedColumn::set_float(size_t ndx, float value) -{ - int64_t val64 = type_punning(value); - set_value(ndx, val64, mixcol_Float); // Throws -} - -inline void MixedColumn::set_bool(size_t ndx, bool value) -{ - set_value(ndx, (value ? 1 : 0), mixcol_Bool); // Throws -} - -inline void MixedColumn::set_olddatetime(size_t ndx, OldDateTime value) -{ - set_value(ndx, int64_t(value.get_olddatetime()), mixcol_OldDateTime); // Throws -} - -inline void MixedColumn::set_subtable(size_t ndx, const Table* t) -{ - REALM_ASSERT_3(ndx, <, m_types->size()); - typedef _impl::TableFriend tf; - ref_type ref; - if (t) { - ref = tf::clone(*t, get_alloc()); // Throws - } - else { - ref = tf::create_empty_table(get_alloc()); // Throws - } - // Remove any previous refs or binary data - clear_value_and_discard_subtab_acc(ndx, mixcol_Table); // Throws - m_data->set(ndx, ref); // Throws -} - -// -// Inserts -// - -inline void MixedColumn::insert_value(size_t row_ndx, int_fast64_t types_value, int_fast64_t data_value) -{ - size_t types_size = m_types->size(); // Slow - bool is_append = row_ndx == types_size; - size_t row_ndx_2 = is_append ? realm::npos : row_ndx; - size_t num_rows = 1; - m_types->insert_without_updating_index(row_ndx_2, types_value, num_rows); // Throws - m_data->do_insert(row_ndx_2, data_value, num_rows); // Throws -} - -// Insert a int64 value. -// Store 63 bit of the value in m_data. Store sign bit in m_types. - -inline void MixedColumn::insert_int(size_t ndx, int_fast64_t value, MixedColType type) -{ - int_fast64_t types_value = type; - // Shift value one bit and set lowest bit to indicate that this is not a ref - int_fast64_t data_value = 1 + (value << 1); - insert_value(ndx, types_value, data_value); // Throws -} - -inline void MixedColumn::insert_pos_neg(size_t ndx, int_fast64_t value, MixedColType pos_type, MixedColType neg_type) -{ - // 'store' the sign-bit in the integer-type - MixedColType type = (value & REALM_BIT63) == 0 ? pos_type : neg_type; - int_fast64_t types_value = type; - // Shift value one bit and set lowest bit to indicate that this is not a ref - int_fast64_t data_value = 1 + (value << 1); - insert_value(ndx, types_value, data_value); // Throws -} - -inline void MixedColumn::insert_int(size_t ndx, int_fast64_t value) -{ - insert_pos_neg(ndx, value, mixcol_Int, mixcol_IntNeg); // Throws -} - -inline void MixedColumn::insert_double(size_t ndx, double value) -{ - int_fast64_t value_2 = type_punning(value); - insert_pos_neg(ndx, value_2, mixcol_Double, mixcol_DoubleNeg); // Throws -} - -inline void MixedColumn::insert_float(size_t ndx, float value) -{ - int_fast64_t value_2 = type_punning(value); - insert_int(ndx, value_2, mixcol_Float); // Throws -} - -inline void MixedColumn::insert_bool(size_t ndx, bool value) -{ - int_fast64_t value_2 = int_fast64_t(value); - insert_int(ndx, value_2, mixcol_Bool); // Throws -} - -inline void MixedColumn::insert_olddatetime(size_t ndx, OldDateTime value) -{ - int_fast64_t value_2 = int_fast64_t(value.get_olddatetime()); - insert_int(ndx, value_2, mixcol_OldDateTime); // Throws -} - -inline void MixedColumn::insert_timestamp(size_t ndx, Timestamp value) -{ - ensure_timestamp_column(); - size_t data_ndx = m_timestamp_data->size(); - m_timestamp_data->add(value); // Throws - insert_int(ndx, int_fast64_t(data_ndx), mixcol_Timestamp); -} - -inline void MixedColumn::insert_string(size_t ndx, StringData value) -{ - ensure_binary_data_column(); - size_t blob_ndx = m_binary_data->size(); - m_binary_data->add_string(value); // Throws - - int_fast64_t value_2 = int_fast64_t(blob_ndx); - insert_int(ndx, value_2, mixcol_String); // Throws -} - -inline void MixedColumn::insert_binary(size_t ndx, BinaryData value) -{ - ensure_binary_data_column(); - size_t blob_ndx = m_binary_data->size(); - m_binary_data->add(value); // Throws - - int_fast64_t value_2 = int_fast64_t(blob_ndx); - insert_int(ndx, value_2, mixcol_Binary); // Throws -} - -inline void MixedColumn::insert_subtable(size_t ndx, const Table* t) -{ - typedef _impl::TableFriend tf; - ref_type ref; - if (t) { - ref = tf::clone(*t, get_alloc()); // Throws - } - else { - ref = tf::create_empty_table(get_alloc()); // Throws - } - int_fast64_t types_value = mixcol_Table; - int_fast64_t data_value = int_fast64_t(ref); - insert_value(ndx, types_value, data_value); // Throws -} - -inline void MixedColumn::erase(size_t row_ndx) -{ - size_t num_rows_to_erase = 1; - size_t prior_num_rows = size(); // Note that size() is slow - do_erase(row_ndx, num_rows_to_erase, prior_num_rows); // Throws -} - -inline void MixedColumn::move_last_over(size_t row_ndx) -{ - size_t prior_num_rows = size(); // Note that size() is slow - do_move_last_over(row_ndx, prior_num_rows); // Throws -} - -inline void MixedColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2) -{ - do_swap_rows(row_ndx_1, row_ndx_2); -} - -inline void MixedColumn::clear() -{ - size_t num_rows = size(); // Note that size() is slow - do_clear(num_rows); // Throws -} - -inline size_t MixedColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept -{ - const char* root_header = alloc.translate(root_ref); - ref_type types_ref = to_ref(Array::get(root_header, 0)); - return IntegerColumn::get_size_from_ref(types_ref, alloc); -} - -inline void MixedColumn::clear_value_and_discard_subtab_acc(size_t row_ndx, MixedColType new_type) -{ - MixedColType old_type = clear_value(row_ndx, new_type); - if (old_type == mixcol_Table) - m_data->discard_subtable_accessor(row_ndx); -} - -// Implementing pure virtual method of ColumnBase. -inline void MixedColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, - bool insert_nulls) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - REALM_ASSERT(!insert_nulls); - - size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); - - int_fast64_t type_value = mixcol_Int; - m_types->insert_without_updating_index(row_ndx_2, type_value, num_rows_to_insert); // Throws - - // The least significant bit indicates that the rest of the bits form an - // integer value, so 1 is actually zero. - int_fast64_t data_value = 1; - m_data->do_insert(row_ndx_2, data_value, num_rows_to_insert); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void MixedColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) -{ - do_erase(row_ndx, num_rows_to_erase, prior_num_rows); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void MixedColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) -{ - do_move_last_over(row_ndx, prior_num_rows); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void MixedColumn::clear(size_t num_rows, bool) -{ - do_clear(num_rows); // Throws -} - -inline void MixedColumn::mark(int type) noexcept -{ - m_data->mark(type); -} - -inline void MixedColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) -{ - ColumnBaseSimple::refresh_accessor_tree(col_ndx, spec); - - get_root_array()->init_from_parent(); - m_types->refresh_accessor_tree(col_ndx, spec); // Throws - m_data->refresh_accessor_tree(col_ndx, spec); // Throws - - m_binary_data.reset(); - // See if m_binary_data needs to be created. - if (get_root_array()->size() >= 3) { - ref_type ref = get_root_array()->get_as_ref(2); - m_binary_data.reset(new BinaryColumn(get_alloc(), ref)); // Throws - m_binary_data->set_parent(get_root_array(), 2); - } - - m_timestamp_data.reset(); - // See if m_timestamp_data needs to be created. - if (get_root_array()->size() >= 4) { - ref_type ref = get_root_array()->get_as_ref(3); - // When adding/creating a Mixed column the user cannot specify nullability, so the "true" below - // makes it implicitly nullable, which may not be wanted. But it's OK since Mixed columns are not - // publicly supported - m_timestamp_data.reset(new TimestampColumn(true /*fixme*/, get_alloc(), ref)); // Throws - m_timestamp_data->set_parent(get_root_array(), 3); - } - - if (m_binary_data) { - REALM_ASSERT_3(get_root_array()->size(), >=, 3); - m_binary_data->refresh_accessor_tree(col_ndx, spec); // Throws - } - if (m_timestamp_data) { - REALM_ASSERT_3(get_root_array()->size(), >=, 4); - m_timestamp_data->refresh_accessor_tree(col_ndx, spec); // Throws - } -} - -inline void MixedColumn::RefsColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) -{ - SubtableColumnBase::refresh_accessor_tree(col_ndx, spec); // Throws - m_subtable_map.refresh_accessor_tree(); // Throws -} - -} // namespace realm diff --git a/Lesson14/Pods/Realm/include/core/realm/column_string.hpp b/Lesson14/Pods/Realm/include/core/realm/column_string.hpp deleted file mode 100644 index e7693ee..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_string.hpp +++ /dev/null @@ -1,377 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_STRING_HPP -#define REALM_COLUMN_STRING_HPP - -#include -#include -#include -#include -#include -#include - -namespace realm { - -// Pre-declarations -class StringIndex; - - -/// A string column (StringColumn) is a single B+-tree, and -/// the root of the column is the root of the B+-tree. Leaf nodes are -/// either of type ArrayString (array of small strings), -/// ArrayStringLong (array of medium strings), or ArrayBigBlobs (array -/// of big strings). -/// -/// A string column can optionally be equipped with a search index. If -/// it is, then the root ref of the index is stored in -/// Table::m_columns immediately after the root ref of the string -/// column. -class StringColumn : public ColumnBaseSimple { -public: - typedef StringData value_type; - - StringColumn(Allocator&, ref_type, bool nullable = false, size_t column_ndx = npos); - ~StringColumn() noexcept override; - - void destroy() noexcept override; - - size_t size() const noexcept final; - bool is_empty() const noexcept - { - return size() == 0; - } - - bool is_null(size_t ndx) const noexcept final; - void set_null(size_t ndx) final; - StringData get(size_t ndx) const noexcept; - void set(size_t ndx, StringData); - void add(); - void add(StringData value); - void insert(size_t ndx); - void insert(size_t ndx, StringData value); - void erase(size_t row_ndx); - void move_last_over(size_t row_ndx); - void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; - void clear(); - - size_t count(StringData value) const; - size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const; - void find_all(IntegerColumn& result, StringData value, size_t begin = 0, size_t end = npos) const; - FindRes find_all_no_copy(StringData value, InternalFindResult& result) const; - - int compare_values(size_t, size_t) const noexcept override; - - //@{ - /// Find the lower/upper bound for the specified value assuming - /// that the elements are already sorted in ascending order - /// according to StringData::operator<(). - size_t lower_bound_string(StringData value) const noexcept; - size_t upper_bound_string(StringData value) const noexcept; - //@} - - void set_string(size_t, StringData) override; - - bool is_nullable() const noexcept final; - - // Search index - StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept final; - bool has_search_index() const noexcept override; - void set_search_index_ref(ref_type, ArrayParent*, size_t) override; - StringIndex* get_search_index() noexcept override; - const StringIndex* get_search_index() const noexcept override; - std::unique_ptr release_search_index() noexcept; - bool supports_search_index() const noexcept final - { - return true; - } - StringIndex* create_search_index() override; - - // Simply inserts all column values in the index in a loop - void populate_search_index(); - void destroy_search_index() noexcept override; - - // Optimizing data layout. enforce == true will enforce enumeration; - // enforce == false will auto-evaluate if it should be enumerated or not - bool auto_enumerate(ref_type& keys, ref_type& values, bool enforce = false) const; - - /// Compare two string columns for equality. - bool compare_string(const StringColumn&) const; - - enum LeafType { - leaf_type_Small, ///< ArrayString - leaf_type_Medium, ///< ArrayStringLong - leaf_type_Big ///< ArrayBigBlobs - }; - - std::unique_ptr get_leaf(size_t ndx, size_t& out_ndx_in_parent, LeafType& out_leaf_type) const; - - static ref_type create(Allocator&, size_t size = 0); - - static size_t get_size_from_ref(ref_type root_ref, Allocator&) noexcept; - - // Overrriding method in ColumnBase - ref_type write(size_t, size_t, size_t, _impl::OutputStream&) const override; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void clear(size_t, bool) override; - void set_ndx_in_parent(size_t ndx_in_parent) noexcept override; - void update_from_parent(size_t old_baseline) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - - void verify() const override; - void verify(const Table&, size_t) const override; - void to_dot(std::ostream&, StringData title) const override; - void do_dump_node_structure(std::ostream&, int) const override; - -private: - std::unique_ptr m_search_index; - bool m_nullable; - - LeafType get_block(size_t ndx, ArrayParent**, size_t& off, bool use_retval = false) const; - - /// If you are appending and have the size of the column readily available, - /// call the 4 argument version instead. If you are not appending, either - /// one is fine. - /// - /// \param row_ndx Must be `realm::npos` if appending. - void do_insert(size_t row_ndx, StringData value, size_t num_rows); - - /// If you are appending and you do not have the size of the column readily - /// available, call the 3 argument version instead. If you are not - /// appending, either one is fine. - /// - /// \param is_append Must be true if, and only if `row_ndx` is equal to the - /// size of the column (before insertion). - void do_insert(size_t row_ndx, StringData value, size_t num_rows, bool is_append); - - /// \param row_ndx Must be `realm::npos` if appending. - void bptree_insert(size_t row_ndx, StringData value, size_t num_rows); - - // Called by Array::bptree_insert(). - static ref_type leaf_insert(MemRef leaf_mem, ArrayParent&, size_t ndx_in_parent, Allocator&, size_t insert_ndx, - BpTreeNode::TreeInsert& state); - - class EraseLeafElem; - class CreateHandler; - class SliceHandler; - - void do_erase(size_t row_ndx, bool is_last); - void do_move_last_over(size_t row_ndx, size_t last_row_ndx); - void do_swap_rows(size_t row_ndx_1, size_t row_ndx_2); - void do_clear(); - - /// Root must be a leaf. Upgrades the root leaf as - /// necessary. Returns the type of the root leaf as it is upon - /// return. - LeafType upgrade_root_leaf(size_t value_size); - - void refresh_root_accessor(); - - void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; - - friend class BpTreeNode; - friend class ColumnBase; -}; - - -// Implementation: - -inline size_t StringColumn::size() const noexcept -{ - if (root_is_leaf()) { - bool long_strings = m_array->has_refs(); - if (!long_strings) { - // Small strings root leaf - ArrayString* leaf = static_cast(m_array.get()); - return leaf->size(); - } - bool is_big = m_array->get_context_flag(); - if (!is_big) { - // Medium strings root leaf - ArrayStringLong* leaf = static_cast(m_array.get()); - return leaf->size(); - } - // Big strings root leaf - ArrayBigBlobs* leaf = static_cast(m_array.get()); - return leaf->size(); - } - // Non-leaf root - BpTreeNode* node = static_cast(m_array.get()); - return node->get_bptree_size(); -} - -inline void StringColumn::add(StringData value) -{ - REALM_ASSERT(!(value.is_null() && !m_nullable)); - size_t row_ndx = realm::npos; - size_t num_rows = 1; - do_insert(row_ndx, value, num_rows); // Throws -} - -inline void StringColumn::add() -{ - add(m_nullable ? realm::null() : StringData("")); -} - -inline void StringColumn::insert(size_t row_ndx, StringData value) -{ - REALM_ASSERT(!(value.is_null() && !m_nullable)); - size_t column_size = this->size(); - REALM_ASSERT_3(row_ndx, <=, column_size); - size_t num_rows = 1; - bool is_append = row_ndx == column_size; - do_insert(row_ndx, value, num_rows, is_append); // Throws -} - -inline void StringColumn::insert(size_t row_ndx) -{ - insert(row_ndx, m_nullable ? realm::null() : StringData("")); -} - -inline void StringColumn::erase(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - bool is_last = row_ndx == last_row_ndx; - do_erase(row_ndx, is_last); // Throws -} - -inline void StringColumn::move_last_over(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -inline void StringColumn::swap_rows(size_t row_ndx_1, size_t row_ndx_2) -{ - do_swap_rows(row_ndx_1, row_ndx_2); // Throws -} - -inline void StringColumn::clear() -{ - do_clear(); // Throws -} - -inline int StringColumn::compare_values(size_t row1, size_t row2) const noexcept -{ - StringData a = get(row1); - StringData b = get(row2); - - if (a.is_null() && !b.is_null()) - return 1; - else if (b.is_null() && !a.is_null()) - return -1; - else if (a.is_null() && b.is_null()) - return 0; - - if (a == b) - return 0; - return utf8_compare(a, b) ? 1 : -1; -} - -inline void StringColumn::set_string(size_t row_ndx, StringData value) -{ - REALM_ASSERT(!(value.is_null() && !m_nullable)); - set(row_ndx, value); // Throws -} - -inline bool StringColumn::has_search_index() const noexcept -{ - return m_search_index != 0; -} - -inline StringIndex* StringColumn::get_search_index() noexcept -{ - return m_search_index.get(); -} - -inline const StringIndex* StringColumn::get_search_index() const noexcept -{ - return m_search_index.get(); -} - -inline size_t StringColumn::get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept -{ - const char* root_header = alloc.translate(root_ref); - bool root_is_leaf = !Array::get_is_inner_bptree_node_from_header(root_header); - if (root_is_leaf) { - bool long_strings = Array::get_hasrefs_from_header(root_header); - if (!long_strings) { - // Small strings leaf - return ArrayString::get_size_from_header(root_header); - } - bool is_big = Array::get_context_flag_from_header(root_header); - if (!is_big) { - // Medium strings leaf - return ArrayStringLong::get_size_from_header(root_header, alloc); - } - // Big strings leaf - return ArrayBigBlobs::get_size_from_header(root_header); - } - - return BpTreeNode::get_bptree_size_from_header(root_header); -} - -// Implementing pure virtual method of ColumnBase. -inline void StringColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, - bool insert_nulls) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - REALM_ASSERT(!insert_nulls || m_nullable); - - StringData value = m_nullable ? realm::null() : StringData(""); - bool is_append = (row_ndx == prior_num_rows); - do_insert(row_ndx, value, num_rows_to_insert, is_append); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void StringColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(num_rows_to_erase <= prior_num_rows); - REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); - - bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); - for (size_t i = num_rows_to_erase; i > 0; --i) { - size_t row_ndx_2 = row_ndx + i - 1; - do_erase(row_ndx_2, is_last); // Throws - } -} - -// Implementing pure virtual method of ColumnBase. -inline void StringColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx < prior_num_rows); - - size_t last_row_ndx = prior_num_rows - 1; - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -// Implementing pure virtual method of ColumnBase. -inline void StringColumn::clear(size_t, bool) -{ - do_clear(); // Throws -} - -} // namespace realm - -#endif // REALM_COLUMN_STRING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_string_enum.hpp b/Lesson14/Pods/Realm/include/core/realm/column_string_enum.hpp deleted file mode 100644 index a73fe0c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_string_enum.hpp +++ /dev/null @@ -1,311 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_STRING_ENUM_HPP -#define REALM_COLUMN_STRING_ENUM_HPP - -#include - -namespace realm { - -// Pre-declarations -class StringIndex; - - -/// From the point of view of the application, an enumerated strings column -/// (StringEnumColumn) is like a string column (StringColumn), yet it manages -/// its strings in such a way that each unique string is stored only once. In -/// fact, an enumerated strings column is a combination of two subcolumns; a -/// regular string column (StringColumn) that stores the unique strings, and an -/// integer column that stores one unique string index for each entry in the -/// enumerated strings column. -/// -/// In terms of the underlying node structure, the subcolumn containing the -/// unique strings is not a true part of the enumerated strings column. Instead -/// it is a part of the spec structure that describes the table of which the -/// enumerated strings column is a part. This way, the unique strings can be -/// shared across enumerated strings columns of multiple subtables. This also -/// means that the root of an enumerated strings column coincides with the root -/// of the integer subcolumn, and in some sense, an enumerated strings column is -/// just the integer subcolumn. -/// -/// An enumerated strings column can optionally be equipped with a -/// search index. If it is, then the root ref of the index is stored -/// in Table::m_columns immediately after the root ref of the -/// enumerated strings column. -class StringEnumColumn : public IntegerColumn { -public: - typedef StringData value_type; - - StringEnumColumn(Allocator&, ref_type ref, ref_type keys_ref, bool nullable, size_t column_ndx = npos); - ~StringEnumColumn() noexcept override; - void destroy() noexcept override; - MemRef clone_deep(Allocator& alloc) const override; - - int compare_values(size_t row1, size_t row2) const noexcept override - { - StringData a = get(row1); - StringData b = get(row2); - - if (a.is_null() && !b.is_null()) - return 1; - else if (b.is_null() && !a.is_null()) - return -1; - else if (a.is_null() && b.is_null()) - return 0; - - if (a == b) - return 0; - - return utf8_compare(a, b) ? 1 : -1; - } - - StringData get(size_t ndx) const noexcept; - bool is_null(size_t ndx) const noexcept final; - void set(size_t ndx, StringData value); - void set_null(size_t ndx) override; - void add(); - void add(StringData value); - void insert(size_t ndx); - void insert(size_t ndx, StringData value); - void erase(size_t row_ndx); - void move_last_over(size_t row_ndx); - void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; - void clear(); - bool is_nullable() const noexcept final; - - size_t count(StringData value) const; - size_t find_first(StringData value, size_t begin = 0, size_t end = npos) const; - void find_all(IntegerColumn& res, StringData value, size_t begin = 0, size_t end = npos) const; - FindRes find_all_no_copy(StringData value, InternalFindResult& result) const; - - size_t count(size_t key_index) const; - size_t find_first(size_t key_index, size_t begin = 0, size_t end = -1) const; - void find_all(IntegerColumn& res, size_t key_index, size_t begin = 0, size_t end = -1) const; - - //@{ - /// Find the lower/upper bound for the specified value assuming - /// that the elements are already sorted in ascending order - /// according to StringData::operator<(). - size_t lower_bound_string(StringData value) const noexcept; - size_t upper_bound_string(StringData value) const noexcept; - //@} - - void set_string(size_t, StringData) override; - - void adjust_keys_ndx_in_parent(int diff) noexcept; - - // Search index - StringData get_index_data(size_t ndx, StringIndex::StringConversionBuffer& buffer) const noexcept final; - bool supports_search_index() const noexcept final - { - return true; - } - StringIndex* create_search_index() override; - void install_search_index(std::unique_ptr) noexcept; - void destroy_search_index() noexcept override; - - // Compare two string columns for equality - bool compare_string(const StringColumn&) const; - bool compare_string(const StringEnumColumn&) const; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void clear(size_t, bool) override; - void update_from_parent(size_t) noexcept override; - void refresh_accessor_tree(size_t, const Spec&) override; - - size_t get_key_ndx(StringData value) const; - size_t get_key_ndx_or_add(StringData value); - - StringColumn& get_keys(); - const StringColumn& get_keys() const; - -#ifdef REALM_DEBUG - void verify() const override; - void verify(const Table&, size_t) const override; - void do_dump_node_structure(std::ostream&, int) const override; - void to_dot(std::ostream&, StringData title) const override; -#endif - -private: - // Member variables - StringColumn m_keys; - bool m_nullable; - - /// If you are appending and have the size of the column readily available, - /// call the 4 argument version instead. If you are not appending, either - /// one is fine. - /// - /// \param row_ndx Must be `realm::npos` if appending. - void do_insert(size_t row_ndx, StringData value, size_t num_rows); - - /// If you are appending and you do not have the size of the column readily - /// available, call the 3 argument version instead. If you are not - /// appending, either one is fine. - /// - /// \param is_append Must be true if, and only if `row_ndx` is equal to the - /// size of the column (before insertion). - void do_insert(size_t row_ndx, StringData value, size_t num_rows, bool is_append); - - void do_erase(size_t row_ndx, bool is_last); - void do_move_last_over(size_t row_ndx, size_t last_row_ndx); - void do_clear(); -}; - - -// Implementation: - -inline StringData StringEnumColumn::get(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, IntegerColumn::size()); - size_t key_ndx = to_size_t(IntegerColumn::get(ndx)); - StringData sd = m_keys.get(key_ndx); - REALM_ASSERT_DEBUG(!(!m_nullable && sd.is_null())); - return sd; -} - -inline bool StringEnumColumn::is_null(size_t ndx) const noexcept -{ - return is_nullable() && get(ndx).is_null(); -} - -inline void StringEnumColumn::add() -{ - add(m_nullable ? realm::null() : StringData("")); -} - -inline void StringEnumColumn::add(StringData value) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - size_t row_ndx = realm::npos; - size_t num_rows = 1; - do_insert(row_ndx, value, num_rows); // Throws -} - -inline void StringEnumColumn::insert(size_t row_ndx) -{ - insert(row_ndx, m_nullable ? realm::null() : StringData("")); -} - -inline void StringEnumColumn::insert(size_t row_ndx, StringData value) -{ - REALM_ASSERT_DEBUG(!(!m_nullable && value.is_null())); - size_t column_size = this->size(); - REALM_ASSERT_3(row_ndx, <=, column_size); - size_t num_rows = 1; - bool is_append = row_ndx == column_size; - do_insert(row_ndx, value, num_rows, is_append); // Throws -} - -inline void StringEnumColumn::erase(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - bool is_last = row_ndx == last_row_ndx; - do_erase(row_ndx, is_last); // Throws -} - -inline void StringEnumColumn::move_last_over(size_t row_ndx) -{ - size_t last_row_ndx = size() - 1; // Note that size() is slow - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -inline void StringEnumColumn::clear() -{ - do_clear(); // Throws -} - -// Overriding virtual method of Column. -inline void StringEnumColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, - bool insert_nulls) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - REALM_ASSERT(!insert_nulls || m_nullable); - - StringData value = m_nullable ? realm::null() : StringData(""); - bool is_append = (row_ndx == prior_num_rows); - do_insert(row_ndx, value, num_rows_to_insert, is_append); // Throws -} - -// Overriding virtual method of Column. -inline void StringEnumColumn::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(num_rows_to_erase <= prior_num_rows); - REALM_ASSERT(row_ndx <= prior_num_rows - num_rows_to_erase); - - bool is_last = (row_ndx + num_rows_to_erase == prior_num_rows); - for (size_t i = num_rows_to_erase; i > 0; --i) { - size_t row_ndx_2 = row_ndx + i - 1; - do_erase(row_ndx_2, is_last); // Throws - } -} - -// Overriding virtual method of Column. -inline void StringEnumColumn::move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx < prior_num_rows); - - size_t last_row_ndx = prior_num_rows - 1; - do_move_last_over(row_ndx, last_row_ndx); // Throws -} - -// Overriding virtual method of Column. -inline void StringEnumColumn::clear(size_t, bool) -{ - do_clear(); // Throws -} - -inline size_t StringEnumColumn::lower_bound_string(StringData value) const noexcept -{ - return ColumnBase::lower_bound(*this, value); -} - -inline size_t StringEnumColumn::upper_bound_string(StringData value) const noexcept -{ - return ColumnBase::upper_bound(*this, value); -} - -inline void StringEnumColumn::set_string(size_t row_ndx, StringData value) -{ - set(row_ndx, value); // Throws -} - -inline void StringEnumColumn::set_null(size_t row_ndx) -{ - set(row_ndx, realm::null{}); -} - -inline StringColumn& StringEnumColumn::get_keys() -{ - return m_keys; -} - -inline const StringColumn& StringEnumColumn::get_keys() const -{ - return m_keys; -} - - -} // namespace realm - -#endif // REALM_COLUMN_STRING_ENUM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_table.hpp b/Lesson14/Pods/Realm/include/core/realm/column_table.hpp deleted file mode 100644 index 0d424c2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_table.hpp +++ /dev/null @@ -1,693 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_TABLE_HPP -#define REALM_COLUMN_TABLE_HPP - -#include -#include - -#include -#include -#include -#include - -namespace realm { - - -/// Base class for any type of column that can contain subtables. -// FIXME: Don't derive from IntegerColumn, but define a BpTree specialization. -class SubtableColumnBase : public IntegerColumn, public Table::Parent { -public: - void discard_child_accessors() noexcept; - - ~SubtableColumnBase() noexcept override; - - static ref_type create(Allocator&, size_t size = 0); - - TableRef get_subtable_accessor(size_t) const noexcept override; - - void insert_rows(size_t, size_t, size_t, bool) override; - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - void clear(size_t, bool) override; - void swap_rows(size_t, size_t) override; - void discard_subtable_accessor(size_t) noexcept override; - void update_from_parent(size_t) noexcept override; - void adj_acc_insert_rows(size_t, size_t) noexcept override; - void adj_acc_erase_row(size_t) noexcept override; - void adj_acc_move_over(size_t, size_t) noexcept override; - void adj_acc_clear_root_table() noexcept override; - void adj_acc_swap_rows(size_t, size_t) noexcept override; - void adj_acc_move_row(size_t, size_t) noexcept override; - void mark(int) noexcept override; - bool supports_search_index() const noexcept override - { - return false; - } - StringIndex* create_search_index() override - { - return nullptr; - } - bool is_null(size_t ndx) const noexcept override - { - return get_as_ref(ndx) == 0; - } - - void verify() const override; - void verify(const Table&, size_t) const override; - -protected: - /// A pointer to the table that this column is part of. For a free-standing - /// column, this pointer is null. - Table* const m_table; - - struct SubtableMap { - bool empty() const noexcept - { - return m_entries.empty(); - } - Table* find(size_t subtable_ndx) const noexcept; - void add(size_t subtable_ndx, Table*); - // Returns true if, and only if at least one entry was detached and - // removed from the map. - bool detach_and_remove_all() noexcept; - // Returns true if, and only if the entry was found and removed, and it - // was the last entry in the map. - bool detach_and_remove(size_t subtable_ndx) noexcept; - // Returns true if, and only if the entry was found and removed, and it - // was the last entry in the map. - bool remove(Table*) noexcept; - void update_from_parent(size_t old_baseline) const noexcept; - template - void adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept; - // Returns true if, and only if an entry was found and removed, and it - // was the last entry in the map. - template - bool adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept; - // Returns true if, and only if an entry was found and removed, and it - // was the last entry in the map. - template - bool adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - template - void adj_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; - template - void adj_move_row(size_t from_ndx, size_t to_ndx) noexcept; - void adj_set_null(size_t row_ndx) noexcept; - - void update_accessors(const size_t* col_path_begin, const size_t* col_path_end, - _impl::TableFriend::AccessorUpdater&); - void recursive_mark() noexcept; - void refresh_accessor_tree(); - void verify(const SubtableColumn& parent); - - private: - struct SubtableEntry { - size_t m_subtable_ndx; - Table* m_table; - }; - typedef std::vector entries; - entries m_entries; - }; - - /// Contains all existing accessors that are attached to a subtable in this - /// column. It can map a row index into a pointer to the corresponding - /// accessor when it exists. - /// - /// There is an invariant in force: Either `m_table` is null, or there is an - /// additional referece count on `*m_table` when, and only when the map is - /// non-empty. - mutable SubtableMap m_subtable_map; - mutable std::recursive_mutex m_subtable_map_lock; - - SubtableColumnBase(Allocator&, ref_type, Table*, size_t column_ndx); - - /// Get a TableRef to the accessor of the specified subtable. The - /// accessor will be created if it does not already exist. - /// - /// NOTE: This method must be used only for subtables with - /// independent specs, i.e. for elements of a MixedColumn. - TableRef get_subtable_tableref(size_t subtable_ndx); - - // Overriding method in ArrayParent - void update_child_ref(size_t, ref_type) override; - - // Overriding method in ArrayParent - ref_type get_child_ref(size_t) const noexcept override; - - // Overriding method in Table::Parent - Table* get_parent_table(size_t*) noexcept override; - - // Overriding method in Table::Parent - void child_accessor_destroyed(Table*) noexcept override; - - // Overriding method in Table::Parent - std::recursive_mutex* get_accessor_management_lock() noexcept override - { return &m_subtable_map_lock; } - - /// Assumes that the two tables have the same spec. - static bool compare_subtable_rows(const Table&, const Table&); - - /// Construct a copy of the columns array of the specified table - /// and return just the ref to that array. - /// - /// In the clone, no string column will be of the enumeration - /// type. - ref_type clone_table_columns(const Table*); - - size_t* record_subtable_path(size_t* begin, size_t* end) noexcept override; - - void update_table_accessors(const size_t* col_path_begin, const size_t* col_path_end, - _impl::TableFriend::AccessorUpdater&); - - /// \param row_ndx Must be `realm::npos` if appending. - /// \param value The value to place in any newly created rows. - /// \param num_rows The number of rows to insert. - void do_insert(size_t row_ndx, int_fast64_t value, size_t num_rows); - - std::pair get_to_dot_parent(size_t ndx_in_parent) const override; - - friend class Table; -}; - - -class SubtableColumn : public SubtableColumnBase { -public: - using value_type = ConstTableRef; - /// Create a subtable column accessor and attach it to a - /// preexisting underlying structure of arrays. - /// - /// \param alloc The allocator to provide new memory. - /// - /// \param ref The memory reference of the underlying subtable that - /// we are creating an accessor for. - /// - /// \param table If this column is used as part of a table you must - /// pass a pointer to that table. Otherwise you must pass null. - /// - /// \param column_ndx If this column is used as part of a table - /// you must pass the logical index of the column within that - /// table. Otherwise you should pass zero. - SubtableColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx); - - ~SubtableColumn() noexcept override - { - } - - // Overriding method in Table::Parent - Spec* get_subtable_spec() noexcept override; - - size_t get_subtable_size(size_t ndx) const noexcept; - - /// Get a TableRef to the accessor of the specified subtable. The - /// accessor will be created if it does not already exist. - TableRef get_subtable_tableref(size_t subtable_ndx); - - ConstTableRef get_subtable_tableref(size_t subtable_ndx) const; - - /// This is to be used by the query system that does not need to - /// modify the subtable. Will return a ref object containing a - /// nullptr if there is no table object yet. - ConstTableRef get(size_t subtable_ndx) const - { - int64_t ref = IntegerColumn::get(subtable_ndx); - if (ref) - return get_subtable_tableref(subtable_ndx); - else - return {}; - } - - // When passing a table to add() or insert() it is assumed that - // the table spec is compatible with this column. The number of - // columns must be the same, and the corresponding columns must - // have the same data type (as returned by - // Table::get_column_type()). - - void add(const Table* value = nullptr); - void insert(size_t ndx, const Table* value = nullptr); - void set(size_t ndx, const Table*); - void clear_table(size_t ndx); - void set_null(size_t ndx) override; - - using SubtableColumnBase::insert; - - void erase_rows(size_t, size_t, size_t, bool) override; - void move_last_row_over(size_t, size_t, bool) override; - - /// Compare two subtable columns for equality. - bool compare_table(const SubtableColumn&) const; - - void refresh_accessor_tree(size_t, const Spec&) override; - void refresh_subtable_map(); - -#ifdef REALM_DEBUG - void verify(const Table&, size_t) const override; - void do_dump_node_structure(std::ostream&, int) const override; - void to_dot(std::ostream&, StringData title) const override; -#endif - -private: - mutable size_t m_subspec_ndx; // Unknown if equal to `npos` - - size_t get_subspec_ndx() const noexcept; - - void destroy_subtable(size_t ndx) noexcept; - - void do_discard_child_accessors() noexcept override; -}; - - -// Implementation - -// Overriding virtual method of Column. -inline void SubtableColumnBase::insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool) -{ - REALM_ASSERT_DEBUG(prior_num_rows == size()); - REALM_ASSERT(row_ndx <= prior_num_rows); - - size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx); - int_fast64_t value = 0; - do_insert(row_ndx_2, value, num_rows_to_insert); // Throws -} - -// Overriding virtual method of Column. -inline void SubtableColumnBase::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, - bool broken_reciprocal_backlinks) -{ - IntegerColumn::erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks); // Throws - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = true; - bool last_entry_removed = m_subtable_map.adj_erase_rows(row_ndx, num_rows_to_erase); - typedef _impl::TableFriend tf; - if (last_entry_removed) - tf::unbind_ptr(*m_table); -} - -// Overriding virtual method of Column. -inline void SubtableColumnBase::move_last_row_over(size_t row_ndx, size_t prior_num_rows, - bool broken_reciprocal_backlinks) -{ - IntegerColumn::move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks); // Throws - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = true; - size_t last_row_ndx = prior_num_rows - 1; - bool last_entry_removed = m_subtable_map.adj_move_over(last_row_ndx, row_ndx); - typedef _impl::TableFriend tf; - if (last_entry_removed) - tf::unbind_ptr(*m_table); -} - -inline void SubtableColumnBase::clear(size_t, bool) -{ - discard_child_accessors(); - clear_without_updating_index(); // Throws - // FIXME: This one is needed because - // IntegerColumn::clear_without_updating_index() forgets about the - // leaf type. A better solution should probably be sought after. - get_root_array()->set_type(Array::type_HasRefs); -} - -inline void SubtableColumnBase::swap_rows(size_t row_ndx_1, size_t row_ndx_2) -{ - IntegerColumn::swap_rows(row_ndx_1, row_ndx_2); // Throws - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = true; - m_subtable_map.adj_swap_rows(row_ndx_1, row_ndx_2); -} - -inline void SubtableColumnBase::mark(int type) noexcept -{ - if (type & mark_Recursive) { - std::lock_guard lg(m_subtable_map_lock); - m_subtable_map.recursive_mark(); - } -} - -inline void SubtableColumnBase::adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = false; - m_subtable_map.adj_insert_rows(row_ndx, num_rows); -} - -inline void SubtableColumnBase::adj_acc_erase_row(size_t row_ndx) noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = false; - size_t num_rows_erased = 1; - bool last_entry_removed = m_subtable_map.adj_erase_rows(row_ndx, num_rows_erased); - typedef _impl::TableFriend tf; - if (last_entry_removed) - tf::unbind_ptr(*m_table); -} - -inline void SubtableColumnBase::adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = false; - bool last_entry_removed = m_subtable_map.adj_move_over(from_row_ndx, to_row_ndx); - typedef _impl::TableFriend tf; - if (last_entry_removed) - tf::unbind_ptr(*m_table); -} - -inline void SubtableColumnBase::adj_acc_clear_root_table() noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - IntegerColumn::adj_acc_clear_root_table(); - discard_child_accessors(); -} - -inline void SubtableColumnBase::adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept -{ - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = false; - m_subtable_map.adj_swap_rows(row_ndx_1, row_ndx_2); -} - -inline void SubtableColumnBase::adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept -{ - std::lock_guard lg(m_subtable_map_lock); - const bool fix_ndx_in_parent = false; - m_subtable_map.adj_move_row(from_ndx, to_ndx); -} - -inline TableRef SubtableColumnBase::get_subtable_accessor(size_t row_ndx) const noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - std::lock_guard lg(m_subtable_map_lock); - TableRef subtable(m_subtable_map.find(row_ndx)); - return subtable; -} - -inline void SubtableColumnBase::discard_subtable_accessor(size_t row_ndx) noexcept -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - std::lock_guard lg(m_subtable_map_lock); - bool last_entry_removed = m_subtable_map.detach_and_remove(row_ndx); - typedef _impl::TableFriend tf; - if (last_entry_removed) - tf::unbind_ptr(*m_table); -} - -inline void SubtableColumnBase::SubtableMap::add(size_t subtable_ndx, Table* table) -{ - SubtableEntry e; - e.m_subtable_ndx = subtable_ndx; - e.m_table = table; - m_entries.push_back(e); -} - -template -void SubtableColumnBase::SubtableMap::adj_insert_rows(size_t row_ndx, size_t num_rows_inserted) noexcept -{ - for (auto& entry : m_entries) { - if (entry.m_subtable_ndx >= row_ndx) { - entry.m_subtable_ndx += num_rows_inserted; - typedef _impl::TableFriend tf; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - } -} - -template -bool SubtableColumnBase::SubtableMap::adj_erase_rows(size_t row_ndx, size_t num_rows_erased) noexcept -{ - if (m_entries.empty()) - return false; - typedef _impl::TableFriend tf; - auto end = m_entries.end(); - auto i = m_entries.begin(); - do { - if (i->m_subtable_ndx >= row_ndx + num_rows_erased) { - i->m_subtable_ndx -= num_rows_erased; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(i->m_table), i->m_subtable_ndx); - } - else if (i->m_subtable_ndx >= row_ndx) { - // Must hold a counted reference while detaching - TableRef table(i->m_table); - tf::detach(*table); - // Move last over - *i = *--end; - continue; - } - ++i; - } while (i != end); - m_entries.erase(end, m_entries.end()); - return m_entries.empty(); -} - - -template -bool SubtableColumnBase::SubtableMap::adj_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept -{ - typedef _impl::TableFriend tf; - - size_t i = 0, n = m_entries.size(); - // We return true if, and only if we remove the last entry in the map. We - // need special handling for the case, where the set of entries are already - // empty, otherwise the final return statement would return true in this - // case, even though we didn't actually remove an entry. - if (n == 0) - return false; - - while (i < n) { - SubtableEntry& e = m_entries[i]; - if (REALM_UNLIKELY(e.m_subtable_ndx == to_row_ndx)) { - // Must hold a counted reference while detaching - TableRef table(e.m_table); - tf::detach(*table); - // Delete entry by moving last over (faster and avoids invalidating - // iterators) - e = m_entries[--n]; - m_entries.pop_back(); - } - else { - if (REALM_UNLIKELY(e.m_subtable_ndx == from_row_ndx)) { - e.m_subtable_ndx = to_row_ndx; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(e.m_table), e.m_subtable_ndx); - } - ++i; - } - } - return m_entries.empty(); -} - -template -void SubtableColumnBase::SubtableMap::adj_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept -{ - using tf = _impl::TableFriend; - for (auto& entry : m_entries) { - if (REALM_UNLIKELY(entry.m_subtable_ndx == row_ndx_1)) { - entry.m_subtable_ndx = row_ndx_2; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - else if (REALM_UNLIKELY(entry.m_subtable_ndx == row_ndx_2)) { - entry.m_subtable_ndx = row_ndx_1; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - } -} - - -template -void SubtableColumnBase::SubtableMap::adj_move_row(size_t from_ndx, size_t to_ndx) noexcept -{ - using tf = _impl::TableFriend; - for (auto& entry : m_entries) { - if (entry.m_subtable_ndx == from_ndx) { - entry.m_subtable_ndx = to_ndx; - if (fix_ndx_in_parent) - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - else { - if (from_ndx < to_ndx) { - // shift the range (from, to] down one - if (entry.m_subtable_ndx <= to_ndx && entry.m_subtable_ndx > from_ndx) { - entry.m_subtable_ndx--; - if (fix_ndx_in_parent) { - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - } - } else if (from_ndx > to_ndx) { - // shift the range (from, to] up one - if (entry.m_subtable_ndx >= to_ndx && entry.m_subtable_ndx < from_ndx) { - entry.m_subtable_ndx++; - if (fix_ndx_in_parent) { - tf::set_ndx_in_parent(*(entry.m_table), entry.m_subtable_ndx); - } - } - } - } - } -} - -inline void SubtableColumnBase::SubtableMap::adj_set_null(size_t row_ndx) noexcept -{ - Table* table = find(row_ndx); - if (table) - _impl::TableFriend::refresh_accessor_tree(*table); -} - -inline SubtableColumnBase::SubtableColumnBase(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) - : IntegerColumn(alloc, ref, column_ndx) // Throws - , m_table(table) -{ -} - -inline void SubtableColumnBase::update_child_ref(size_t child_ndx, ref_type new_ref) -{ - set_as_ref(child_ndx, new_ref); -} - -inline ref_type SubtableColumnBase::get_child_ref(size_t child_ndx) const noexcept -{ - return get_as_ref(child_ndx); -} - -inline void SubtableColumnBase::discard_child_accessors() noexcept -{ - std::lock_guard lg(m_subtable_map_lock); - bool last_entry_removed = m_subtable_map.detach_and_remove_all(); - if (last_entry_removed && m_table) - _impl::TableFriend::unbind_ptr(*m_table); -} - -inline SubtableColumnBase::~SubtableColumnBase() noexcept -{ - discard_child_accessors(); -} - -inline bool SubtableColumnBase::compare_subtable_rows(const Table& a, const Table& b) -{ - return _impl::TableFriend::compare_rows(a, b); -} - -inline ref_type SubtableColumnBase::clone_table_columns(const Table* t) -{ - return _impl::TableFriend::clone_columns(*t, get_root_array()->get_alloc()); -} - -inline ref_type SubtableColumnBase::create(Allocator& alloc, size_t size) -{ - return IntegerColumn::create(alloc, Array::type_HasRefs, size); // Throws -} - -inline size_t* SubtableColumnBase::record_subtable_path(size_t* begin, size_t* end) noexcept -{ - if (end == begin) - return 0; // Error, not enough space in buffer - *begin++ = get_column_index(); - if (end == begin) - return 0; // Error, not enough space in buffer - return _impl::TableFriend::record_subtable_path(*m_table, begin, end); -} - -inline void SubtableColumnBase::update_table_accessors(const size_t* col_path_begin, const size_t* col_path_end, - _impl::TableFriend::AccessorUpdater& updater) -{ - // This function must assume no more than minimal consistency of the - // accessor hierarchy. This means in particular that it cannot access the - // underlying node structure. See AccessorConsistencyLevels. - - m_subtable_map.update_accessors(col_path_begin, col_path_end, updater); // Throws -} - -inline void SubtableColumnBase::do_insert(size_t row_ndx, int_fast64_t value, size_t num_rows) -{ - IntegerColumn::insert_without_updating_index(row_ndx, value, num_rows); // Throws - bool is_append = row_ndx == realm::npos; - if (!is_append) { - const bool fix_ndx_in_parent = true; - m_subtable_map.adj_insert_rows(row_ndx, num_rows); - } -} - - -inline SubtableColumn::SubtableColumn(Allocator& alloc, ref_type ref, Table* table, size_t column_ndx) - : SubtableColumnBase(alloc, ref, table, column_ndx) - , m_subspec_ndx(realm::npos) -{ -} - -inline ConstTableRef SubtableColumn::get_subtable_tableref(size_t subtable_ndx) const -{ - return const_cast(this)->get_subtable_tableref(subtable_ndx); -} - -inline void SubtableColumn::refresh_accessor_tree(size_t col_ndx, const Spec& spec) -{ - SubtableColumnBase::refresh_accessor_tree(col_ndx, spec); // Throws - m_subspec_ndx = spec.get_subspec_ndx(col_ndx); - std::lock_guard lg(m_subtable_map_lock); - m_subtable_map.refresh_accessor_tree(); // Throws -} - -inline void SubtableColumn::refresh_subtable_map() -{ - std::lock_guard lg(m_subtable_map_lock); - m_subtable_map.refresh_accessor_tree(); // Throws -} - -inline size_t SubtableColumn::get_subspec_ndx() const noexcept -{ - if (REALM_UNLIKELY(m_subspec_ndx == realm::npos)) { - typedef _impl::TableFriend tf; - m_subspec_ndx = tf::get_spec(*m_table).get_subspec_ndx(get_column_index()); - } - return m_subspec_ndx; -} - -inline Spec* SubtableColumn::get_subtable_spec() noexcept -{ - typedef _impl::TableFriend tf; - return tf::get_spec(*m_table).get_subtable_spec(get_column_index()); -} - - -} // namespace realm - -#endif // REALM_COLUMN_TABLE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_timestamp.hpp b/Lesson14/Pods/Realm/include/core/realm/column_timestamp.hpp deleted file mode 100644 index 0cc6d07..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_timestamp.hpp +++ /dev/null @@ -1,167 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_TIMESTAMP_HPP -#define REALM_COLUMN_TIMESTAMP_HPP - -#include -#include - -namespace realm { - -// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the -// column type -class TimestampColumn : public ColumnBaseSimple { -public: - TimestampColumn(bool nullable, Allocator& alloc, ref_type ref, size_t col_ndx = npos); - - static ref_type create(Allocator& alloc, size_t size, bool nullable); - static size_t get_size_from_ref(ref_type root_ref, Allocator& alloc) noexcept; - - /// Get the number of entries in this column. This operation is relatively - /// slow. - size_t size() const noexcept override; - /// Whether or not this column is nullable. - bool is_nullable() const noexcept override; - /// Whether or not the value at \a row_ndx is NULL. If the column is not - /// nullable, always returns false. - bool is_null(size_t row_ndx) const noexcept override; - /// Sets the value at \a row_ndx to be NULL. - /// \throw LogicError Thrown if this column is not nullable. - void set_null(size_t row_ndx) override; - void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override; - void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, - bool broken_reciprocal_backlinks) override; - void move_last_row_over(size_t row_ndx, size_t prior_num_rows, bool broken_reciprocal_backlinks) override; - void clear(size_t num_rows, bool broken_reciprocal_backlinks) override; - void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override; - void destroy() noexcept override; - - bool has_search_index() const noexcept final - { - return bool(m_search_index); - } - StringIndex* get_search_index() noexcept final - { - return m_search_index.get(); - } - StringIndex* get_search_index() const noexcept final - { - return m_search_index.get(); - } - void destroy_search_index() noexcept override; - void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent) final; - void populate_search_index(); - StringIndex* create_search_index() override; - bool supports_search_index() const noexcept final - { - return true; - } - - StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override; - ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override; - void update_from_parent(size_t old_baseline) noexcept override; - void set_ndx_in_parent(size_t ndx) noexcept override; - void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override; - - void verify() const override; - void to_dot(std::ostream&, StringData title = StringData()) const override; - void do_dump_node_structure(std::ostream&, int level) const override; - void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override; - void get_seconds_leaf(size_t ndx, size_t& ndx_in_leaf, - BpTree>::LeafInfo& inout_leaf) const noexcept; - void get_nanoseconds_leaf(size_t ndx, size_t& ndx_in_leaf, BpTree::LeafInfo& inout_leaf) const noexcept; - - void add(const Timestamp& ts = Timestamp{}); - Timestamp get(size_t row_ndx) const noexcept; - void set(size_t row_ndx, const Timestamp& ts); - bool compare(const TimestampColumn& c) const noexcept; - int compare_values(size_t row1, size_t row2) const noexcept override; - - Timestamp maximum(size_t* result_index) const; - Timestamp minimum(size_t* result_index) const; - size_t count(Timestamp) const; - void erase(size_t row_ndx, bool is_last); - - template - size_t find(Timestamp value, size_t begin, size_t end) const noexcept - { - // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match - // check nanoseconds, etc. Lots of possibilities. Below code is naive and slow but works. - - Condition cond; - for (size_t t = begin; t < end; t++) { - Timestamp ts = get(t); - if (cond(ts, value, ts.is_null(), value.is_null())) - return t; - } - return npos; - } - - void find_all(IntegerColumn& result, Timestamp value, size_t begin, size_t end) const - { - if (m_search_index && begin == 0 && end == npos) { - m_search_index->find_all(result, value); // Throws - return; - } - REALM_ASSERT(false); - } - - typedef Timestamp value_type; - -private: - std::unique_ptr>> m_seconds; - std::unique_ptr> m_nanoseconds; - - std::unique_ptr m_search_index; - bool m_nullable; - - template - class CreateHandler; - - template - Timestamp minmax(size_t* result_index) const noexcept - { - // Condition is realm::Greater for maximum and realm::Less for minimum. Any non-null value is both larger - // and smaller than a null value. - if (size() == 0) { - if (result_index) - *result_index = npos; - return Timestamp{}; - } - - Timestamp best = get(0); - size_t best_index = best.is_null() ? npos : 0; - - for (size_t i = 1; i < size(); ++i) { - Timestamp candidate = get(i); - // Condition() will return false if any of the two values are null. - if ((best.is_null() && !candidate.is_null()) || Condition()(candidate, best, candidate.is_null(), best.is_null())) { - best = candidate; - best_index = i; - } - } - if (result_index) - *result_index = best_index; - return best; - } -}; - -} // namespace realm - -#endif // REALM_COLUMN_TIMESTAMP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_tpl.hpp b/Lesson14/Pods/Realm/include/core/realm/column_tpl.hpp deleted file mode 100644 index 2411007..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_tpl.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_TPL_HPP -#define REALM_COLUMN_TPL_HPP - -#include - -#include -#include -#include - -namespace realm { - -template -class FloatDoubleNode; -template -class IntegerNode; -template -class SequentialGetter; - -template -struct ColumnTypeTraits2; - -template -struct ColumnTypeTraits2 { - typedef IntegerColumn column_type; - typedef ArrayInteger array_type; -}; -template -struct ColumnTypeTraits2 { - typedef IntegerColumn column_type; - typedef ArrayInteger array_type; -}; -template -struct ColumnTypeTraits2 { - typedef FloatColumn column_type; - typedef ArrayFloat array_type; -}; -template -struct ColumnTypeTraits2 { - typedef DoubleColumn column_type; - typedef ArrayDouble array_type; -}; - - -namespace _impl { - -template -struct FindInLeaf { - using LeafType = typename ColType::LeafType; - - template - static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, - QueryState& state) - { - Condition cond; - bool cont = true; - // todo, make an additional loop with hard coded `false` instead of is_null(v) for non-nullable columns - bool null_target = null::is_null_float(target); - for (size_t local_index = local_start; cont && local_index < local_end; local_index++) { - auto v = leaf.get(local_index); - if (cond(v, target, null::is_null_float(v), null_target)) { - cont = state.template match(leaf_start + local_index, 0, static_cast(v)); - } - } - return cont; - } -}; - -template <> -struct FindInLeaf { - using LeafType = IntegerColumn::LeafType; - - template - static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, - QueryState& state) - { - const int c = Condition::condition; - return leaf.find(c, action, target, local_start, local_end, leaf_start, &state); - } -}; - -template <> -struct FindInLeaf { - using LeafType = IntNullColumn::LeafType; - - template - static bool find(const LeafType& leaf, T target, size_t local_start, size_t local_end, size_t leaf_start, - QueryState& state) - { - constexpr int cond = Condition::condition; - return leaf.find(cond, action, target, local_start, local_end, leaf_start, &state); - } -}; - -} // namespace _impl - -template -R aggregate(const ColType& column, T target, size_t start, size_t end, size_t limit, size_t* return_ndx) -{ - if (end == npos) - end = column.size(); - - QueryState state; - state.init(action, nullptr, limit); - SequentialGetter sg{&column}; - - bool cont = true; - for (size_t s = start; cont && s < end;) { - sg.cache_next(s); - size_t start2 = s - sg.m_leaf_start; - size_t end2 = sg.local_end(end); - cont = _impl::FindInLeaf::template find(*sg.m_leaf_ptr, target, start2, end2, - sg.m_leaf_start, state); - s = sg.m_leaf_start + end2; - } - - if (return_ndx) - *return_ndx = action == act_Sum ? state.m_match_count : state.m_minmax_index; - - return state.m_state; -} - - -} // namespace realm - -#endif // REALM_COLUMN_TPL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_type.hpp b/Lesson14/Pods/Realm/include/core/realm/column_type.hpp deleted file mode 100644 index 5a6e21c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_type.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_TYPE_HPP -#define REALM_COLUMN_TYPE_HPP - -namespace realm { - - -// Note: Enumeration value assignments must be kept in sync with -// . -enum ColumnType { - // Column types - col_type_Int = 0, - col_type_Bool = 1, - col_type_String = 2, - col_type_StringEnum = 3, // double refs - col_type_Binary = 4, - col_type_Table = 5, - col_type_Mixed = 6, - col_type_OldDateTime = 7, - col_type_Timestamp = 8, - col_type_Float = 9, - col_type_Double = 10, - col_type_Reserved4 = 11, // Decimal - col_type_Link = 12, - col_type_LinkList = 13, - col_type_BackLink = 14 -}; - - -// Column attributes can be combined using bitwise or. -enum ColumnAttr { - col_attr_None = 0, - col_attr_Indexed = 1, - - /// Specifies that this column forms a unique constraint. It requires - /// `col_attr_Indexed`. - col_attr_Unique = 2, - - /// Reserved for future use. - col_attr_Reserved = 4, - - /// Specifies that the links of this column are strong, not weak. Applies - /// only to link columns (`type_Link` and `type_LinkList`). - col_attr_StrongLinks = 8, - - /// Specifies that elements in the column can be null. - col_attr_Nullable = 16 -}; - - -} // namespace realm - -#endif // REALM_COLUMN_TYPE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/column_type_traits.hpp b/Lesson14/Pods/Realm/include/core/realm/column_type_traits.hpp deleted file mode 100644 index 78441de..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/column_type_traits.hpp +++ /dev/null @@ -1,168 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_COLUMN_TYPE_TRAITS_HPP -#define REALM_COLUMN_TYPE_TRAITS_HPP - -#include -#include -#include -#include - -namespace realm { - -class OldDateTime; -class ArrayBinary; -class ArrayInteger; -class ArrayIntNull; -template -class BasicArray; - -template -struct ColumnTypeTraits; - -template <> -struct ColumnTypeTraits { - using column_type = Column; - using leaf_type = ArrayInteger; - using sum_type = int64_t; - using minmax_type = int64_t; - static const DataType id = type_Int; - static const ColumnType column_id = col_type_Int; - static const ColumnType real_column_type = col_type_Int; -}; - -template <> -struct ColumnTypeTraits> { - using column_type = Column>; - using leaf_type = ArrayIntNull; - using sum_type = int64_t; - using minmax_type = int64_t; - static const DataType id = type_Int; - static const ColumnType column_id = col_type_Int; - static const ColumnType real_column_type = col_type_Int; -}; - -template <> -struct ColumnTypeTraits : ColumnTypeTraits { - static const DataType id = type_Bool; - static const ColumnType column_id = col_type_Bool; -}; - -template <> -struct ColumnTypeTraits> : ColumnTypeTraits> { - static const DataType id = type_Bool; - static const ColumnType column_id = col_type_Bool; -}; - -template <> -struct ColumnTypeTraits { - using column_type = FloatColumn; - using leaf_type = BasicArray; - using sum_type = double; - using minmax_type = float; - static const DataType id = type_Float; - static const ColumnType column_id = col_type_Float; - static const ColumnType real_column_type = col_type_Float; -}; - -template <> -struct ColumnTypeTraits { - using column_type = DoubleColumn; - using leaf_type = BasicArray; - using sum_type = double; - using minmax_type = double; - static const DataType id = type_Double; - static const ColumnType column_id = col_type_Double; - static const ColumnType real_column_type = col_type_Double; -}; - -template <> -struct ColumnTypeTraits : ColumnTypeTraits { - static const DataType id = type_OldDateTime; - static const ColumnType column_id = col_type_OldDateTime; -}; - -template <> -struct ColumnTypeTraits { - using column_type = TimestampColumn; - static const DataType id = type_Timestamp; - static const ColumnType column_id = col_type_Timestamp; -}; - -template <> -struct ColumnTypeTraits> : ColumnTypeTraits> { - static const DataType id = type_OldDateTime; - static const ColumnType column_id = col_type_OldDateTime; -}; - -template <> -struct ColumnTypeTraits { - using column_type = StringColumn; - static const DataType id = type_String; - static const ColumnType column_id = col_type_String; -}; - -template <> -struct ColumnTypeTraits { - using column_type = BinaryColumn; - using leaf_type = ArrayBinary; - static const DataType id = type_Binary; - static const ColumnType column_id = col_type_Binary; - static const ColumnType real_column_type = col_type_Binary; -}; - -template -struct GetColumnType; -template <> -struct GetColumnType { - using type = IntegerColumn; -}; -template <> -struct GetColumnType { - using type = IntNullColumn; -}; -template -struct GetColumnType { - // FIXME: Null definition - using type = FloatColumn; -}; -template -struct GetColumnType { - // FIXME: Null definition - using type = DoubleColumn; -}; - -// Only purpose is to return 'double' if and only if source column (T) is float and you're doing a sum (A) -template -struct ColumnTypeTraitsSum { - typedef T sum_type; -}; - -template <> -struct ColumnTypeTraitsSum { - typedef double sum_type; -}; - -template -struct ColumnTypeTraitsSum, A> { - using sum_type = int64_t; -}; -} - -#endif // REALM_COLUMN_TYPE_TRAITS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/data_type.hpp b/Lesson14/Pods/Realm/include/core/realm/data_type.hpp deleted file mode 100644 index 37e8a1b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/data_type.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_DATA_TYPE_HPP -#define REALM_DATA_TYPE_HPP - -#include - -namespace realm { - -class StringData; -class BinaryData; -class Timestamp; - -typedef int64_t Int; -typedef bool Bool; -typedef float Float; -typedef double Double; -typedef realm::StringData String; -typedef realm::BinaryData Binary; -typedef realm::Timestamp Timestamp; - - -// Note: Value assignments must be kept in sync with -// Note: Value assignments must be kept in sync with -// Note: Value assignments must be kept in sync with -// Note: Value assignments must be kept in sync with "com/realm/ColumnType.java" -// Note: Any change to this enum is a file-format breaking change. -enum DataType { - type_Int = 0, - type_Bool = 1, - type_Float = 9, - type_Double = 10, - type_String = 2, - type_Binary = 4, - type_OldDateTime = 7, - type_Timestamp = 8, - type_Table = 5, - type_Mixed = 6, - type_Link = 12, - type_LinkList = 13 -}; - -/// See Descriptor::set_link_type(). -enum LinkType { - link_Strong, - link_Weak, -}; - -} // namespace realm - -#endif // REALM_DATA_TYPE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/descriptor.hpp b/Lesson14/Pods/Realm/include/core/realm/descriptor.hpp deleted file mode 100644 index 9d37de5..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/descriptor.hpp +++ /dev/null @@ -1,812 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_DESCRIPTOR_HPP -#define REALM_DESCRIPTOR_HPP - -#include - -#include -#include -#include - - -namespace realm { - -namespace _impl { -class DescriptorFriend; -} - - -/// Accessor for table type descriptors. -/// -/// A table type descriptor is an entity that specifies the dynamic -/// type of a Realm table. Objects of this class are accessors -/// through which the descriptor can be inspected and -/// changed. Accessors can become detached, see is_attached() for more -/// on this. The descriptor itself is stored inside the database file, -/// or elsewhere in case of a free-standing table or a table in a -/// free-standing group. -/// -/// The dynamic type consists first, and foremost of an ordered list -/// of column descriptors. Each column descriptor specifies the name -/// and type of the column. -/// -/// When a table has a subtable column, every cell in than column -/// contains a subtable. All those subtables have the same dynamic -/// type, and therefore have a shared descriptor. See is_root() for -/// more on this. -/// -/// The Table class contains convenience methods, such as -/// Table::get_column_count() and Table::add_column(), that allow you -/// to inspect and change the dynamic type of simple tables without -/// resorting to use of descriptors. For example, the following two -/// statements have the same effect: -/// -/// table->add_column(type, name); -/// table->get_descriptor()->add_column(type, name); -/// -/// Note, however, that this equivalence holds only as long as no -/// shared subtable descriptors are involved. -/// -/// \sa Table::get_descriptor() -class Descriptor : public std::enable_shared_from_this { -public: - /// Get the number of columns in the associated tables. - size_t get_column_count() const noexcept; - - /// Get the type of the column at the specified index. - /// - /// The consequences of specifying a column index that is out of - /// range, are undefined. - DataType get_column_type(size_t column_ndx) const noexcept; - - /// Get the name of the column at the specified index. - /// - /// The consequences of specifying a column index that is out of - /// range, are undefined. - StringData get_column_name(size_t column_ndx) const noexcept; - - /// Search for a column with the specified name. - /// - /// This function finds the first column with the specified name, - /// and returns its index. If there are no such columns, it - /// returns `not_found`. - size_t get_column_index(StringData name) const noexcept; - - /// Get the index of the table to which links in the column at the specified - /// index refer. - /// - /// The consequences of specifying a column index that is out of - /// range, are undefined. - /// - /// The consequences of specifying a column index that does not refer - /// to a link column, are undefined. - size_t get_column_link_target(size_t column_ndx) const noexcept; - - /// Get whether or not the specified column is nullable. - /// - /// The consequences of specifying a column index that is out of - /// range, are undefined. - bool is_nullable(size_t column_ndx) const noexcept; - - /// \defgroup descriptor_column_accessors Accessing Columns Via A Descriptor - /// - /// add_column() and add_column_link() are a shorthands for calling - /// insert_column() and insert_column_link(), respectively, with a column - /// index equal to the original number of columns. The returned value is - /// that column index. - /// - /// insert_column() inserts a new column into all the tables associated with - /// this descriptor. If any of the tables are not empty, the new column will - /// be filled with the default value associated with the specified data - /// type. This function cannot be used to insert link-type columns. For - /// that, you have to use insert_column_link() instead. - /// - /// This function modifies the dynamic type of all the tables that - /// share this descriptor. It does this by inserting a new column - /// with the specified name and type into the descriptor at the - /// specified index, and into each of the tables that share this - /// descriptor. - /// - /// insert_column_link() is like insert_column(), but inserts a link-type - /// column to a group-level table. It is not possible to add link-type - /// columns to tables that are not group-level tables. This functions must - /// be used in place of insert_column() when the column type is `type_Link` - /// or `type_LinkList`. A link-type column is associated with a particular - /// target table. All links in a link-type column refer to rows in the - /// target table of that column. The target table must also be a group-level - /// table, and it must belong to the same group as the origin table. - /// - /// \param name Name of new column. All strings are valid column names as - /// long as they are valid UTF-8 encodings and the number of bytes does not - /// exceed `max_column_name_length`. An attempt to add a column with a name - /// that is longer than `max_column_name_length` will cause an exception to - /// be thrown. - /// - /// \param subdesc If a non-null pointer is passed, and the - /// specified type is `type_Table`, then this function - /// automatically retrieves the descriptor associated with the new - /// subtable column, and stores a reference to its accessor in - /// `*subdesc`. - /// - /// \param col_ndx Insert the new column at this index. Preexisting columns - /// at indexes equal to, or greater than `col_ndx` will be shifted to the - /// next higher index. It is an error to specify an index that is greater - /// than the number of columns prior to the insertion. - /// - /// \param link_type See set_link_type(). - /// - /// \sa Table::add_column() - /// \sa Table::insert_column() - /// \sa Table::add_column_link() - /// \sa Table::insert_column_link() - /// \sa is_root() - //@{ - - static const size_t max_column_name_length = 63; - - size_t add_column(DataType type, StringData name, DescriptorRef* subdesc = nullptr, bool nullable = false); - - void insert_column(size_t col_ndx, DataType type, StringData name, DescriptorRef* subdesc = nullptr, - bool nullable = false); - - size_t add_column_link(DataType type, StringData name, Table& target, LinkType = link_Weak); - void insert_column_link(size_t col_ndx, DataType type, StringData name, Table& target, LinkType = link_Weak); - //@} - - /// Remove the specified column from each of the associated - /// tables. If the removed column is the only column in the - /// descriptor, then the table size will drop to zero for all - /// tables that were not already empty. - /// - /// This function modifies the dynamic type of all the tables that - /// share this descriptor. It does this by removing the column at - /// the specified index from the descriptor, and from each of the - /// tables that share this descriptor. The consequences of - /// specifying a column index that is out of range, are undefined. - /// - /// If the removed column was a subtable column, then the - /// associated descriptor accessor will be detached, if it - /// exists. This function will also detach all accessors of - /// subtables of the root table. Only the accessor of the root - /// table will remain attached. The root table is the table - /// associated with the root descriptor. - /// - /// \param col_ndx The index of the column to be removed. It is an error to - /// specify an index that is greater than, or equal to the number of - /// columns. - /// - /// \sa is_root() - /// \sa Table::remove_column() - void remove_column(size_t col_ndx); - - /// Rename the specified column. - /// - /// This function modifies the dynamic type of all the tables that - /// share this descriptor. The consequences of specifying a column - /// index that is out of range, are undefined. - /// - /// This function will detach all accessors of subtables of the - /// root table. Only the accessor of the root table will remain - /// attached. The root table is the table associated with the root - /// descriptor. - /// - /// \param col_ndx The index of the column to be renamed. It is an error to - /// specify an index that is greater than, or equal to the number of - /// columns. - /// - /// \param new_name The new name of the column. - /// - /// \sa is_root() - /// \sa Table::rename_column() - void rename_column(size_t col_ndx, StringData new_name); - - /// If the descriptor is describing a subtable column, the add_search_index() - /// and remove_search_index() will add or remove search indexes of *all* - /// subtables of the subtable column. This may take a while if there are many - /// subtables with many rows each. - bool has_search_index(size_t column_ndx) const noexcept; - void add_search_index(size_t column_ndx); - void remove_search_index(size_t column_ndx); - - /// There are two kinds of links, 'weak' and 'strong'. A strong link is one - /// that implies ownership, i.e., that the origin row (parent) owns the - /// target row (child). Simply stated, this means that when the origin row - /// (parent) is removed, so is the target row (child). If there are multiple - /// strong links to a target row, the origin rows share ownership, and the - /// target row is removed when the last owner disappears. Weak links do not - /// imply ownership, and will be nullified or removed when the target row - /// disappears. - /// - /// To put this in precise terms; when a strong link is broken, and the - /// target row has no other strong links to it, the target row is removed. A - /// row that is implicitly removed in this way, is said to be - /// *cascade-removed*. When a weak link is broken, nothing is - /// cascade-removed. - /// - /// A link is considered broken if - /// - /// - the link is nullified, removed, or replaced by a different link - /// (Row::nullify_link(), Row::set_link(), LinkView::remove_link(), - /// LinkView::set_link(), LinkView::clear()), or if - /// - /// - the origin row is explicitly removed (Row::move_last_over(), - /// Table::clear()), or if - /// - /// - the origin row is cascade-removed, or if - /// - /// - the origin column is removed from the table (Table::remove_column()), - /// or if - /// - /// - the origin table is removed from the group. - /// - /// Note that a link is *not* considered broken when it is replaced by a - /// link to the same target row. I.e., no no rows will be cascade-removed - /// due to such an operation. - /// - /// When a row is explicitly removed (such as by Table::move_last_over()), - /// all links to it are automatically removed or nullified. For single link - /// columns (type_Link), links to the removed row are nullified. For link - /// list columns (type_LinkList), links to the removed row are removed from - /// the list. - /// - /// When a row is cascade-removed there can no longer be any strong links to - /// it, but if there are any weak links, they will be removed or nullified. - /// - /// It is important to understand that this cascade-removal scheme is too - /// simplistic to enable detection and removal of orphaned link-cycles. In - /// this respect, it suffers from the same limitations as a reference - /// counting scheme generally does. - /// - /// It is also important to understand, that the possible presence of a link - /// cycle can cause a row to be cascade-removed as a consequence of being - /// modified. This happens, for example, if two rows, A and B, have strong - /// links to each other, and there are no other strong links to either of - /// them. In this case, if A->B is changed to A->C, then both A and B will - /// be cascade-removed. This can lead to obscure bugs in some applications, - /// such as in the following case: - /// - /// table.set_link(col_ndx_1, row_ndx, ...); - /// table.set_int(col_ndx_2, row_ndx, ...); // Oops, `row_ndx` may no longer refer to the same row - /// - /// To be safe, applications, that may encounter cycles, are advised to - /// adopt the following pattern: - /// - /// Row row = table[row_ndx]; - /// row.set_link(col_ndx_1, ...); - /// if (row) - /// row.set_int(col_ndx_2, ...); // Ok, because we check whether the row has disappeared - /// - /// \param col_ndx The index of the link column (`type_Link` or - /// `type_LinkList`) to be modified. It is an error to specify an index that - /// is greater than, or equal to the number of columns, or to specify the - /// index of a non-link column. - /// - /// \param link_type The type of links the column should store. - void set_link_type(size_t col_ndx, LinkType link_type); - - //@{ - /// Get the descriptor for the specified subtable column. - /// - /// This function provides access to the shared subtable - /// descriptor for the subtables in the specified column. The - /// specified column must be a column whose type is 'table'. The - /// consequences of specifying a column of a different type, or - /// specifying an index that is out of range, are undefined. - /// - /// Note that this function cannot be used with 'mixed' columns, - /// since subtables of that kind have independent dynamic types, - /// and therefore, have independent descriptors. You can only get - /// access to the descriptor of a subtable in a mixed column by - /// first getting access to the subtable itself. - /// - /// \sa is_root() - DescriptorRef get_subdescriptor(size_t column_ndx); - ConstDescriptorRef get_subdescriptor(size_t column_ndx) const; - //@} - - //@{ - /// Returns the parent table descriptor, if any. - /// - /// If this descriptor is the *root descriptor*, then this - /// function returns null. Otherwise it returns the accessor of - /// the parent descriptor. - /// - /// \sa is_root() - DescriptorRef get_parent() noexcept; - ConstDescriptorRef get_parent() const noexcept; - //@} - - //@{ - /// Get the table associated with the root descriptor. - /// - /// \sa get_parent() - /// \sa is_root() - TableRef get_root_table() noexcept; - ConstTableRef get_root_table() const noexcept; - //@} - - //@{ - /// Get the target table associated with the specified link column. This - /// descriptor must be a root descriptor (is_root()), and the specified - /// column must be a link column (`type_Link` or `type_LinkList`). - TableRef get_link_target(size_t col_ndx) noexcept; - ConstTableRef get_link_target(size_t col_ndx) const noexcept; - //@} - - /// Is this a root descriptor? - /// - /// Descriptors of tables with independent dynamic type are root - /// descriptors. Root descriptors are never shared. Tables that - /// are direct members of groups have independent dynamic - /// types. The same is true for free-standing tables and subtables - /// in columns of type 'mixed'. - /// - /// When a table has a column of type 'table', the cells in that - /// column contain subtables. All those subtables have the same - /// dynamic type, and they share a single dynamic type - /// descriptor. Such shared descriptors are never root - /// descriptors. - /// - /// A type descriptor can even be shared by subtables with - /// different parent tables, but only if the parent tables - /// themselves have a shared type descriptor. For example, if a - /// table has a column `foo` of type 'table', and each of the - /// subtables in `foo` has a column `bar` of type 'table', then - /// all the subtables in all the `bar` columns share the same - /// dynamic type descriptor. - /// - /// \sa Table::has_shared_type() - bool is_root() const noexcept; - - /// Determine whether this accessor is still attached. - /// - /// A table descriptor accessor may get detached from the - /// underlying descriptor for various reasons (see below). When it - /// does, it no longer refers to that descriptor, and can no - /// longer be used, except for calling is_attached(). The - /// consequences of calling other methods on a detached accessor - /// are undefined. Descriptor accessors obtained by calling - /// functions in the Realm API are always in the 'attached' - /// state immediately upon return from those functions. - /// - /// A descriptor accessor that is obtained directly from a table - /// becomes detached if the table becomes detached. A shared - /// subtable descriptor accessor that is obtained by a call to - /// get_subdescriptor() becomes detached if the parent descriptor - /// accessor becomes detached, or if the corresponding subtable - /// column is removed. A descriptor accessor does not get detached - /// under any other circumstances. - bool is_attached() const noexcept; - - //@{ - /// \brief Compare two table descriptors. - /// - /// Two table descriptors are equal if they have the same number of columns, - /// and for each column index, the two columns have the same name, data - /// type, and set of attributes. - /// - /// For link columns (`type_Link` and `type_LinkList`), the target table - /// (get_link_target()) of the two columns must be the same. - /// - /// For subtable columns (`type_Table`), the two corresponding - /// subdescriptors must themselves be equal, as if by a recursive call to - /// operator==(). - /// - /// The consequences of comparing a detached descriptor are - /// undefined. - bool operator==(const Descriptor&) const noexcept; - bool operator!=(const Descriptor&) const noexcept; - //@} - - /// If the specified column is optimized to store only unique values, then - /// this function returns the number of unique values currently - /// stored. Otherwise it returns zero. This function is mainly intended for - /// debugging purposes. - size_t get_num_unique_values(size_t column_ndx) const; - - ~Descriptor() noexcept; - -private: - // for initialization through make_shared - struct PrivateTag { - }; - -public: - Descriptor(const PrivateTag&) - : Descriptor() - { - } - -private: - // Table associated with root descriptor. Detached iff null. - TableRef m_root_table; - DescriptorRef m_parent; // Null iff detached or root descriptor. - Spec* m_spec; // Valid if attached. Owned iff valid and `m_parent`. - - // Whenever a subtable descriptor accessor is created, it is - // stored in this map. This ensures that when get_subdescriptor() - // is called to created multiple DescriptorRef objects that - // overlap in time, then they will all refer to the same - // descriptor object. - // - // It also enables the necessary recursive detaching of descriptor - // objects. - struct subdesc_entry { - size_t m_column_ndx; - std::weak_ptr m_subdesc; - subdesc_entry(size_t column_ndx, DescriptorRef); - }; - typedef std::vector subdesc_map; - mutable subdesc_map m_subdesc_map; - - Descriptor() noexcept; - - // Called by the root table if this becomes the root - // descriptor. Otherwise it is called by the descriptor that - // becomes its parent. - // - // Puts this descriptor accessor into the attached state. This - // attaches it to the underlying structure of array nodes. It does - // not establish the parents reference to this descriptor, that is - // the job of the parent. When this function returns, - // is_attached() will return true. - // - // Not idempotent. - // - // The specified table is not allowed to be a subtable with a - // shareable spec. That is, Table::has_shared_spec() must return - // false. - // - // The specified spec must be the spec of the specified table or - // of one of its direct or indirect subtable columns. - // - // When the specified spec is the spec of the root table, the - // parent must be specified as null. When the specified spec is - // not the root spec, a proper parent must be specified. - void attach(Table*, DescriptorRef parent, Spec*) noexcept; - - // Detach accessor from underlying descriptor. Caller must ensure - // that a reference count exists upon return, for example by - // obtaining an extra reference count before the call. - // - // This function is called either by the root table if this is the - // root descriptor, or by the parent descriptor, if it is not. - // - // Puts this descriptor accessor into the detached state. This - // detaches it from the underlying structure of array nodes. It - // also calls detach_subdesc_accessors(). When this function - // returns, is_attached() will return false. - // - // Not idempotent. - void detach() noexcept; - - // Recursively detach all subtable descriptor accessors that - // exist, that is, all subtable descriptor accessors that have - // this descriptor as ancestor. - void detach_subdesc_accessors() noexcept; - - // Record the path in terms of subtable column indexes from the - // root descriptor to this descriptor. If this descriptor is a - // root descriptor, the path is empty. Returns zero if the path is - // too long to fit in the specified buffer. Otherwise the path - // indexes will be stored between `begin_2`and `end`, where - // `begin_2` is the returned pointer. - size_t* record_subdesc_path(size_t* begin, size_t* end) const noexcept; - - // Returns a pointer to the accessor of the specified - // subdescriptor if that accessor exists, otherwise this function - // return null. - DescriptorRef get_subdesc_accessor(size_t column_ndx) noexcept; - - void adj_insert_column(size_t col_ndx) noexcept; - void adj_erase_column(size_t col_ndx) noexcept; - - friend class util::bind_ptr; - friend class util::bind_ptr; - friend class _impl::DescriptorFriend; -}; - - -// Implementation: - -inline size_t Descriptor::get_column_count() const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_public_column_count(); -} - -inline StringData Descriptor::get_column_name(size_t ndx) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_column_name(ndx); -} - -inline DataType Descriptor::get_column_type(size_t ndx) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_public_column_type(ndx); -} - -inline bool Descriptor::is_nullable(size_t ndx) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_column_attr(ndx) & col_attr_Nullable; -} - -inline size_t Descriptor::get_column_index(StringData name) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_column_index(name); -} - -inline size_t Descriptor::get_column_link_target(size_t column_ndx) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_opposite_link_table_ndx(column_ndx); -} - -inline size_t Descriptor::add_column(DataType type, StringData name, DescriptorRef* subdesc, bool nullable) -{ - size_t col_ndx = m_spec->get_public_column_count(); - insert_column(col_ndx, type, name, subdesc, nullable); // Throws - return col_ndx; -} - -inline void Descriptor::insert_column(size_t col_ndx, DataType type, StringData name, DescriptorRef* subdesc, - bool nullable) -{ - typedef _impl::TableFriend tf; - - if (REALM_UNLIKELY(!is_attached())) - throw LogicError(LogicError::detached_accessor); - if (REALM_UNLIKELY(col_ndx > get_column_count())) - throw LogicError(LogicError::column_index_out_of_range); - if (REALM_UNLIKELY(tf::is_link_type(ColumnType(type)))) - throw LogicError(LogicError::illegal_type); - - LinkTargetInfo invalid_link; - tf::insert_column(*this, col_ndx, type, name, invalid_link, nullable); // Throws - adj_insert_column(col_ndx); - if (subdesc && type == type_Table) - *subdesc = get_subdescriptor(col_ndx); -} - -inline size_t Descriptor::add_column_link(DataType type, StringData name, Table& target, LinkType link_type) -{ - size_t col_ndx = m_spec->get_public_column_count(); - insert_column_link(col_ndx, type, name, target, link_type); // Throws - return col_ndx; -} - -inline void Descriptor::insert_column_link(size_t col_ndx, DataType type, StringData name, Table& target, - LinkType link_type) -{ - typedef _impl::TableFriend tf; - - if (REALM_UNLIKELY(!is_attached() || !target.is_attached())) - throw LogicError(LogicError::detached_accessor); - if (REALM_UNLIKELY(col_ndx > get_column_count())) - throw LogicError(LogicError::column_index_out_of_range); - if (REALM_UNLIKELY(!tf::is_link_type(ColumnType(type)))) - throw LogicError(LogicError::illegal_type); - if (REALM_UNLIKELY(!is_root())) - throw LogicError(LogicError::wrong_kind_of_descriptor); - // Both origin and target must be group-level tables, and in the same group. - Group* origin_group = tf::get_parent_group(*get_root_table()); - Group* target_group = tf::get_parent_group(target); - if (!origin_group || !target_group) - throw LogicError(LogicError::wrong_kind_of_table); - if (origin_group != target_group) - throw LogicError(LogicError::group_mismatch); - - LinkTargetInfo link(&target); - tf::insert_column(*this, col_ndx, type, name, link); // Throws - adj_insert_column(col_ndx); - - tf::set_link_type(*get_root_table(), col_ndx, link_type); // Throws -} - -inline void Descriptor::remove_column(size_t col_ndx) -{ - typedef _impl::TableFriend tf; - - if (REALM_UNLIKELY(!is_attached())) - throw LogicError(LogicError::detached_accessor); - if (REALM_UNLIKELY(col_ndx >= get_column_count())) - throw LogicError(LogicError::column_index_out_of_range); - - tf::erase_column(*this, col_ndx); // Throws - adj_erase_column(col_ndx); -} - -inline void Descriptor::rename_column(size_t col_ndx, StringData name) -{ - typedef _impl::TableFriend tf; - - if (REALM_UNLIKELY(!is_attached())) - throw LogicError(LogicError::detached_accessor); - if (REALM_UNLIKELY(col_ndx >= get_column_count())) - throw LogicError(LogicError::column_index_out_of_range); - - tf::rename_column(*this, col_ndx, name); // Throws -} - -inline void Descriptor::set_link_type(size_t col_ndx, LinkType link_type) -{ - typedef _impl::TableFriend tf; - - if (REALM_UNLIKELY(!is_attached())) - throw LogicError(LogicError::detached_accessor); - if (REALM_UNLIKELY(col_ndx >= get_column_count())) - throw LogicError(LogicError::column_index_out_of_range); - if (REALM_UNLIKELY(!tf::is_link_type(ColumnType(get_column_type(col_ndx))))) - throw LogicError(LogicError::illegal_type); - - tf::set_link_type(*get_root_table(), col_ndx, link_type); // Throws -} - -inline ConstDescriptorRef Descriptor::get_subdescriptor(size_t column_ndx) const -{ - return const_cast(this)->get_subdescriptor(column_ndx); -} - -inline DescriptorRef Descriptor::get_parent() noexcept -{ - return m_parent; -} - -inline ConstDescriptorRef Descriptor::get_parent() const noexcept -{ - return const_cast(this)->get_parent(); -} - -inline TableRef Descriptor::get_root_table() noexcept -{ - return m_root_table; -} - -inline ConstTableRef Descriptor::get_root_table() const noexcept -{ - return const_cast(this)->get_root_table(); -} - -inline TableRef Descriptor::get_link_target(size_t col_ndx) noexcept -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT(is_root()); - return get_root_table()->get_link_target(col_ndx); -} - -inline ConstTableRef Descriptor::get_link_target(size_t col_ndx) const noexcept -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT(is_root()); - return get_root_table()->get_link_target(col_ndx); -} - -inline bool Descriptor::is_root() const noexcept -{ - return !m_parent; -} - -inline Descriptor::Descriptor() noexcept -{ -} - -inline void Descriptor::attach(Table* table, DescriptorRef parent, Spec* spec) noexcept -{ - REALM_ASSERT(!is_attached()); - REALM_ASSERT(!table->has_shared_type()); - m_root_table.reset(table); - m_parent = parent; - m_spec = spec; -} - -inline bool Descriptor::is_attached() const noexcept -{ - return bool(m_root_table); -} - -inline Descriptor::subdesc_entry::subdesc_entry(size_t n, DescriptorRef d) - : m_column_ndx(n) - , m_subdesc(d) -{ -} - -inline bool Descriptor::operator==(const Descriptor& d) const noexcept -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT(d.is_attached()); - return *m_spec == *d.m_spec; -} - -inline bool Descriptor::operator!=(const Descriptor& d) const noexcept -{ - return !(*this == d); -} - -// The purpose of this class is to give internal access to some, but -// not all of the non-public parts of the Descriptor class. -class _impl::DescriptorFriend { -public: - static DescriptorRef create() - { - return std::make_shared(Descriptor::PrivateTag()); // Throws - } - - static void attach(Descriptor& desc, Table* table, DescriptorRef parent, Spec* spec) noexcept - { - desc.attach(table, parent, spec); - } - - static void detach(Descriptor& desc) noexcept - { - desc.detach(); - } - - static void detach_subdesc_accessors(Descriptor& desc) noexcept - { - desc.detach_subdesc_accessors(); - } - - static Table& get_root_table(Descriptor& desc) noexcept - { - return *desc.m_root_table; - } - - static const Table& get_root_table(const Descriptor& desc) noexcept - { - return *desc.m_root_table; - } - - static Spec& get_spec(Descriptor& desc) noexcept - { - return *desc.m_spec; - } - - static const Spec& get_spec(const Descriptor& desc) noexcept - { - return *desc.m_spec; - } - - static size_t* record_subdesc_path(const Descriptor& desc, size_t* begin, size_t* end) noexcept - { - return desc.record_subdesc_path(begin, end); - } - - static DescriptorRef get_subdesc_accessor(Descriptor& desc, size_t column_ndx) noexcept - { - return desc.get_subdesc_accessor(column_ndx); - } - - static void adj_insert_column(Descriptor& desc, size_t col_ndx) noexcept - { - desc.adj_insert_column(col_ndx); - } - - static void adj_erase_column(Descriptor& desc, size_t col_ndx) noexcept - { - desc.adj_erase_column(col_ndx); - } -}; - -} // namespace realm - -#endif // REALM_DESCRIPTOR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/descriptor_fwd.hpp b/Lesson14/Pods/Realm/include/core/realm/descriptor_fwd.hpp deleted file mode 100644 index 2937724..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/descriptor_fwd.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_DESCRIPTOR_FWD_HPP -#define REALM_DESCRIPTOR_FWD_HPP - -#include - - -namespace realm { - -class Descriptor; -typedef std::shared_ptr DescriptorRef; -typedef std::shared_ptr ConstDescriptorRef; - -} // namespace realm - -#endif // REALM_DESCRIPTOR_FWD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp b/Lesson14/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp deleted file mode 100644 index f642d6f..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/disable_sync_to_disk.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_DISABLE_SYNC_TO_DISK_HPP -#define REALM_DISABLE_SYNC_TO_DISK_HPP - -#include - -namespace realm { - -/// Completely disable synchronization with storage device to speed up unit -/// testing. This is an unsafe mode of operation, and should never be used in -/// production. This function is thread safe. -void disable_sync_to_disk(); - -/// Returns true after disable_sync_to_disk() has been called. This function is -/// thread safe. -bool get_disable_sync_to_disk() noexcept; - -} // namespace realm - -#endif // REALM_DISABLE_SYNC_TO_DISK_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/exceptions.hpp b/Lesson14/Pods/Realm/include/core/realm/exceptions.hpp deleted file mode 100644 index 7db8d18..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/exceptions.hpp +++ /dev/null @@ -1,338 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_EXCEPTIONS_HPP -#define REALM_EXCEPTIONS_HPP - -#include - -#include -#include - -namespace realm { - -using util::ExceptionWithBacktrace; - -/// Thrown by various functions to indicate that a specified table does not -/// exist. -class NoSuchTable : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -/// Thrown by various functions to indicate that a specified table name is -/// already in use. -class TableNameInUse : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -// Thrown by functions that require a table to **not** be the target of link -// columns, unless those link columns are part of the table itself. -class CrossTableLinkTarget : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -/// Thrown by various functions to indicate that the dynamic type of a table -/// does not match a particular other table type (dynamic or static). -class DescriptorMismatch : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -/// The FileFormatUpgradeRequired exception can be thrown by the SharedGroup -/// constructor when opening a database that uses a deprecated file format -/// and/or a deprecated history schema, and the user has indicated he does not -/// want automatic upgrades to be performed. This exception indicates that until -/// an upgrade of the file format is performed, the database will be unavailable -/// for read or write operations. -class FileFormatUpgradeRequired : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -/// Thrown when a sync agent attempts to join a session in which there is -/// already a sync agent. A session may only contain one sync agent at any given -/// time. -class MultipleSyncAgents : public ExceptionWithBacktrace { -public: - const char* message() const noexcept override; -}; - - -/// Thrown when memory can no longer be mapped to. When mmap/remap fails. -class AddressSpaceExhausted : public std::runtime_error { -public: - AddressSpaceExhausted(const std::string& msg); - /// runtime_error::what() returns the msg provided in the constructor. -}; - -/// Thrown when creating references that are too large to be contained in our ref_type (size_t) -class MaximumFileSizeExceeded : public std::runtime_error { -public: - MaximumFileSizeExceeded(const std::string& msg); - /// runtime_error::what() returns the msg provided in the constructor. -}; - -/// Thrown when writing fails because the disk is full. -class OutOfDiskSpace : public std::runtime_error { -public: - OutOfDiskSpace(const std::string& msg); - /// runtime_error::what() returns the msg provided in the constructor. -}; - -// SerialisationError intentionally does not inherit ExceptionWithBacktrace -// because the query-based-sync permissions queries generated on the server -// use a LinksToNode which is not currently serialisable (this limitation can -// be lifted in core 6 given stable ids). Coupled with query metrics which -// serialize all queries, the capturing of the stack for these frequent -// permission queries shows up in performance profiles. -class SerialisationError : public std::runtime_error { -public: - SerialisationError(const std::string& msg); - /// runtime_error::what() returns the msg provided in the constructor. -}; - -// thrown when a user constructed link path is not a valid input -class InvalidPathError : public std::runtime_error { -public: - InvalidPathError(const std::string& msg); - /// runtime_error::what() returns the msg provided in the constructor. -}; - - -/// The \c LogicError exception class is intended to be thrown only when -/// applications (or bindings) violate rules that are stated (or ought to have -/// been stated) in the documentation of the public API, and only in cases -/// where the violation could have been easily and efficiently predicted by the -/// application. In other words, this exception class is for the cases where -/// the error is due to incorrect use of the public API. -/// -/// This class is not supposed to be caught by applications. It is not even -/// supposed to be considered part of the public API, and therefore the -/// documentation of the public API should **not** mention the \c LogicError -/// exception class by name. Note how this contrasts with other exception -/// classes, such as \c NoSuchTable, which are part of the public API, and are -/// supposed to be mentioned in the documentation by name. The \c LogicError -/// exception is part of Realm's private API. -/// -/// In other words, the \c LogicError class should exclusively be used in -/// replacement (or in addition to) asserts (debug or not) in order to -/// guarantee program interruption, while still allowing for complete -/// test-cases to be written and run. -/// -/// To this effect, the special `CHECK_LOGIC_ERROR()` macro is provided as a -/// test framework plugin to allow unit tests to check that the functions in -/// the public API do throw \c LogicError when rules are violated. -/// -/// The reason behind hiding this class from the public API is to prevent users -/// from getting used to the idea that "Undefined Behaviour" equates a specific -/// exception being thrown. The whole point of properly documenting "Undefined -/// Behaviour" cases is to help the user know what the limits are, without -/// constraining the database to handle every and any use-case thrown at it. -/// -/// FIXME: This exception class should probably be moved to the `_impl` -/// namespace, in order to avoid some confusion. -class LogicError : public ExceptionWithBacktrace { -public: - enum ErrorKind { - string_too_big, - binary_too_big, - table_name_too_long, - column_name_too_long, - table_index_out_of_range, - row_index_out_of_range, - column_index_out_of_range, - string_position_out_of_range, - link_index_out_of_range, - bad_version, - illegal_type, - - /// Indicates that an argument has a value that is illegal in combination - /// with another argument, or with the state of an involved object. - illegal_combination, - - /// Indicates a data type mismatch, such as when `Table::find_pkey_int()` is - /// called and the type of the primary key is not `type_Int`. - type_mismatch, - - /// Indicates that two involved tables are not in the same group. - group_mismatch, - - /// Indicates that an involved descriptor is of the wrong kind, i.e., if - /// it is a subtable descriptor, and the function requires a root table - /// descriptor. - wrong_kind_of_descriptor, - - /// Indicates that an involved table is of the wrong kind, i.e., if it - /// is a subtable, and the function requires a root table, or if it is a - /// free-standing table, and the function requires a group-level table. - wrong_kind_of_table, - - /// Indicates that an involved accessor is was detached, i.e., was not - /// attached to an underlying object. - detached_accessor, - - /// Indicates that a specified row index of a target table (a link) is - /// out of range. This is used for disambiguation in cases such as - /// Table::set_link() where one specifies both a row index of the origin - /// table, and a row index of the target table. - target_row_index_out_of_range, - - // Indicates that an involved column lacks a search index. - no_search_index, - - /// Indicates that a modification was attempted that would have produced a - /// duplicate primary value. - unique_constraint_violation, - - /// User attempted to insert null in non-nullable column - column_not_nullable, - - /// Group::open() is called on a group accessor that is already in the - /// attached state. Or Group::open() or Group::commit() is called on a - /// group accessor that is managed by a SharedGroup object. - wrong_group_state, - - /// No active transaction on a particular SharedGroup object (e.g., - /// SharedGroup::commit()), or the active transaction on the SharedGroup - /// object is of the wrong type (read/write), or an attampt was made to - /// initiate a new transaction while one is already in progress on the - /// same SharedGroup object. - wrong_transact_state, - - /// Attempted use of a continuous transaction through a SharedGroup - /// object with no history. See Replication::get_history(). - no_history, - - /// Durability setting (as passed to the SharedGroup constructor) was - /// not consistent across the session. - mixed_durability, - - /// History type (as specified by the Replication implementation passed - /// to the SharedGroup constructor) was not consistent across the - /// session. - mixed_history_type, - - /// History schema version (as specified by the Replication - /// implementation passed to the SharedGroup constructor) was not - /// consistent across the session. - mixed_history_schema_version, - - /// Adding rows to a table with no columns is not supported. - table_has_no_columns, - - /// Referring to a column that has been deleted. - column_does_not_exist, - - /// You can not add index on a subtable of a subtable - subtable_of_subtable_index - }; - - LogicError(ErrorKind message); - - const char* message() const noexcept override; - ErrorKind kind() const noexcept; - -private: - ErrorKind m_kind; -}; - - -// Implementation: - -// LCOV_EXCL_START (Wording of what() strings are not to be tested) - -inline const char* NoSuchTable::message() const noexcept -{ - return "No such table exists"; -} - -inline const char* TableNameInUse::message() const noexcept -{ - return "The specified table name is already in use"; -} - -inline const char* CrossTableLinkTarget::message() const noexcept -{ - return "Table is target of cross-table link columns"; -} - -inline const char* DescriptorMismatch::message() const noexcept -{ - return "Table descriptor mismatch"; -} - -inline const char* FileFormatUpgradeRequired::message() const noexcept -{ - return "Database upgrade required but prohibited"; -} - -inline const char* MultipleSyncAgents::message() const noexcept -{ - return "Multiple sync agents attempted to join the same session"; -} - -// LCOV_EXCL_STOP - -inline AddressSpaceExhausted::AddressSpaceExhausted(const std::string& msg) - : std::runtime_error(msg) -{ -} - -inline MaximumFileSizeExceeded::MaximumFileSizeExceeded(const std::string& msg) - : std::runtime_error(msg) -{ -} - -inline OutOfDiskSpace::OutOfDiskSpace(const std::string& msg) -: std::runtime_error(msg) -{ -} - -inline SerialisationError::SerialisationError(const std::string& msg) - : std::runtime_error(msg) -{ -} - -inline InvalidPathError::InvalidPathError(const std::string& msg) - : runtime_error(msg) -{ -} - -inline LogicError::LogicError(LogicError::ErrorKind k) - : m_kind(k) -{ -} - -inline LogicError::ErrorKind LogicError::kind() const noexcept -{ - return m_kind; -} - - -} // namespace realm - - -#endif // REALM_EXCEPTIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/group.hpp b/Lesson14/Pods/Realm/include/core/realm/group.hpp deleted file mode 100644 index 3c0a9e6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/group.hpp +++ /dev/null @@ -1,1440 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_GROUP_HPP -#define REALM_GROUP_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - -class SharedGroup; -namespace _impl { -class GroupFriend; -class TransactLogConvenientEncoder; -class TransactLogParser; -} - - -/// A group is a collection of named tables. -/// -/// Tables occur in the group in an unspecified order, but an order that -/// generally remains fixed. The order is guaranteed to remain fixed between two -/// points in time if no tables are added to, or removed from the group during -/// that time. When tables are added to, or removed from the group, the order -/// may change arbitrarily. -/// -/// If `table` is a table accessor attached to a group-level table, and `group` -/// is a group accessor attached to the group, then the following is guaranteed, -/// even after a change in the table order: -/// -/// \code{.cpp} -/// -/// table == group.get_table(table.get_index_in_group()) -/// -/// \endcode -/// -class Group : private Table::Parent { -public: - /// Construct a free-standing group. This group instance will be - /// in the attached state, but neither associated with a file, nor - /// with an external memory buffer. - Group(); - - enum OpenMode { - /// Open in read-only mode. Fail if the file does not already exist. - mode_ReadOnly, - /// Open in read/write mode. Create the file if it doesn't exist. - mode_ReadWrite, - /// Open in read/write mode. Fail if the file does not already exist. - mode_ReadWriteNoCreate - }; - - /// Equivalent to calling open(const std::string&, const char*, OpenMode) - /// on an unattached group accessor. - explicit Group(const std::string& file, const char* encryption_key = nullptr, OpenMode = mode_ReadOnly); - - /// Equivalent to calling open(BinaryData, bool) on an unattached - /// group accessor. Note that if this constructor throws, the - /// ownership of the memory buffer will remain with the caller, - /// regardless of whether \a take_ownership is set to `true` or - /// `false`. - explicit Group(BinaryData, bool take_ownership = true); - - struct unattached_tag { - }; - - /// Create a Group instance in its unattached state. It may then - /// be attached to a database file later by calling one of the - /// open() methods. You may test whether this instance is - /// currently in its attached state by calling - /// is_attached(). Calling any other method (except the - /// destructor) while in the unattached state has undefined - /// behavior. - Group(unattached_tag) noexcept; - - // FIXME: Implement a proper copy constructor (fairly trivial). - Group(const Group&) = delete; - Group& operator=(const Group&) = delete; - - ~Group() noexcept override; - - /// Attach this Group instance to the specified database file. - /// - /// By default, the specified file is opened in read-only mode - /// (mode_ReadOnly). This allows opening a file even when the - /// caller lacks permission to write to that file. The opened - /// group may still be modified freely, but the changes cannot be - /// written back to the same file using the commit() function. An - /// attempt to do that, will cause an exception to be thrown. When - /// opening in read-only mode, it is an error if the specified - /// file does not already exist in the file system. - /// - /// Alternatively, the file can be opened in read/write mode - /// (mode_ReadWrite). This allows use of the commit() function, - /// but, of course, it also requires that the caller has - /// permission to write to the specified file. When opening in - /// read-write mode, an attempt to create the specified file will - /// be made, if it does not already exist in the file system. - /// - /// In any case, if the file already exists, it must contain a - /// valid Realm database. In many cases invalidity will be - /// detected and cause the InvalidDatabase exception to be thrown, - /// but you should not rely on it. - /// - /// Note that changes made to the database via a Group instance - /// are not automatically committed to the specified file. You - /// may, however, at any time, explicitly commit your changes by - /// calling the commit() method, provided that the specified - /// open-mode is not mode_ReadOnly. Alternatively, you may call - /// write() to write the entire database to a new file. Writing - /// the database to a new file does not end, or in any other way - /// change the association between the Group instance and the file - /// that was specified in the call to open(). - /// - /// A Realm file that contains a history (see Replication::HistoryType) may - /// be opened via Group::open(), as long as the application can ensure that - /// there is no concurrent access to the file (see below for more on - /// concurrency), but if the file is modified via Group::commit() the - /// history will be discarded. To retain the history, the application must - /// instead access the file in shared mode, i.e., via SharedGroup, and - /// supply the right kind of replication plugin (see - /// Replication::get_history_type()). - /// - /// A file that is passed to Group::open(), may not be modified by - /// a third party until after the Group object is - /// destroyed. Behavior is undefined if a file is modified by a - /// third party while any Group object is associated with it. - /// - /// Calling open() on a Group instance that is already in the - /// attached state has undefined behavior. - /// - /// Accessing a Realm database file through manual construction - /// of a Group object does not offer any level of thread safety or - /// transaction safety. When any of those kinds of safety are a - /// concern, consider using a SharedGroup instead. When accessing - /// a database file in read/write mode through a manually - /// constructed Group object, it is entirely the responsibility of - /// the application that the file is not accessed in any way by a - /// third party during the life-time of that group object. It is, - /// on the other hand, safe to concurrently access a database file - /// by multiple manually created Group objects, as long as all of - /// them are opened in read-only mode, and there is no other party - /// that modifies the file concurrently. - /// - /// Do not call this function on a group instance that is managed - /// by a shared group. Doing so will result in undefined behavior. - /// - /// Even if this function throws, it may have the side-effect of - /// creating the specified file, and the file may get left behind - /// in an invalid state. Of course, this can only happen if - /// read/write mode (mode_ReadWrite) was requested, and the file - /// did not already exist. - /// - /// \param file File system path to a Realm database file. - /// - /// \param encryption_key 32-byte key used to encrypt and decrypt - /// the database file, or nullptr to disable encryption. - /// - /// \param mode Specifying a mode that is not mode_ReadOnly - /// requires that the specified file can be opened in read/write - /// mode. In general there is no reason to open a group in - /// read/write mode unless you want to be able to call - /// Group::commit(). - /// - /// \throw util::File::AccessError If the file could not be - /// opened. If the reason corresponds to one of the exception - /// types that are derived from util::File::AccessError, the - /// derived exception type is thrown. Note that InvalidDatabase is - /// among these derived exception types. - void open(const std::string& file, const char* encryption_key = nullptr, OpenMode mode = mode_ReadOnly); - - /// Attach this Group instance to the specified memory buffer. - /// - /// This is similar to constructing a group from a file except - /// that in this case the database is assumed to be stored in the - /// specified memory buffer. - /// - /// If \a take_ownership is `true`, you pass the ownership of the - /// specified buffer to the group. In this case the buffer will - /// eventually be freed using std::free(), so the buffer you pass, - /// must have been allocated using std::malloc(). - /// - /// On the other hand, if \a take_ownership is set to `false`, it - /// is your responsibility to keep the memory buffer alive during - /// the lifetime of the group, and in case the buffer needs to be - /// deallocated afterwards, that is your responsibility too. - /// - /// If this function throws, the ownership of the memory buffer - /// will remain with the caller, regardless of whether \a - /// take_ownership is set to `true` or `false`. - /// - /// Calling open() on a Group instance that is already in the - /// attached state has undefined behavior. - /// - /// Do not call this function on a group instance that is managed - /// by a shared group. Doing so will result in undefined behavior. - /// - /// \throw InvalidDatabase If the specified buffer does not appear - /// to contain a valid database. - void open(BinaryData, bool take_ownership = true); - - /// A group may be created in the unattached state, and then later - /// attached to a file with a call to open(). Calling any method - /// other than open(), and is_attached() on an unattached instance - /// results in undefined behavior. - bool is_attached() const noexcept; - - /// Returns true if, and only if the number of tables in this - /// group is zero. - bool is_empty() const noexcept; - - /// Returns the number of tables in this group. - size_t size() const noexcept; - - /// \defgroup group_table_access Table Accessors - /// - /// has_table() returns true if, and only if this group contains a table - /// with the specified name. - /// - /// find_table() returns the index of the first table in this group with the - /// specified name, or `realm::not_found` if this group does not contain a - /// table with the specified name. - /// - /// get_table_name() returns the name of table at the specified index. - /// - /// The versions of get_table(), that accepts a \a name argument, return the - /// first table with the specified name, or null if no such table exists. - /// - /// add_table() adds a table with the specified name to this group. It - /// throws TableNameInUse if \a require_unique_name is true and \a name - /// clashes with the name of an existing table. If \a require_unique_name is - /// false, it is possible to add more than one table with the same - /// name. Whenever a table is added, the order of the preexisting tables may - /// change arbitrarily, and the new table may not end up as the last one - /// either. But know that you can always call Table::get_index_in_group() on - /// the returned table accessor to find out at which index it ends up. - /// - /// get_or_add_table() checks if a table exists in this group with the specified - /// name. If it doesn't exist, a table is created. - /// - /// get_or_insert_table() works slightly differently from get_or_add_table(), - /// in that it considers the position of the requested table as part of that - /// table's identifying "key", in addition to the name. - /// - /// remove_table() removes the specified table from this group. A table can - /// be removed only when it is not the target of a link column of a - /// different table. Whenever a table is removed, the order of the remaining - /// tables may change arbitrarily. - /// - /// rename_table() changes the name of a preexisting table. If \a - /// require_unique_name is false, it becomes possible to have more than one - /// table with a given name in a single group. - /// - /// The template functions work exactly like their non-template namesakes - /// except as follows: The template versions of get_table() and - /// get_or_add_table() throw DescriptorMismatch if the dynamic type of the - /// specified table does not match the statically specified custom table - /// type. The template versions of add_table() and get_or_add_table() set - /// the dynamic type (descriptor) to match the statically specified custom - /// table type. - /// - /// \param index Index of table in this group. - /// - /// \param name Name of table. All strings are valid table names as long as - /// they are valid UTF-8 encodings and the number of bytes does not exceed - /// `max_table_name_length`. A call to add_table() or get_or_add_table() - /// with a name that is longer than `max_table_name_length` will cause an - /// exception to be thrown. - /// - /// \param new_name New name for preexisting table. - /// - /// \param require_unique_name When set to true (the default), it becomes - /// impossible to add a table with a name that is already in use, or to - /// rename a table to a name that is already in use. - /// - /// \param was_added When specified, the boolean variable is set to true if - /// the table was added, and to false otherwise. If the function throws, the - /// boolean variable retains its original value. - /// - /// \return get_table(), add_table(), and get_or_add_table() return a table - /// accessor attached to the requested (or added) table. get_table() may - /// return null. - /// - /// \throw DescriptorMismatch Thrown by get_table() and get_or_add_table() - /// tf the dynamic table type does not match the statically specified custom - /// table type (\a T). - /// - /// \throw NoSuchTable Thrown by remove_table() and rename_table() if there - /// is no table with the specified \a name. - /// - /// \throw TableNameInUse Thrown by add_table() if \a require_unique_name is - /// true and \a name clashes with the name of a preexisting table. Thrown by - /// rename_table() if \a require_unique_name is true and \a new_name clashes - /// with the name of a preexisting table. - /// - /// \throw CrossTableLinkTarget Thrown by remove_table() if the specified - /// table is the target of a link column of a different table. - /// - //@{ - - static const size_t max_table_name_length = 63; - - bool has_table(StringData name) const noexcept; - size_t find_table(StringData name) const noexcept; - StringData get_table_name(size_t table_ndx) const; - - TableRef get_table(size_t index); - ConstTableRef get_table(size_t index) const; - - TableRef get_table(StringData name); - ConstTableRef get_table(StringData name) const; - - TableRef add_table(StringData name, bool require_unique_name = true); - TableRef insert_table(size_t index, StringData name, bool require_unique_name = true); - TableRef get_or_add_table(StringData name, bool* was_added = nullptr); - TableRef get_or_insert_table(size_t index, StringData name, bool* was_added = nullptr); - - void remove_table(size_t index); - void remove_table(StringData name); - - void rename_table(size_t index, StringData new_name, bool require_unique_name = true); - void rename_table(StringData name, StringData new_name, bool require_unique_name = true); - - //@} - - // Serialization - - /// Write this database to the specified output stream. - /// - /// \param out The destination output stream to write to. - /// - /// \param pad If true, the file is padded to ensure the footer is aligned - /// to the end of a page - void write(std::ostream& out, bool pad = false) const; - - /// Write this database to a new file. It is an error to specify a - /// file that already exists. This is to protect against - /// overwriting a database file that is currently open, which - /// would cause undefined behaviour. - /// - /// \param file A filesystem path. - /// - /// \param encryption_key 32-byte key used to encrypt the database file, - /// or nullptr to disable encryption. - /// - /// \param version If different from 0, the new file will be a full fledged - /// realm file with free list and history info. The version of the commit - /// will be set to the value given here. - /// - /// \throw util::File::AccessError If the file could not be - /// opened. If the reason corresponds to one of the exception - /// types that are derived from util::File::AccessError, the - /// derived exception type is thrown. In particular, - /// util::File::Exists will be thrown if the file exists already. - void write(const std::string& file, const char* encryption_key = nullptr, uint64_t version = 0, - bool write_history = true) const; - - /// Write this database to a memory buffer. - /// - /// Ownership of the returned buffer is transferred to the - /// caller. The memory will have been allocated using - /// std::malloc(). - BinaryData write_to_mem() const; - - /// Commit changes to the attached file. This requires that the - /// attached file is opened in read/write mode. - /// - /// Calling this function on an unattached group, a free-standing - /// group, a group whose attached file is opened in read-only - /// mode, a group that is attached to a memory buffer, or a group - /// that is managed by a shared group, is an error and will result - /// in undefined behavior. - /// - /// Table accesors will remain valid across the commit. Note that - /// this is not the case when working with proper transactions. - void commit(); - - //@{ - /// Some operations on Tables in a Group can cause indirect changes to other - /// fields, including in other Tables in the same Group. Specifically, - /// removing a row will set any links to that row to null, and if it had the - /// last strong links to other rows, will remove those rows. When this - /// happens, The cascade notification handler will be called with a - /// CascadeNotification containing information about what indirect changes - /// will occur, before any changes are made. - /// - /// has_cascade_notification_handler() returns true if and only if there is - /// currently a non-null notification handler registered. - /// - /// set_cascade_notification_handler() replaces the current handler (if any) - /// with the passed in handler. Pass in nullptr to remove the current handler - /// without registering a new one. - /// - /// CascadeNotification contains a vector of rows which will be removed and - /// a vector of links which will be set to null (or removed, for entries in - /// LinkLists). - struct CascadeNotification { - struct row { - /// Non-zero iff the removal of this row is ordered - /// (Table::remove()), as opposed to ordered - /// (Table::move_last_over()). Implicit removals are always - /// unordered. - /// - /// This flag does not take part in comparisons (operator==() and - /// operator<()). - size_t is_ordered_removal : 1; - - /// Index within group of a group-level table. - size_t table_ndx : std::numeric_limits::digits - 1; - - /// Row index which will be removed. - size_t row_ndx; - - row() - : is_ordered_removal(0) - { - } - - bool operator==(const row&) const noexcept; - bool operator!=(const row&) const noexcept; - - /// Trivial lexicographic order - bool operator<(const row&) const noexcept; - }; - - struct link { - const Table* origin_table; ///< A group-level table. - size_t origin_col_ndx; ///< Link column being nullified. - size_t origin_row_ndx; ///< Row in column being nullified. - /// The target row index which is being removed. Mostly relevant for - /// LinkList (to know which entries are being removed), but also - /// valid for Link. - size_t old_target_row_ndx; - }; - - /// A sorted list of rows which will be removed by the current operation. - std::vector rows; - - /// An unordered list of links which will be nullified by the current - /// operation. - std::vector links; - }; - - bool has_cascade_notification_handler() const noexcept; - void set_cascade_notification_handler(std::function new_handler) noexcept; - - //@} - - //@{ - /// During sync operation, schema changes may happen at runtime as connected - /// clients update their schema as part of an app update. Since this is a - /// relatively rare event, no attempt is made at limiting the amount of work - /// the handler is required to do to update its information about table and - /// column indices (i.e., all table and column indices must be recalculated). - /// - /// At the time of writing, only additive schema changes may occur in that - /// scenario. - /// - /// has_schema_change_notification_handler() returns true iff there is currently - /// a non-null notification handler registered. - /// - /// set_schema_change_notification_handler() replaces the current handler (if any) - /// with the passed in handler. Pass in nullptr to remove the current handler - /// without registering a new one. - - bool has_schema_change_notification_handler() const noexcept; - void set_schema_change_notification_handler(std::function new_handler) noexcept; - - //@} - - // Conversion - template - void to_json(S& out, size_t link_depth = 0, std::map* renames = nullptr) const; - void to_string(std::ostream& out) const; - - /// Compare two groups for equality. Two groups are equal if, and - /// only if, they contain the same tables in the same order, that - /// is, for each table T at index I in one of the groups, there is - /// a table at index I in the other group that is equal to T. - /// Tables are equal if they have the same content and the same table name. - bool operator==(const Group&) const; - - /// Compare two groups for inequality. See operator==(). - bool operator!=(const Group& g) const - { - return !(*this == g); - } - - /// Control of what to include when computing memory usage - enum SizeAggregateControl { - size_of_state = 1, ///< size of tables, indexes, toplevel array - size_of_history = 2, ///< size of the in-file history compartment - size_of_freelists = 4, ///< size of the freelists - size_of_all = 7 - }; - /// Compute the sum of the sizes in number of bytes of all the array nodes - /// that currently make up this group. When this group represents a snapshot - /// in a Realm file (such as during a read transaction via a SharedGroup - /// instance), this function computes the footprint of that snapshot within - /// the Realm file. - /// - /// If this group accessor is the detached state, this function returns - /// zero. - size_t compute_aggregated_byte_size(SizeAggregateControl ctrl = SizeAggregateControl::size_of_all) const noexcept; - /// Return the size taken up by the current snapshot. This is in contrast to - /// the number returned by SharedGroup::get_stats() which will return the - /// size of the last snapshot done in that SharedGroup. If the snapshots are - /// identical, the numbers will of course be equal. - size_t get_used_space() const noexcept; - - void verify() const; -#ifdef REALM_DEBUG - void print() const; - void print_free() const; - MemStats get_stats(); - void enable_mem_diagnostics(bool enable = true) - { - m_alloc.enable_debug(enable); - } - void to_dot(std::ostream&) const; - void to_dot() const; // To std::cerr (for GDB) - void to_dot(const char* file_path) const; -#endif - -private: - SlabAlloc m_alloc; - - int m_file_format_version; - /// `m_top` is the root node (or top array) of the Realm, and has the - /// following layout: - /// - ///
-    ///
-    ///                                                     Introduced in file
-    ///   Slot  Value                                       format version
-    ///   ---------------------------------------------------------------------
-    ///    1st   m_table_names
-    ///    2nd   m_tables
-    ///    3rd   Logical file size
-    ///    4th   GroupWriter::m_free_positions (optional)
-    ///    5th   GroupWriter::m_free_lengths   (optional)
-    ///    6th   GroupWriter::m_free_versions  (optional)
-    ///    7th   Transaction number / version  (optional)
-    ///    8th   History type         (optional)             4
-    ///    9th   History ref          (optional)             4
-    ///   10th   History version      (optional)             7
-    ///
-    /// 
- /// - /// The 'History type' slot stores a value of type - /// Replication::HistoryType. The 'History version' slot stores a history - /// schema version as returned by Replication::get_history_schema_version(). - /// - /// The first three entries are mandatory. In files created by - /// Group::write(), none of the optional entries are present and the size of - /// `m_top` is 3. In files updated by Group::commit(), the 4th and 5th entry - /// are present, and the size of `m_top` is 5. In files updated by way of a - /// transaction (SharedGroup::commit()), the 4th, 5th, 6th, and 7th entry - /// are present, and the size of `m_top` is 7. In files that contain a - /// changeset history, the 8th, 9th, and 10th entry are present, except that - /// if the file was opened in nonshared mode (via Group::open()), and the - /// file format remains at 6 (not previously upgraded to 7 or later), then - /// the 10th entry will be absent. - /// - /// When a group accessor is attached to a newly created file or an empty - /// memory buffer where there is no top array yet, `m_top`, `m_tables`, and - /// `m_table_names` will be left in the detached state until the initiation - /// of the first write transaction. In particular, they will remain in the - /// detached state during read transactions that precede the first write - /// transaction. - Array m_top; - ArrayInteger m_tables; - ArrayString m_table_names; - - typedef std::vector table_accessors; - mutable table_accessors m_table_accessors; - - bool m_attached = false; - const bool m_is_shared; - - std::function m_notify_handler; - std::function m_schema_change_handler; - std::shared_ptr m_metrics; - size_t m_total_rows; - - struct shared_tag { - }; - Group(shared_tag) noexcept; - - void init_array_parents() noexcept; - - void open(ref_type top_ref, const std::string& file_path); - - /// If `top_ref` is not zero, attach this group accessor to the specified - /// underlying node structure. If `top_ref` is zero and \a - /// create_group_when_missing is true, create a new node structure that - /// represents an empty group, and attach this group accessor to it. It is - /// an error to call this function on an already attached group accessor. - void attach(ref_type top_ref, bool create_group_when_missing); - - /// Detach this group accessor from the underlying node structure. If this - /// group accessors is already in the detached state, this function does - /// nothing (idempotency). - void detach() noexcept; - - /// \param writable Must be set to true when, and only when attaching for a - /// write transaction. - void attach_shared(ref_type new_top_ref, size_t new_file_size, bool writable); - - void create_empty_group(); - - void reset_free_space_tracking(); - - void remap(size_t new_file_size); - void remap_and_update_refs(ref_type new_top_ref, size_t new_file_size); - - /// Recursively update refs stored in all cached array - /// accessors. This includes cached array accessors in any - /// currently attached table accessors. This ensures that the - /// group instance itself, as well as any attached table accessor - /// that exists across Group::commit() will remain valid. This - /// function is not appropriate for use in conjunction with - /// commits via shared group. - void update_refs(ref_type top_ref, size_t old_baseline) noexcept; - - // Overriding method in ArrayParent - void update_child_ref(size_t, ref_type) override; - - // Overriding method in ArrayParent - ref_type get_child_ref(size_t) const noexcept override; - - // Overriding method in Table::Parent - StringData get_child_name(size_t) const noexcept override; - - // Overriding method in Table::Parent - void child_accessor_destroyed(Table*) noexcept override; - - // Overriding method in Table::Parent - std::recursive_mutex* get_accessor_management_lock() noexcept override - { return nullptr; } // we don't need locking for group! - - // Overriding method in Table::Parent - Group* get_parent_group() noexcept override; - - class TableWriter; - class DefaultTableWriter; - - static void write(std::ostream&, int file_format_version, TableWriter&, bool no_top_array, - bool pad_for_encryption, uint_fast64_t version_number); - - typedef void (*DescSetter)(Table&); - typedef bool (*DescMatcher)(const Spec&); - - Table* do_get_table(size_t table_ndx, DescMatcher desc_matcher); - const Table* do_get_table(size_t table_ndx, DescMatcher desc_matcher) const; - Table* do_get_table(StringData name, DescMatcher desc_matcher); - const Table* do_get_table(StringData name, DescMatcher desc_matcher) const; - Table* do_insert_table(size_t, StringData name, DescSetter desc_setter, bool require_unique_name); - Table* do_insert_table(size_t, StringData name, DescSetter desc_setter); - Table* do_get_or_add_table(StringData name, DescMatcher desc_matcher, DescSetter setter, bool* was_added); - Table* do_get_or_insert_table(size_t, StringData name, DescMatcher desc_matcher, DescSetter desc_setter, - bool* was_added); - - void create_and_insert_table(size_t new_table_ndx, StringData name); - Table* create_table_accessor(size_t table_ndx); - - void detach_table_accessors() noexcept; // Idempotent - - void mark_all_table_accessors() noexcept; - - void write(util::File& file, const char* encryption_key, uint_fast64_t version_number, bool write_history) const; - void write(std::ostream&, bool pad, uint_fast64_t version_numer, bool write_history) const; - - Replication* get_replication() const noexcept; - void set_replication(Replication*) noexcept; - std::shared_ptr get_metrics() const noexcept; - void set_metrics(std::shared_ptr other) noexcept; - void update_num_objects(); - class TransactAdvancer; - void advance_transact(ref_type new_top_ref, size_t new_file_size, _impl::NoCopyInputStream&); - void refresh_dirty_accessors(); - template - void update_table_indices(F&& map_function); - - /// \brief The version of the format of the node structure (in file or in - /// memory) in use by Realm objects associated with this group. - /// - /// Every group contains a file format version field, which is returned - /// by this function. The file format version field is set to the file format - /// version specified by the attached file (or attached memory buffer) at the - /// time of attachment and the value is used to determine if a file format - /// upgrade is required. - /// - /// A value of zero means that the file format is not yet decided. This is - /// only possible for empty Realms where top-ref is zero. (When group is created - /// with the unattached_tag). The version number will then be determined in the - /// subsequent call to Group::open. - /// - /// In shared mode (when a Realm file is opened via a SharedGroup instance) - /// it can happen that the file format is upgraded asyncronously (via - /// another SharedGroup instance), and in that case the file format version - /// field can get out of date, but only for a short while. It is always - /// guaranteed to be, and remain up to date after the opening process completes - /// (when SharedGroup::do_open() returns). - /// - /// An empty Realm file (one whose top-ref is zero) may specify a file - /// format version of zero to indicate that the format is not yet - /// decided. In that case the file format version must be changed to a proper - /// before the opening process completes (Group::open() or SharedGroup::open()). - /// - /// File format versions: - /// - /// 1 Initial file format version - /// - /// 2 Various changes. - /// - /// 3 Supporting null on string columns broke the file format in following - /// way: Index appends an 'X' character to all strings except the null - /// string, to be able to distinguish between null and empty - /// string. Bumped to 3 because of null support of String columns and - /// because of new format of index. - /// - /// 4 Introduction of optional in-Realm history of changes (additional - /// entries in Group::m_top). Since this change is not forward - /// compatible, the file format version had to be bumped. This change is - /// implemented in a way that achieves backwards compatibility with - /// version 3 (and in turn with version 2). - /// - /// 5 Introduced the new Timestamp column type that replaces DateTime. - /// When opening an older database file, all DateTime columns will be - /// automatically upgraded Timestamp columns. - /// - /// 6 Introduced a new structure for the StringIndex. Moved the commit - /// logs into the Realm file. Changes to the transaction log format - /// including reshuffling instructions. This is the format used in - /// milestone 2.0.0. - /// - /// 7 Introduced "history schema version" as 10th entry in top array. - /// - /// 8 Subtables can now have search index. - /// - /// 9 Replication instruction values shuffled, instr_MoveRow added. - /// - /// IMPORTANT: When introducing a new file format version, be sure to review - /// the file validity checks in Group::open() and SharedGroup::do_open, the file - /// format selection logic in - /// Group::get_target_file_format_version_for_session(), and the file format - /// upgrade logic in Group::upgrade_file_format(). - - int get_file_format_version() const noexcept; - void set_file_format_version(int) noexcept; - int get_committed_file_format_version() const noexcept; - - /// The specified history type must be a value of Replication::HistoryType. - static int get_target_file_format_version_for_session(int current_file_format_version, int history_type) noexcept; - - /// Must be called from within a write transaction - void upgrade_file_format(int target_file_format_version); - - std::pair get_to_dot_parent(size_t ndx_in_parent) const override; - - void send_cascade_notification(const CascadeNotification& notification) const; - void send_schema_change_notification() const; - - static void get_version_and_history_info(const Array& top, _impl::History::version_type& version, - int& history_type, int& history_schema_version) noexcept; - static ref_type get_history_ref(const Array& top) noexcept; - static int get_history_schema_version(const Array& top) noexcept; - void set_history_schema_version(int version); - void set_history_parent(Array& history_root) noexcept; - void prepare_history_parent(Array& history_root, int history_type, int history_schema_version); - static void validate_top_array(const Array& arr, const SlabAlloc& alloc); - - friend class Table; - friend class GroupWriter; - friend class SharedGroup; - friend class _impl::GroupFriend; - friend class _impl::TransactLogConvenientEncoder; - friend class _impl::TransactLogParser; - friend class Replication; - friend class TrivialReplication; - friend class metrics::QueryInfo; - friend class metrics::Metrics; -}; - - -// Implementation - -inline Group::Group(const std::string& file, const char* key, OpenMode mode) - : m_alloc() // Throws - , m_top(m_alloc) - , m_tables(m_alloc) - , m_table_names(m_alloc) - , m_is_shared(false) - , m_total_rows(0) -{ - init_array_parents(); - - open(file, key, mode); // Throws -} - -inline Group::Group(BinaryData buffer, bool take_ownership) - : m_alloc() // Throws - , m_top(m_alloc) - , m_tables(m_alloc) - , m_table_names(m_alloc) - , m_is_shared(false) - , m_total_rows(0) -{ - init_array_parents(); - open(buffer, take_ownership); // Throws -} - -inline Group::Group(unattached_tag) noexcept - : m_alloc() - , // Throws - m_top(m_alloc) - , m_tables(m_alloc) - , m_table_names(m_alloc) - , m_is_shared(false) - , m_total_rows(0) -{ - init_array_parents(); -} - -inline Group* Group::get_parent_group() noexcept -{ - return this; -} - -inline Group::Group(shared_tag) noexcept - : m_alloc() - , // Throws - m_top(m_alloc) - , m_tables(m_alloc) - , m_table_names(m_alloc) - , m_is_shared(true) - , m_total_rows(0) -{ - init_array_parents(); -} - -inline bool Group::is_attached() const noexcept -{ - return m_attached; -} - -inline bool Group::is_empty() const noexcept -{ - if (!is_attached()) - return false; - if (m_table_names.is_attached()) - return m_table_names.is_empty(); - return true; -} - -inline size_t Group::size() const noexcept -{ - if (!is_attached()) - return 0; - if (m_table_names.is_attached()) - return m_table_names.size(); - return 0; -} - -inline StringData Group::get_table_name(size_t table_ndx) const -{ - if (table_ndx >= size()) - throw LogicError(LogicError::table_index_out_of_range); - return m_table_names.get(table_ndx); -} - -inline bool Group::has_table(StringData name) const noexcept -{ - size_t ndx = find_table(name); - return ndx != not_found; -} - -inline size_t Group::find_table(StringData name) const noexcept -{ - if (!is_attached()) - return 0; - if (m_table_names.is_attached()) - return m_table_names.find_first(name); - return not_found; -} - -inline TableRef Group::get_table(size_t table_ndx) -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - Table* table = do_get_table(table_ndx, desc_matcher); // Throws - return TableRef(table); -} - -inline ConstTableRef Group::get_table(size_t table_ndx) const -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - const Table* table = do_get_table(table_ndx, desc_matcher); // Throws - return ConstTableRef(table); -} - -inline TableRef Group::get_table(StringData name) -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - Table* table = do_get_table(name, desc_matcher); // Throws - return TableRef(table); -} - -inline ConstTableRef Group::get_table(StringData name) const -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - const Table* table = do_get_table(name, desc_matcher); // Throws - return ConstTableRef(table); -} - -inline TableRef Group::insert_table(size_t table_ndx, StringData name, bool require_unique_name) -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescSetter desc_setter = nullptr; // Do not add any columns - Table* table = do_insert_table(table_ndx, name, desc_setter, require_unique_name); // Throws - return TableRef(table); -} - -inline TableRef Group::add_table(StringData name, bool require_unique_name) -{ - return insert_table(size(), name, require_unique_name); -} - -inline TableRef Group::get_or_insert_table(size_t table_ndx, StringData name, bool* was_added) -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - DescSetter desc_setter = nullptr; // Do not add any columns - Table* table = do_get_or_insert_table(table_ndx, name, desc_matcher, desc_setter, was_added); // Throws - return TableRef(table); -} - -inline TableRef Group::get_or_add_table(StringData name, bool* was_added) -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - DescMatcher desc_matcher = nullptr; // Do not check descriptor - DescSetter desc_setter = nullptr; // Do not add any columns - Table* table = do_get_or_add_table(name, desc_matcher, desc_setter, was_added); // Throws - return TableRef(table); -} - -template -void Group::to_json(S& out, size_t link_depth, std::map* renames) const -{ - if (!is_attached()) - throw LogicError(LogicError::detached_accessor); - - std::map renames2; - renames = renames ? renames : &renames2; - - out << "{" << std::endl; - - for (size_t i = 0; i < m_tables.size(); ++i) { - StringData name = m_table_names.get(i); - std::map& m = *renames; - if (m[name] != "") - name = m[name]; - - ConstTableRef table = get_table(i); - - if (i) - out << ","; - out << "\"" << name << "\""; - out << ":"; - table->to_json(out, link_depth, renames); - out << std::endl; - } - - out << "}" << std::endl; -} - -inline void Group::init_array_parents() noexcept -{ - m_table_names.set_parent(&m_top, 0); - m_tables.set_parent(&m_top, 1); -} - -inline void Group::update_child_ref(size_t child_ndx, ref_type new_ref) -{ - m_tables.set(child_ndx, new_ref); -} - -inline ref_type Group::get_child_ref(size_t child_ndx) const noexcept -{ - return m_tables.get_as_ref(child_ndx); -} - -inline StringData Group::get_child_name(size_t child_ndx) const noexcept -{ - return m_table_names.get(child_ndx); -} - -inline void Group::child_accessor_destroyed(Table*) noexcept -{ - // Ignore -} - -inline bool Group::has_cascade_notification_handler() const noexcept -{ - return !!m_notify_handler; -} - -inline void -Group::set_cascade_notification_handler(std::function new_handler) noexcept -{ - m_notify_handler = std::move(new_handler); -} - -inline void Group::send_cascade_notification(const CascadeNotification& notification) const -{ - if (m_notify_handler) - m_notify_handler(notification); -} - -inline bool Group::has_schema_change_notification_handler() const noexcept -{ - return !!m_schema_change_handler; -} - -inline void Group::set_schema_change_notification_handler(std::function new_handler) noexcept -{ - m_schema_change_handler = std::move(new_handler); -} - -inline void Group::send_schema_change_notification() const -{ - if (m_schema_change_handler) - m_schema_change_handler(); -} - -inline void Group::get_version_and_history_info(const Array& top, _impl::History::version_type& version, - int& history_type, int& history_schema_version) noexcept -{ - using version_type = _impl::History::version_type; - version_type version_2 = 0; - int history_type_2 = 0; - int history_schema_version_2 = 0; - if (top.is_attached()) { - if (top.size() >= 6) { - REALM_ASSERT(top.size() >= 7); - version_2 = version_type(top.get_as_ref_or_tagged(6).get_as_int()); - } - if (top.size() >= 8) { - REALM_ASSERT(top.size() >= 9); - history_type_2 = int(top.get_as_ref_or_tagged(7).get_as_int()); - } - if (top.size() >= 10) { - history_schema_version_2 = int(top.get_as_ref_or_tagged(9).get_as_int()); - } - } - // Version 0 is not a legal initial version, so it has to be set to 1 - // instead. - if (version_2 == 0) - version_2 = 1; - version = version_2; - history_type = history_type_2; - history_schema_version = history_schema_version_2; -} - -inline ref_type Group::get_history_ref(const Array& top) noexcept -{ - bool has_history = (top.is_attached() && top.size() >= 8); - if (has_history) { - // This function is only used is shared mode (from SharedGroup) - REALM_ASSERT(top.size() >= 10); - return top.get_as_ref(8); - } - return 0; -} - -inline int Group::get_history_schema_version(const Array& top) noexcept -{ - bool has_history = (top.is_attached() && top.size() >= 8); - if (has_history) { - // This function is only used is shared mode (from SharedGroup) - REALM_ASSERT(top.size() >= 10); - return int(top.get_as_ref_or_tagged(9).get_as_int()); - } - return 0; -} - -inline void Group::set_history_schema_version(int version) -{ - // This function is only used is shared mode (from SharedGroup) - REALM_ASSERT(m_top.size() >= 10); - m_top.set(9, RefOrTagged::make_tagged(unsigned(version))); // Throws -} - -inline void Group::set_history_parent(Array& history_root) noexcept -{ - history_root.set_parent(&m_top, 8); -} - -class Group::TableWriter { -public: - struct HistoryInfo { - ref_type ref = 0; - int type = 0; - int version = 0; - }; - - virtual ref_type write_names(_impl::OutputStream&) = 0; - virtual ref_type write_tables(_impl::OutputStream&) = 0; - virtual HistoryInfo write_history(_impl::OutputStream&) = 0; - virtual ~TableWriter() noexcept - { - } -}; - -inline const Table* Group::do_get_table(size_t table_ndx, DescMatcher desc_matcher) const -{ - return const_cast(this)->do_get_table(table_ndx, desc_matcher); // Throws -} - -inline const Table* Group::do_get_table(StringData name, DescMatcher desc_matcher) const -{ - return const_cast(this)->do_get_table(name, desc_matcher); // Throws -} - -inline void Group::reset_free_space_tracking() -{ - m_alloc.reset_free_space_tracking(); // Throws -} - -inline Replication* Group::get_replication() const noexcept -{ - return m_alloc.get_replication(); -} - -inline void Group::set_replication(Replication* repl) noexcept -{ - m_alloc.set_replication(repl); -} - -inline std::shared_ptr Group::get_metrics() const noexcept -{ - return m_metrics; -} - -inline void Group::set_metrics(std::shared_ptr shared) noexcept -{ - m_metrics = shared; -} - -// The purpose of this class is to give internal access to some, but -// not all of the non-public parts of the Group class. -class _impl::GroupFriend { -public: - static Allocator& get_alloc(Group& group) noexcept - { - return group.m_alloc; - } - - static const Allocator& get_alloc(const Group& group) noexcept - { - return group.m_alloc; - } - - static ref_type get_top_ref(const Group& group) noexcept - { - return group.m_top.get_ref(); - } - - static Table& get_table(Group& group, size_t ndx_in_group) - { - Group::DescMatcher desc_matcher = 0; // Do not check descriptor - Table* table = group.do_get_table(ndx_in_group, desc_matcher); // Throws - return *table; - } - - static const Table& get_table(const Group& group, size_t ndx_in_group) - { - Group::DescMatcher desc_matcher = 0; // Do not check descriptor - const Table* table = group.do_get_table(ndx_in_group, desc_matcher); // Throws - return *table; - } - - static Table* get_table(Group& group, StringData name) - { - Group::DescMatcher desc_matcher = 0; // Do not check descriptor - Table* table = group.do_get_table(name, desc_matcher); // Throws - return table; - } - - static const Table* get_table(const Group& group, StringData name) - { - Group::DescMatcher desc_matcher = 0; // Do not check descriptor - const Table* table = group.do_get_table(name, desc_matcher); // Throws - return table; - } - - static Table& insert_table(Group& group, size_t table_ndx, StringData name, bool require_unique_name) - { - Group::DescSetter desc_setter = nullptr; // Do not add any columns - return *group.do_insert_table(table_ndx, name, desc_setter, require_unique_name); - } - - static Table& add_table(Group& group, StringData name, bool require_unique_name) - { - return insert_table(group, group.size(), name, require_unique_name); - } - - static Table& get_or_insert_table(Group& group, size_t table_ndx, StringData name, bool* was_inserted) - { - Group::DescMatcher desc_matcher = nullptr; // Do not check descriptor - Group::DescSetter desc_setter = nullptr; // Do not add any columns - return *group.do_get_or_insert_table(table_ndx, name, desc_matcher, desc_setter, was_inserted); - } - - static Table& get_or_add_table(Group& group, StringData name, bool* was_inserted) - { - Group::DescMatcher desc_matcher = nullptr; // Do not check descriptor - Group::DescSetter desc_setter = nullptr; // Do not add any columns - return *group.do_get_or_add_table(name, desc_matcher, desc_setter, was_inserted); - } - - static void send_cascade_notification(const Group& group, const Group::CascadeNotification& notification) - { - group.send_cascade_notification(notification); - } - - static Replication* get_replication(const Group& group) noexcept - { - return group.get_replication(); - } - - static void set_replication(Group& group, Replication* repl) noexcept - { - group.set_replication(repl); - } - - static void detach(Group& group) noexcept - { - group.detach(); - } - - static void attach_shared(Group& group, ref_type new_top_ref, size_t new_file_size, bool writable) - { - group.attach_shared(new_top_ref, new_file_size, writable); // Throws - } - - static void reset_free_space_tracking(Group& group) - { - group.reset_free_space_tracking(); // Throws - } - - static void remap(Group& group, size_t new_file_size) - { - group.remap(new_file_size); // Throws - } - - static void remap_and_update_refs(Group& group, ref_type new_top_ref, size_t new_file_size) - { - group.remap_and_update_refs(new_top_ref, new_file_size); // Throws - } - - static void advance_transact(Group& group, ref_type new_top_ref, size_t new_file_size, - _impl::NoCopyInputStream& in) - { - group.advance_transact(new_top_ref, new_file_size, in); // Throws - } - - static void create_empty_group_when_missing(Group& group) - { - if (!group.m_top.is_attached()) - group.create_empty_group(); // Throws - } - - static void get_version_and_history_info(const Allocator& alloc, ref_type top_ref, - _impl::History::version_type& version, - int& history_type, - int& history_schema_version) noexcept - { - Array top{const_cast(alloc)}; - if (top_ref != 0) - top.init_from_ref(top_ref); - Group::get_version_and_history_info(top, version, history_type, history_schema_version); - } - - static ref_type get_history_ref(const Group& group) noexcept - { - return Group::get_history_ref(group.m_top); - } - - static ref_type get_history_ref(Allocator& alloc, ref_type top_ref) noexcept - { - Array top(alloc); - if (top_ref != 0) - top.init_from_ref(top_ref); - return Group::get_history_ref(top); - } - - static int get_history_schema_version(const Group& group) noexcept - { - return Group::get_history_schema_version(group.m_top); - } - - static int get_history_schema_version(Allocator& alloc, ref_type top_ref) noexcept - { - Array top{alloc}; - if (top_ref != 0) - top.init_from_ref(top_ref); - return Group::get_history_schema_version(top); - } - - static void set_history_schema_version(Group& group, int version) - { - group.set_history_schema_version(version); // Throws - } - - static void set_history_parent(Group& group, Array& history_root) noexcept - { - group.set_history_parent(history_root); - } - - static void prepare_history_parent(Group& group, Array& history_root, int history_type, - int history_schema_version) - { - group.prepare_history_parent(history_root, history_type, history_schema_version); // Throws - } - - static int get_file_format_version(const Group& group) noexcept - { - return group.get_file_format_version(); - } - - static void set_file_format_version(Group& group, int file_format_version) noexcept - { - group.set_file_format_version(file_format_version); - } - - static int get_committed_file_format_version(const Group& group) noexcept - { - return group.get_committed_file_format_version(); - } - - static int get_target_file_format_version_for_session(int current_file_format_version, int history_type) noexcept - { - return Group::get_target_file_format_version_for_session(current_file_format_version, history_type); - } - - static void upgrade_file_format(Group& group, int target_file_format_version) - { - group.upgrade_file_format(target_file_format_version); // Throws - } -}; - - -struct CascadeState : Group::CascadeNotification { - /// If non-null, then no recursion will be performed for rows of that - /// table. The effect is then exactly as if all the rows of that table were - /// added to \a state.rows initially, and then removed again after the - /// explicit invocations of Table::cascade_break_backlinks_to() (one for - /// each initiating row). This is used by Table::clear() to avoid - /// reentrance. - /// - /// Must never be set concurrently with stop_on_link_list_column. - Table* stop_on_table = nullptr; - - /// If non-null, then Table::cascade_break_backlinks_to() will skip the - /// removal of reciprocal backlinks for the link list at - /// stop_on_link_list_row_ndx in this column, and no recursion will happen - /// on its behalf. This is used by LinkView::clear() to avoid reentrance. - /// - /// Must never be set concurrently with stop_on_table. - LinkListColumn* stop_on_link_list_column = nullptr; - - /// Is ignored if stop_on_link_list_column is null. - size_t stop_on_link_list_row_ndx = 0; - - /// If false, the links field is not needed, so any work done just for that - /// can be skipped. - bool track_link_nullifications = false; - - /// If false, weak links are followed too - bool only_strong_links = true; -}; - -inline bool Group::CascadeNotification::row::operator==(const row& r) const noexcept -{ - return table_ndx == r.table_ndx && row_ndx == r.row_ndx; -} - -inline bool Group::CascadeNotification::row::operator!=(const row& r) const noexcept -{ - return !(*this == r); -} - -inline bool Group::CascadeNotification::row::operator<(const row& r) const noexcept -{ - return table_ndx < r.table_ndx || (table_ndx == r.table_ndx && row_ndx < r.row_ndx); -} - -} // namespace realm - -#endif // REALM_GROUP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/group_shared.hpp b/Lesson14/Pods/Realm/include/core/realm/group_shared.hpp deleted file mode 100644 index e607409..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/group_shared.hpp +++ /dev/null @@ -1,1233 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_GROUP_SHARED_HPP -#define REALM_GROUP_SHARED_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - -namespace _impl { -class SharedGroupFriend; -class WriteLogCollector; -} - -/// Thrown by SharedGroup::open() if the lock file is already open in another -/// process which can't share mutexes with this process -struct IncompatibleLockFile : std::runtime_error { - IncompatibleLockFile(const std::string& msg) - : std::runtime_error("Incompatible lock file. " + msg) - { - } -}; - -/// Thrown by SharedGroup::open() if the type of history -/// (Replication::HistoryType) in the opened Realm file is incompatible with the -/// mode in which the Realm file is opened. For example, if there is a mismatch -/// between the history type in the file, and the history type associated with -/// the replication plugin passed to SharedGroup::open(). -/// -/// This exception will also be thrown if the history schema version is lower -/// than required, and no migration is possible -/// (Replication::is_upgradable_history_schema()). -struct IncompatibleHistories : util::File::AccessError { - IncompatibleHistories(const std::string& msg, const std::string& path) - : util::File::AccessError("Incompatible histories. " + msg, path) - { - } -}; - -/// A SharedGroup facilitates transactions. -/// -/// When multiple threads or processes need to access a database -/// concurrently, they must do so using transactions. By design, -/// Realm does not allow for multiple threads (or processes) to -/// share a single instance of SharedGroup. Instead, each concurrently -/// executing thread or process must use a separate instance of -/// SharedGroup. -/// -/// Each instance of SharedGroup manages a single transaction at a -/// time. That transaction can be either a read transaction, or a -/// write transaction. -/// -/// Utility classes ReadTransaction and WriteTransaction are provided -/// to make it safe and easy to work with transactions in a scoped -/// manner (by means of the RAII idiom). However, transactions can -/// also be explicitly started (begin_read(), begin_write()) and -/// stopped (end_read(), commit(), rollback()). -/// -/// If a transaction is active when the SharedGroup is destroyed, that -/// transaction is implicitly terminated, either by a call to -/// end_read() or rollback(). -/// -/// Two processes that want to share a database file must reside on -/// the same host. -/// -/// -/// Desired exception behavior (not yet fully implemented) -/// ------------------------------------------------------ -/// -/// - If any data access API function throws an unexpected exception during a -/// read transaction, the shared group accessor is left in state "error -/// during read". -/// -/// - If any data access API function throws an unexpected exception during a -/// write transaction, the shared group accessor is left in state "error -/// during write". -/// -/// - If SharedGroup::begin_write() or SharedGroup::begin_read() throws an -/// unexpected exception, the shared group accessor is left in state "no -/// transaction in progress". -/// -/// - SharedGroup::end_read() and SharedGroup::rollback() do not throw. -/// -/// - If SharedGroup::commit() throws an unexpected exception, the shared group -/// accessor is left in state "error during write" and the transaction was -/// not committed. -/// -/// - If SharedGroup::advance_read() or SharedGroup::promote_to_write() throws -/// an unexpected exception, the shared group accessor is left in state -/// "error during read". -/// -/// - If SharedGroup::commit_and_continue_as_read() or -/// SharedGroup::rollback_and_continue_as_read() throws an unexpected -/// exception, the shared group accessor is left in state "error during -/// write". -/// -/// It has not yet been decided exactly what an "unexpected exception" is, but -/// `std::bad_alloc` is surely one example. On the other hand, an expected -/// exception is one that is mentioned in the function specific documentation, -/// and is used to abort an operation due to a special, but expected condition. -/// -/// States -/// ------ -/// -/// - A newly created shared group accessor is in state "no transaction in -/// progress". -/// -/// - In state "error during read", almost all Realm API functions are -/// illegal on the connected group of accessors. The only valid operations -/// are destruction of the shared group, and SharedGroup::end_read(). If -/// SharedGroup::end_read() is called, the new state becomes "no transaction -/// in progress". -/// -/// - In state "error during write", almost all Realm API functions are -/// illegal on the connected group of accessors. The only valid operations -/// are destruction of the shared group, and SharedGroup::rollback(). If -/// SharedGroup::end_write() is called, the new state becomes "no transaction -/// in progress" -class SharedGroup { -public: - /// \brief Same as calling the corresponding version of open() on a instance - /// constructed in the unattached state. Exception safety note: if the - /// `upgrade_callback` throws, then the file will be closed properly and the - /// upgrade will be aborted. - explicit SharedGroup(const std::string& file, bool no_create = false, - const SharedGroupOptions options = SharedGroupOptions()); - - /// \brief Same as calling the corresponding version of open() on a instance - /// constructed in the unattached state. Exception safety note: if the - /// `upgrade_callback` throws, then the file will be closed properly and - /// the upgrade will be aborted. - explicit SharedGroup(Replication& repl, const SharedGroupOptions options = SharedGroupOptions()); - - struct unattached_tag { - }; - - /// Create a SharedGroup instance in its unattached state. It may - /// then be attached to a database file later by calling - /// open(). You may test whether this instance is currently in its - /// attached state by calling is_attached(). Calling any other - /// function (except the destructor) while in the unattached state - /// has undefined behavior. - SharedGroup(unattached_tag) noexcept; - - ~SharedGroup() noexcept; - - // Disable copying to prevent accessor errors. If you really want another - // instance, open another SharedGroup object on the same file. - SharedGroup(const SharedGroup&) = delete; - SharedGroup& operator=(const SharedGroup&) = delete; - - /// Attach this SharedGroup instance to the specified database file. - /// - /// While at least one instance of SharedGroup exists for a specific - /// database file, a "lock" file will be present too. The lock file will be - /// placed in the same directory as the database file, and its name will be - /// derived by appending ".lock" to the name of the database file. - /// - /// When multiple SharedGroup instances refer to the same file, they must - /// specify the same durability level, otherwise an exception will be - /// thrown. - /// - /// \param file Filesystem path to a Realm database file. - /// - /// \param no_create If the database file does not already exist, it will be - /// created (unless this is set to true.) When multiple threads are involved, - /// it is safe to let the first thread, that gets to it, create the file. - /// - /// \param options See SharedGroupOptions for details of each option. - /// Sensible defaults are provided if this parameter is left out. - /// - /// Calling open() on a SharedGroup instance that is already in the attached - /// state has undefined behavior. - /// - /// \throw util::File::AccessError If the file could not be opened. If the - /// reason corresponds to one of the exception types that are derived from - /// util::File::AccessError, the derived exception type is thrown. Note that - /// InvalidDatabase is among these derived exception types. - /// - /// \throw FileFormatUpgradeRequired only if \a SharedGroupOptions::allow_upgrade - /// is `false` and an upgrade is required. - void open(const std::string& file, bool no_create = false, - const SharedGroupOptions options = SharedGroupOptions()); - - /// Open this group in replication mode. The specified Replication instance - /// must remain in existence for as long as the SharedGroup. - void open(Replication&, const SharedGroupOptions options = SharedGroupOptions()); - - /// Close any open database, returning to the unattached state. - void close() noexcept; - - /// A SharedGroup may be created in the unattached state, and then - /// later attached to a file with a call to open(). Calling any - /// function other than open(), is_attached(), and ~SharedGroup() - /// on an unattached instance results in undefined behavior. - bool is_attached() const noexcept; - -#ifdef REALM_DEBUG - /// Deprecated method, only called from a unit test - /// - /// Reserve disk space now to avoid allocation errors at a later - /// point in time, and to minimize on-disk fragmentation. In some - /// cases, less fragmentation translates into improved - /// performance. - /// - /// When supported by the system, a call to this function will - /// make the database file at least as big as the specified size, - /// and cause space on the target device to be allocated (note - /// that on many systems on-disk allocation is done lazily by - /// default). If the file is already bigger than the specified - /// size, the size will be unchanged, and on-disk allocation will - /// occur only for the initial section that corresponds to the - /// specified size. - /// - /// It is an error to call this function on an unattached shared - /// group. Doing so will result in undefined behavior. - void reserve(size_t size_in_bytes); -#endif - - /// Querying for changes: - /// - /// NOTE: - /// "changed" means that one or more commits has been made to the database - /// since the SharedGroup (on which wait_for_change() is called) last - /// started, committed, promoted or advanced a transaction. If the - /// SharedGroup has not yet begun a transaction, "changed" is undefined. - /// - /// No distinction is made between changes done by another process - /// and changes done by another thread in the same process as the caller. - /// - /// Has db been changed ? - bool has_changed(); - - /// The calling thread goes to sleep until the database is changed, or - /// until wait_for_change_release() is called. After a call to - /// wait_for_change_release() further calls to wait_for_change() will return - /// immediately. To restore the ability to wait for a change, a call to - /// enable_wait_for_change() is required. Return true if the database has - /// changed, false if it might have. - bool wait_for_change(); - - /// release any thread waiting in wait_for_change() on *this* SharedGroup. - void wait_for_change_release(); - - /// re-enable waiting for change - void enable_wait_for_change(); - // Transactions: - - using version_type = _impl::History::version_type; - using VersionID = realm::VersionID; - - /// Thrown by begin_read() if the specified version does not correspond to a - /// bound (or tethered) snapshot. - struct BadVersion; - - /// \defgroup group_shared_transactions - //@{ - - /// begin_read() initiates a new read transaction. A read transaction is - /// bound to, and provides access to a particular snapshot of the underlying - /// Realm (in general the latest snapshot, but see \a version). It cannot be - /// used to modify the Realm, and in that sense, a read transaction is not a - /// real transaction. - /// - /// begin_write() initiates a new write transaction. A write transaction - /// allows the application to both read and modify the underlying Realm - /// file. At most one write transaction can be in progress at any given time - /// for a particular underlying Realm file. If another write transaction is - /// already in progress, begin_write() will block the caller until the other - /// write transaction terminates. No guarantees are made about the order in - /// which multiple concurrent requests will be served. - /// - /// It is an error to call begin_read() or begin_write() on a SharedGroup - /// object with an active read or write transaction. - /// - /// If begin_read() or begin_write() throws, no transaction is initiated, - /// and the application may try to initiate a new read or write transaction - /// later. - /// - /// end_read() terminates the active read transaction. If no read - /// transaction is active, end_read() does nothing. It is an error to call - /// this function on a SharedGroup object with an active write - /// transaction. end_read() does not throw. - /// - /// commit() commits all changes performed in the context of the active - /// write transaction, and thereby terminates that transaction. This - /// produces a new snapshot in the underlying Realm. commit() returns the - /// version associated with the new snapshot. It is an error to call - /// commit() when there is no active write transaction. If commit() throws, - /// no changes will have been committed, and the transaction will still be - /// active, but in a bad state. In that case, the application must either - /// call rollback() to terminate the bad transaction (in which case a new - /// transaction can be initiated), call close() which also terminates the - /// bad transaction, or destroy the SharedGroup object entirely. When the - /// transaction is in a bad state, the application is not allowed to call - /// any method on the Group accessor or on any of its subordinate accessors - /// (Table, Row, Descriptor). Note that the transaction is also left in a - /// bad state when a modifying operation on any subordinate accessor throws. - /// - /// rollback() terminates the active write transaction and discards any - /// changes performed in the context of it. If no write transaction is - /// active, rollback() does nothing. It is an error to call this function in - /// a SharedGroup object with an active read transaction. rollback() does - /// not throw. - /// - /// the Group accessor and all subordinate accessors (Table, Row, - /// Descriptor) that are obtained in the context of a particular read or - /// write transaction will become detached upon termination of that - /// transaction, which means that they can no longer be used to access the - /// underlying objects. - /// - /// Subordinate accessors that were detached at the end of the previous - /// read or write transaction will not be automatically reattached when a - /// new transaction is initiated. The application must reobtain new - /// accessors during a new transaction to regain access to the underlying - /// objects. - /// - /// \param version If specified, this must be the version associated with a - /// *bound* snapshot. A snapshot is said to be bound (or tethered) if there - /// is at least one active read or write transaction bound to it. A read - /// transaction is bound to the snapshot that it provides access to. A write - /// transaction is bound to the latest snapshot available at the time of - /// initiation of the write transaction. If the specified version is not - /// associated with a bound snapshot, this function throws BadVersion. - /// - /// \throw BadVersion Thrown by begin_read() if the specified version does - /// not correspond to a bound (or tethered) snapshot. - - const Group& begin_read(VersionID version = VersionID()); - void end_read() noexcept; - Group& begin_write(); - // Return true (and take the write lock) if there is no other write - // in progress. In case of contention return false immediately. - // If the write lock is obtained, also provide the Group associated - // with the SharedGroup for further operations. - bool try_begin_write(Group*& group); - version_type commit(); - void rollback() noexcept; - // report statistics of last commit done on THIS shared group. - // The free space reported is what can be expected to be freed - // by compact(). This may not correspond to the space which is free - // at the point where get_stats() is called, since that will include - // memory required to hold older versions of data, which still - // needs to be available. The locked space is the amount of memory - // that is free in current version, but being used in still live versions. - // Notice that we will always have two live versions - the current and the - // previous. - void get_stats(size_t& free_space, size_t& used_space, util::Optional locked_space = util::none) const; - //@} - - enum TransactStage { - transact_Ready, - transact_Reading, - transact_Writing, - }; - - /// Get the current transaction type - TransactStage get_transact_stage() const noexcept; - - /// Get a version id which may be used to request a different SharedGroup - /// to start transaction at a specific version. - VersionID get_version_of_current_transaction(); - - /// Report the number of distinct versions currently stored in the database. - /// Note: the database only cleans up versions as part of commit, so ending - /// a read transaction will not immediately release any versions. - uint_fast64_t get_number_of_versions(); - - /// Get the approximate size of the data that would be written to the file if - /// a commit were done at this point. The reported size will always be bigger - /// than what will eventually be needed as we reserve a bit more memory that - /// will be needed. - size_t get_commit_size() const; - - /// Get the size of the currently allocated slab area - size_t get_allocated_size() const; - - /// Compact the database file. - /// - The method will throw if called inside a transaction. - /// - The method will throw if called in unattached state. - /// - The method will return false if other SharedGroups are accessing the - /// database in which case compaction is not done. This is not - /// necessarily an error. - /// It will return true following successful compaction. - /// While compaction is in progress, attempts by other - /// threads or processes to open the database will wait. - /// Be warned that resource requirements for compaction is proportional to - /// the amount of live data in the database. - /// Compaction works by writing the database contents to a temporary - /// database file and then replacing the database with the temporary one. - /// The name of the temporary file is formed by appending - /// ".tmp_compaction_space" to the name of the database - /// - /// If the output_encryption_key is `none` then the file's existing key will - /// be used (if any). If the output_encryption_key is nullptr, the resulting - /// file will be unencrypted. Any other value will change the encryption of - /// the file to the new 64 byte key. - /// - /// FIXME: This function is not yet implemented in an exception-safe manner, - /// therefore, if it throws, the application should not attempt to - /// continue. If may not even be safe to destroy the SharedGroup object. - /// - /// WARNING / FIXME: compact() should NOT be exposed publicly on Windows - /// because it's not crash safe! It may corrupt your database if something fails - bool compact(bool bump_version_number = false, util::Optional output_encryption_key = util::none); - -#ifdef REALM_DEBUG - void test_ringbuf(); -#endif - - /// To handover a table view, query, linkview or row accessor of type T, you - /// must wrap it into a Handover for the transfer. Wrapping and - /// unwrapping of a handover object is done by the methods - /// 'export_for_handover()' and 'import_from_handover()' declared below. - /// 'export_for_handover()' returns a Handover object, and - /// 'import_for_handover()' consumes that object, producing a new accessor - /// which is ready for use in the context of the importing SharedGroup. - /// - /// The Handover always creates a new accessor object at the importing side. - /// For TableViews, there are 3 forms of handover. - /// - /// - with payload move: the payload is handed over and ends up as a payload - /// held by the accessor at the importing side. The accessor on the - /// exporting side will rerun its query and generate a new payload, if - /// TableView::sync_if_needed() is called. If the original payload was in - /// sync at the exporting side, it will also be in sync at the importing - /// side. This is indicated to handover_export() by the argument - /// MutableSourcePayload::Move - /// - /// - with payload copy: a copy of the payload is handed over, so both the - /// accessors on the exporting side *and* the accessors created at the - /// importing side has their own payload. This is indicated to - /// handover_export() by the argument ConstSourcePayload::Copy - /// - /// - without payload: the payload stays with the accessor on the exporting - /// side. On the importing side, the new accessor is created without - /// payload. A call to TableView::sync_if_needed() will trigger generation - /// of a new payload. This form of handover is indicated to - /// handover_export() by the argument ConstSourcePayload::Stay. - /// - /// For all other (non-TableView) accessors, handover is done with payload - /// copy, since the payload is trivial. - /// - /// Handover *without* payload is useful when you want to ship a tableview - /// with its query for execution in a background thread. Handover with - /// *payload move* is useful when you want to transfer the result back. - /// - /// Handover *without* payload or with payload copy is guaranteed *not* to - /// change the accessors on the exporting side. - /// - /// Handover is *not* thread safe and should be carried out - /// by the thread that "owns" the involved accessors. - /// - /// Handover is transitive: - /// If the object being handed over depends on other views - /// (table- or link- ), those objects will be handed over as well. The mode - /// of handover (payload copy, payload move, without payload) is applied - /// recursively. Note: If you are handing over a tableview dependent upon - /// another tableview and using MutableSourcePayload::Move, - /// you are on thin ice! - /// - /// On the importing side, the top-level accessor being created during - /// import takes ownership of all other accessors (if any) being created as - /// part of the import. - - /// Type used to support handover of accessors between shared groups. - template - struct Handover; - - /// thread-safe/const export (mode is Stay or Copy) - /// during export, the following operations on the shared group is locked: - /// - advance_read(), promote_to_write(), commit_and_continue_as_read(), - /// rollback_and_continue_as_read(), close() - template - std::unique_ptr> export_for_handover(const T& accessor, ConstSourcePayload mode); - - // specialization for handover of Rows - template - std::unique_ptr>> export_for_handover(const BasicRow& accessor); - - // destructive export (mode is Move) - template - std::unique_ptr> export_for_handover(T& accessor, MutableSourcePayload mode); - - /// Import an accessor wrapped in a handover object. The import will fail - /// if the importing SharedGroup is viewing a version of the database that - /// is different from the exporting SharedGroup. The call to - /// import_from_handover is not thread-safe. - template - std::unique_ptr import_from_handover(std::unique_ptr> handover); - - // We need two cases for handling of LinkViews, because they are ref counted. - std::unique_ptr> export_linkview_for_handover(const LinkViewRef& accessor); - LinkViewRef import_linkview_from_handover(std::unique_ptr> handover); - - // likewise for Tables. - std::unique_ptr> export_table_for_handover(const TableRef& accessor); - TableRef import_table_from_handover(std::unique_ptr> handover); - - /// When doing handover to background tasks that may be run later, we - /// may want to momentarily pin the current version until the other thread - /// has retrieved it. - /// - /// Pinning can be done in both read- and write-transactions, but with different - /// semantics. When pinning during a read-transaction, the version pinned is the - /// one accessible during the read-transaction. When pinning during a write-transaction, - /// the version pinned will be the last version that was succesfully committed to the - /// realm file at the point in time, when the write-transaction was started. - /// - /// The release is not thread-safe, so it has to be done on the SharedGroup - /// associated with the thread calling unpin_version(), and the SharedGroup - /// must be attached to the realm file at the point of unpinning. - - // Pin version for handover (not thread safe) - VersionID pin_version(); - - // Release pinned version (not thread safe) - void unpin_version(VersionID version); - - std::shared_ptr get_metrics(); - - // Try to grab a exclusive lock of the given realm path's lock file. If the lock - // can be acquired, the callback will be executed with the lock and then return true. - // Otherwise false will be returned directly. - // The lock taken precludes races with other threads or processes accessing the - // files through a SharedGroup. - // It is safe to delete/replace realm files inside the callback. - // WARNING: It is not safe to delete the lock file in the callback. - using CallbackWithLock = std::function; - static bool call_with_lock(const std::string& realm_path, CallbackWithLock callback); - - // Return a list of files/directories core may use of the given realm file path. - // The first element of the pair in the returned list is the path string, the - // second one is to indicate the path is a directory or not. - // The temporary files are not returned by this function. - // It is safe to delete those returned files/directories in the call_with_lock's callback. - static std::vector> get_core_files(const std::string& realm_path); - -private: - struct SharedInfo; - struct ReadCount; - struct ReadLockInfo { - uint_fast64_t m_version = std::numeric_limits::max(); - uint_fast32_t m_reader_idx = 0; - ref_type m_top_ref = 0; - size_t m_file_size = 0; - }; - class ReadLockUnlockGuard; - - // Member variables - size_t m_free_space = 0; - size_t m_locked_space = 0; - size_t m_used_space = 0; - Group m_group; - ReadLockInfo m_read_lock; - uint_fast32_t m_local_max_entry; - util::File m_file; - util::File::Map m_file_map; // Never remapped - util::File::Map m_reader_map; - bool m_wait_for_change_enabled; - std::string m_lockfile_path; - std::string m_lockfile_prefix; - std::string m_db_path; - std::string m_coordination_dir; - const char* m_key; - TransactStage m_transact_stage; - util::InterprocessMutex m_writemutex; -#ifdef REALM_ASYNC_DAEMON - util::InterprocessMutex m_balancemutex; -#endif - util::InterprocessMutex m_controlmutex; -#ifdef REALM_ASYNC_DAEMON - util::InterprocessCondVar m_room_to_write; - util::InterprocessCondVar m_work_to_do; - util::InterprocessCondVar m_daemon_becomes_ready; -#endif - util::InterprocessCondVar m_new_commit_available; - util::InterprocessCondVar m_pick_next_writer; - std::function m_upgrade_callback; - -#if REALM_METRICS - std::shared_ptr m_metrics; -#endif // REALM_METRICS - - void do_open(const std::string& file, bool no_create, bool is_backend, const SharedGroupOptions options); - - // Ring buffer management - bool ringbuf_is_empty() const noexcept; - size_t ringbuf_size() const noexcept; - size_t ringbuf_capacity() const noexcept; - bool ringbuf_is_first(size_t ndx) const noexcept; - void ringbuf_remove_first() noexcept; - size_t ringbuf_find(uint64_t version) const noexcept; - ReadCount& ringbuf_get(size_t ndx) noexcept; - ReadCount& ringbuf_get_first() noexcept; - ReadCount& ringbuf_get_last() noexcept; - void ringbuf_put(const ReadCount& v); - void ringbuf_expand(); - - /// Grab a read lock on the snapshot associated with the specified - /// version. If `version_id == VersionID()`, a read lock will be grabbed on - /// the latest available snapshot. Fails if the snapshot is no longer - /// available. - /// - /// As a side effect update memory mapping to ensure that the ringbuffer - /// entries referenced in the readlock info is accessible. - /// - /// FIXME: It needs to be made more clear exactly under which conditions - /// this function fails. Also, why is it useful to promise anything about - /// detection of bad versions? Can we really promise enough to make such a - /// promise useful to the caller? - void grab_read_lock(ReadLockInfo&, VersionID); - - // Release a specific read lock. The read lock MUST have been obtained by a - // call to grab_read_lock(). - void release_read_lock(ReadLockInfo&) noexcept; - - void do_begin_read(VersionID, bool writable); - void do_end_read() noexcept; - /// return true if write transaction can commence, false otherwise. - bool do_try_begin_write(); - void do_begin_write(); - version_type do_commit(); - void do_end_write() noexcept; - void set_transact_stage(TransactStage stage) noexcept; - - /// Returns the version of the latest snapshot. - version_type get_version_of_latest_snapshot(); - - /// Returns the version of the snapshot bound in the current read or write - /// transaction. It is an error to call this function when no transaction is - /// in progress. - version_type get_version_of_bound_snapshot() const noexcept; - - // make sure the given index is within the currently mapped area. - // if not, expand the mapped area. Returns true if the area is expanded. - bool grow_reader_mapping(uint_fast32_t index); - - // Must be called only by someone that has a lock on the write - // mutex. - void low_level_commit(uint_fast64_t new_version); - - void do_async_commits(); - - /// Upgrade file format and/or history schema - void upgrade_file_format(bool allow_file_format_upgrade, int target_file_format_version, - int current_hist_schema_version, int target_hist_schema_version); - - //@{ - /// See LangBindHelper. - template - void advance_read(O* observer, VersionID); - template - void promote_to_write(O* observer); - version_type commit_and_continue_as_read(); - template - void rollback_and_continue_as_read(O* observer); - //@} - - /// Returns true if, and only if _impl::History::update_early_from_top_ref() - /// was called during the execution of this function. - template - bool do_advance_read(O* observer, VersionID, _impl::History&); - - /// If there is an associated \ref Replication object, then this function - /// returns `repl->get_history()` where `repl` is that Replication object, - /// otherwise this function returns null. - _impl::History* get_history(); - - int get_file_format_version() const noexcept; - - /// finish up the process of starting a write transaction. Internal use only. - void finish_begin_write(); - - void close_internal(std::unique_lock) noexcept; - friend class _impl::SharedGroupFriend; -}; - - -inline void SharedGroup::get_stats(size_t& free_space, size_t& used_space, util::Optional locked_space) const -{ - free_space = m_free_space; - used_space = m_used_space; - if (locked_space) { - *locked_space = m_locked_space; - } -} - - -class ReadTransaction { -public: - ReadTransaction(SharedGroup& sg) - : m_shared_group(sg) - { - m_shared_group.begin_read(); // Throws - } - - ~ReadTransaction() noexcept - { - m_shared_group.end_read(); - } - - bool has_table(StringData name) const noexcept - { - return get_group().has_table(name); - } - - ConstTableRef get_table(size_t table_ndx) const - { - return get_group().get_table(table_ndx); // Throws - } - - ConstTableRef get_table(StringData name) const - { - return get_group().get_table(name); // Throws - } - - const Group& get_group() const noexcept; - - /// Get the version of the snapshot to which this read transaction is bound. - SharedGroup::version_type get_version() const noexcept; - -private: - SharedGroup& m_shared_group; -}; - - -class WriteTransaction { -public: - WriteTransaction(SharedGroup& sg) - : m_shared_group(&sg) - { - m_shared_group->begin_write(); // Throws - } - - ~WriteTransaction() noexcept - { - if (m_shared_group) - m_shared_group->rollback(); - } - - bool has_table(StringData name) const noexcept - { - return get_group().has_table(name); - } - - TableRef get_table(size_t table_ndx) const - { - return get_group().get_table(table_ndx); // Throws - } - - TableRef get_table(StringData name) const - { - return get_group().get_table(name); // Throws - } - - TableRef add_table(StringData name, bool require_unique_name = true) const - { - return get_group().add_table(name, require_unique_name); // Throws - } - - TableRef get_or_add_table(StringData name, bool* was_added = nullptr) const - { - return get_group().get_or_add_table(name, was_added); // Throws - } - - Group& get_group() const noexcept; - - /// Get the version of the snapshot on which this write transaction is - /// based. - SharedGroup::version_type get_version() const noexcept; - - SharedGroup::version_type commit() - { - REALM_ASSERT(m_shared_group); - SharedGroup::version_type new_version = m_shared_group->commit(); - m_shared_group = nullptr; - return new_version; - } - - void rollback() noexcept - { - REALM_ASSERT(m_shared_group); - m_shared_group->rollback(); - m_shared_group = nullptr; - } - -private: - SharedGroup* m_shared_group; -}; - - -// Implementation: - -struct SharedGroup::BadVersion : std::exception { -}; - -inline SharedGroup::SharedGroup(const std::string& file, bool no_create, const SharedGroupOptions options) - : m_group(Group::shared_tag()) - , m_upgrade_callback(std::move(options.upgrade_callback)) -{ - open(file, no_create, options); // Throws -} - -inline SharedGroup::SharedGroup(unattached_tag) noexcept - : m_group(Group::shared_tag()) -{ -} - -inline SharedGroup::SharedGroup(Replication& repl, const SharedGroupOptions options) - : m_group(Group::shared_tag()) - , m_upgrade_callback(std::move(options.upgrade_callback)) -{ - open(repl, options); // Throws -} - -inline void SharedGroup::open(const std::string& path, bool no_create_file, const SharedGroupOptions options) -{ - // Exception safety: Since open() is called from constructors, if it throws, - // it must leave the file closed. - - bool is_backend = false; - do_open(path, no_create_file, is_backend, options); // Throws -} - -inline void SharedGroup::open(Replication& repl, const SharedGroupOptions options) -{ - // Exception safety: Since open() is called from constructors, if it throws, - // it must leave the file closed. - - REALM_ASSERT(!is_attached()); - - repl.initialize(*this); // Throws - - typedef _impl::GroupFriend gf; - gf::set_replication(m_group, &repl); - - std::string file = repl.get_database_path(); - bool no_create = false; - bool is_backend = false; - do_open(file, no_create, is_backend, options); // Throws -} - -inline bool SharedGroup::is_attached() const noexcept -{ - return m_file_map.is_attached(); -} - -inline SharedGroup::TransactStage SharedGroup::get_transact_stage() const noexcept -{ - return m_transact_stage; -} - -inline SharedGroup::version_type SharedGroup::get_version_of_bound_snapshot() const noexcept -{ - return m_read_lock.m_version; -} - -class SharedGroup::ReadLockUnlockGuard { -public: - ReadLockUnlockGuard(SharedGroup& shared_group, ReadLockInfo& read_lock) noexcept - : m_shared_group(shared_group) - , m_read_lock(&read_lock) - { - } - ~ReadLockUnlockGuard() noexcept - { - if (m_read_lock) - m_shared_group.release_read_lock(*m_read_lock); - } - void release() noexcept - { - m_read_lock = 0; - } - -private: - SharedGroup& m_shared_group; - ReadLockInfo* m_read_lock; -}; - - -template -struct SharedGroup::Handover { - std::unique_ptr patch; - std::unique_ptr clone; - VersionID version; -}; - -template -std::unique_ptr> SharedGroup::export_for_handover(const T& accessor, ConstSourcePayload mode) -{ - if (m_transact_stage != transact_Reading) - throw LogicError(LogicError::wrong_transact_state); - std::unique_ptr> result(new Handover()); - // Implementation note: - // often, the return value from clone will be T*, BUT it may be ptr to some - // base of T instead, so we must cast it to T*. This is always safe, because - // no matter the type, clone() will clone the actual accessor instance, and - // hence return an instance of the same type. - result->clone.reset(dynamic_cast(accessor.clone_for_handover(result->patch, mode).release())); - result->version = get_version_of_current_transaction(); - return move(result); -} - - -template -std::unique_ptr>> SharedGroup::export_for_handover(const BasicRow& accessor) -{ - if (m_transact_stage != transact_Reading) - throw LogicError(LogicError::wrong_transact_state); - std::unique_ptr>> result(new Handover>()); - // See implementation note above. - result->clone.reset(dynamic_cast*>(accessor.clone_for_handover(result->patch).release())); - result->version = get_version_of_current_transaction(); - return move(result); -} - - -template -std::unique_ptr> SharedGroup::export_for_handover(T& accessor, MutableSourcePayload mode) -{ - if (m_transact_stage != transact_Reading) - throw LogicError(LogicError::wrong_transact_state); - std::unique_ptr> result(new Handover()); - // see implementation note above. - result->clone.reset(dynamic_cast(accessor.clone_for_handover(result->patch, mode).release())); - result->version = get_version_of_current_transaction(); - return move(result); -} - - -template -std::unique_ptr SharedGroup::import_from_handover(std::unique_ptr> handover) -{ - if (handover->version != get_version_of_current_transaction()) { - throw BadVersion(); - } - std::unique_ptr result = move(handover->clone); - result->apply_and_consume_patch(handover->patch, m_group); - return result; -} - -template -inline void SharedGroup::advance_read(O* observer, VersionID version_id) -{ - if (m_transact_stage != transact_Reading) - throw LogicError(LogicError::wrong_transact_state); - - // It is an error if the new version precedes the currently bound one. - if (version_id.version < m_read_lock.m_version) - throw LogicError(LogicError::bad_version); - - Replication* repl = m_group.get_replication(); - _impl::History* hist = repl ? repl->get_history() : nullptr; // Throws - - if (!hist) - throw LogicError(LogicError::no_history); - - bool hist_updated = do_advance_read(observer, version_id, *hist); // Throws - repl->initiate_transact(Replication::TransactionType::trans_Read, version_id.version, hist_updated); -} - -template -inline void SharedGroup::promote_to_write(O* observer) -{ - if (m_transact_stage != transact_Reading) - throw LogicError(LogicError::wrong_transact_state); - - _impl::History* hist = get_history(); // Throws - if (!hist) - throw LogicError(LogicError::no_history); - - do_begin_write(); // Throws - try { - VersionID version = VersionID(); // Latest - bool history_updated = do_advance_read(observer, version, *hist); // Throws - - Replication* repl = m_group.get_replication(); - REALM_ASSERT(repl); // Presence of `repl` follows from the presence of `hist` - version_type current_version = m_read_lock.m_version; - repl->initiate_transact(Replication::TransactionType::trans_Write, current_version, - history_updated); // Throws - - // If the group has no top array (top_ref == 0), create a new node - // structure for an empty group now, to be ready for modifications. See - // also Group::attach_shared(). - using gf = _impl::GroupFriend; - gf::create_empty_group_when_missing(m_group); // Throws - } - catch (...) { - do_end_write(); - throw; - } - - set_transact_stage(transact_Writing); -} - -template -inline void SharedGroup::rollback_and_continue_as_read(O* observer) -{ - if (m_transact_stage != transact_Writing) - throw LogicError(LogicError::wrong_transact_state); - - _impl::History* hist = get_history(); // Throws - if (!hist) - throw LogicError(LogicError::no_history); - - BinaryData uncommitted_changes = hist->get_uncommitted_changes(); - - // FIXME: We are currently creating two transaction log parsers, one here, - // and one in advance_transact(). That is wasteful as the parser creation is - // expensive. - _impl::SimpleInputStream in(uncommitted_changes.data(), uncommitted_changes.size()); - _impl::TransactLogParser parser; // Throws - _impl::TransactReverser reverser; - parser.parse(in, reverser); // Throws - - if (observer && uncommitted_changes.size()) { - _impl::ReversedNoCopyInputStream reversed_in(reverser); - parser.parse(reversed_in, *observer); // Throws - observer->parse_complete(); // Throws - } - - // Mark all managed space (beyond the attached file) as free. - using gf = _impl::GroupFriend; - gf::reset_free_space_tracking(m_group); // Throws - - ref_type top_ref = m_read_lock.m_top_ref; - size_t file_size = m_read_lock.m_file_size; - _impl::ReversedNoCopyInputStream reversed_in(reverser); - gf::advance_transact(m_group, top_ref, file_size, reversed_in); // Throws - - do_end_write(); - - Replication* repl = gf::get_replication(m_group); - REALM_ASSERT(repl); // Presence of `repl` follows from the presence of `hist` - repl->abort_transact(); - - set_transact_stage(transact_Reading); -} - -template -inline bool SharedGroup::do_advance_read(O* observer, VersionID version_id, _impl::History& hist) -{ - ReadLockInfo new_read_lock; - grab_read_lock(new_read_lock, version_id); // Throws - REALM_ASSERT(new_read_lock.m_version >= m_read_lock.m_version); - if (new_read_lock.m_version == m_read_lock.m_version) { - release_read_lock(new_read_lock); - // _impl::History::update_from_ref() was not called - return false; - } - - ReadLockUnlockGuard g(*this, new_read_lock); - { - version_type new_version = new_read_lock.m_version; - size_t new_file_size = new_read_lock.m_file_size; - - // Synchronize readers view of the file - SlabAlloc& alloc = m_group.m_alloc; - alloc.update_reader_view(new_file_size); - - ref_type hist_ref = _impl::GroupFriend::get_history_ref(alloc, new_read_lock.m_top_ref); - hist.update_from_ref_and_version(hist_ref, new_version); // Throws - } - - if (observer) { - // This has to happen in the context of the originally bound snapshot - // and while the read transaction is still in a fully functional state. - _impl::TransactLogParser parser; - version_type old_version = m_read_lock.m_version; - version_type new_version = new_read_lock.m_version; - _impl::ChangesetInputStream in(hist, old_version, new_version); - parser.parse(in, *observer); // Throws - observer->parse_complete(); // Throws - } - - // The old read lock must be retained for as long as the change history is - // accessed (until Group::advance_transact() returns). This ensures that the - // oldest needed changeset remains in the history, even when the history is - // implemented as a separate unversioned entity outside the Realm (i.e., the - // old implementation and ShortCircuitHistory in - // test_lang_Bind_helper.cpp). On the other hand, if it had been the case, - // that the history was always implemented as a versioned entity, that was - // part of the Realm state, then it would not have been necessary to retain - // the old read lock beyond this point. - - { - version_type old_version = m_read_lock.m_version; - version_type new_version = new_read_lock.m_version; - ref_type new_top_ref = new_read_lock.m_top_ref; - size_t new_file_size = new_read_lock.m_file_size; - _impl::ChangesetInputStream in(hist, old_version, new_version); - m_group.advance_transact(new_top_ref, new_file_size, in); // Throws - } - - g.release(); - release_read_lock(m_read_lock); - m_read_lock = new_read_lock; - - return true; // _impl::History::update_early_from_top_ref() was called -} - -inline _impl::History* SharedGroup::get_history() -{ - using gf = _impl::GroupFriend; - if (Replication* repl = gf::get_replication(m_group)) - return repl->get_history(); - return 0; -} - -inline int SharedGroup::get_file_format_version() const noexcept -{ - using gf = _impl::GroupFriend; - return gf::get_file_format_version(m_group); -} - - -// The purpose of this class is to give internal access to some, but -// not all of the non-public parts of the SharedGroup class. -class _impl::SharedGroupFriend { -public: - static Group& get_group(SharedGroup& sg) noexcept - { - return sg.m_group; - } - - template - static void advance_read(SharedGroup& sg, O* obs, SharedGroup::VersionID ver) - { - sg.advance_read(obs, ver); // Throws - } - - template - static void promote_to_write(SharedGroup& sg, O* obs) - { - sg.promote_to_write(obs); // Throws - } - - static SharedGroup::version_type commit_and_continue_as_read(SharedGroup& sg) - { - return sg.commit_and_continue_as_read(); // Throws - } - - template - static void rollback_and_continue_as_read(SharedGroup& sg, O* obs) - { - sg.rollback_and_continue_as_read(obs); // Throws - } - - static void async_daemon_open(SharedGroup& sg, const std::string& file) - { - bool no_create = true; - bool is_backend = true; - SharedGroupOptions options; - options.durability = SharedGroupOptions::Durability::Async; - options.encryption_key = nullptr; - options.allow_file_format_upgrade = false; - sg.do_open(file, no_create, is_backend, options); // Throws - } - - static int get_file_format_version(const SharedGroup& sg) noexcept - { - return sg.get_file_format_version(); - } - - static SharedGroup::version_type get_version_of_latest_snapshot(SharedGroup& sg) - { - return sg.get_version_of_latest_snapshot(); - } - - static SharedGroup::version_type get_version_of_bound_snapshot(const SharedGroup& sg) noexcept - { - return sg.get_version_of_bound_snapshot(); - } -}; - -inline const Group& ReadTransaction::get_group() const noexcept -{ - using sgf = _impl::SharedGroupFriend; - return sgf::get_group(m_shared_group); -} - -inline SharedGroup::version_type ReadTransaction::get_version() const noexcept -{ - using sgf = _impl::SharedGroupFriend; - return sgf::get_version_of_bound_snapshot(m_shared_group); -} - -inline Group& WriteTransaction::get_group() const noexcept -{ - REALM_ASSERT(m_shared_group); - using sgf = _impl::SharedGroupFriend; - return sgf::get_group(*m_shared_group); -} - -inline SharedGroup::version_type WriteTransaction::get_version() const noexcept -{ - using sgf = _impl::SharedGroupFriend; - return sgf::get_version_of_bound_snapshot(*m_shared_group); -} - -} // namespace realm - -#endif // REALM_GROUP_SHARED_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/group_shared_options.hpp b/Lesson14/Pods/Realm/include/core/realm/group_shared_options.hpp deleted file mode 100644 index 73f7d3e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/group_shared_options.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_GROUP_SHARED_OPTIONS_HPP -#define REALM_GROUP_SHARED_OPTIONS_HPP - -#include -#include - -namespace realm { - -struct SharedGroupOptions { - - /// The persistence level of the SharedGroup. - /// uint16_t is the type of SharedGroup::SharedInfo::durability - enum class Durability : uint16_t { - Full, - MemOnly, - Async, ///< Not yet supported on windows. - Unsafe // If you use this, you loose ACID property - }; - - explicit SharedGroupOptions(Durability level = Durability::Full, const char* key = nullptr, - bool allow_upgrade = true, - std::function file_upgrade_callback = std::function(), - std::string temp_directory = sys_tmp_dir, bool track_metrics = false, - size_t metrics_history_size = 10000) - : durability(level) - , encryption_key(key) - , allow_file_format_upgrade(allow_upgrade) - , upgrade_callback(file_upgrade_callback) - , temp_dir(temp_directory) - , enable_metrics(track_metrics) - , metrics_buffer_size(metrics_history_size) - - { - } - - explicit SharedGroupOptions(const char* key) - : durability(Durability::Full) - , encryption_key(key) - , allow_file_format_upgrade(true) - , upgrade_callback(std::function()) - , temp_dir(sys_tmp_dir) - , enable_metrics(false) - , metrics_buffer_size(10000) - { - } - - /// The persistence level of the Realm file. See Durability. - Durability durability; - - /// The key to encrypt and decrypt the Realm file with, or nullptr to - /// indicate that encryption should not be used. - const char* encryption_key; - - /// If \a allow_file_format_upgrade is set to `true`, this function will - /// automatically upgrade the file format used in the specified Realm file - /// if necessary (and if it is possible). In order to prevent this, set \a - /// allow_upgrade to `false`. - /// - /// If \a allow_upgrade is set to `false`, only two outcomes are possible: - /// - /// - the specified Realm file is already using the latest file format, and - /// can be used, or - /// - /// - the specified Realm file uses a deprecated file format, resulting a - /// the throwing of FileFormatUpgradeRequired. - bool allow_file_format_upgrade; - - /// Optionally allows a custom function to be called immediately after the - /// Realm file is upgraded. The two parameters in the function are the - /// previous version and the version just upgraded to, respectively. - /// If the callback function throws, the Realm file will safely abort the - /// upgrade (rollback the transaction) but the SharedGroup will not be opened. - std::function upgrade_callback; - - /// A path to a directory where Realm can write temporary files or pipes to. - /// This string should include a trailing slash '/'. - std::string temp_dir; - - /// Controls the feature of collecting various metrics to the SharedGroup. - /// A prerequisite is compiling with REALM_METRICS=ON. - bool enable_metrics; - - /// The maximum number of entries stored by the metrics (if enabled). If this number - /// is exceeded without being consumed, only the most recent entries will be stored. - size_t metrics_buffer_size; - - /// sys_tmp_dir will be used if the temp_dir is empty when creating SharedGroupOptions. - /// It must be writable and allowed to create pipe/fifo file on it. - /// set_sys_tmp_dir is not a thread-safe call and it is only supposed to be called once - // when process starts. - static void set_sys_tmp_dir(const std::string& dir) noexcept { sys_tmp_dir = dir; } - static std::string get_sys_tmp_dir() noexcept { return sys_tmp_dir; } - -private: - static std::string sys_tmp_dir; -}; - -} // end namespace realm - -#endif // REALM_GROUP_SHARED_OPTIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/group_writer.hpp b/Lesson14/Pods/Realm/include/core/realm/group_writer.hpp deleted file mode 100644 index 5721a3e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/group_writer.hpp +++ /dev/null @@ -1,202 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_GROUP_WRITER_HPP -#define REALM_GROUP_WRITER_HPP - -#include // unint8_t etc -#include -#include - -#include -#include -#include -#include -#include - - -namespace realm { - -// Pre-declarations -class Group; -class SlabAlloc; - - -/// This class is not supposed to be reused for multiple write sessions. In -/// particular, do not reuse it in case any of the functions throw. -/// -/// FIXME: Move this class to namespace realm::_impl and to subdir src/realm/impl. -class GroupWriter : public _impl::ArrayWriterBase { -public: - // For groups in transactional mode (Group::m_is_shared), this constructor - // must be called while a write transaction is in progress. - // - // The constructor adds free-space tracking information to the specified - // group, if it is not already present (4th and 5th entry in - // Group::m_top). If the specified group is in transactional mode - // (Group::m_is_shared), the constructor also adds version tracking - // information to the group, if it is not already present (6th and 7th entry - // in Group::m_top). - using Durability = SharedGroupOptions::Durability; - GroupWriter(Group&, Durability dura = Durability::Full); - ~GroupWriter(); - - void set_versions(uint64_t current, uint64_t read_lock) noexcept; - - /// Write all changed array nodes into free space. - /// - /// Returns the new top ref. When in full durability mode, call - /// commit() with the returned top ref. - ref_type write_group(); - - /// Flush changes to physical medium, then write the new top ref - /// to the file header, then flush again. Pass the top ref - /// returned by write_group(). - void commit(ref_type new_top_ref); - - size_t get_file_size() const noexcept; - - ref_type write_array(const char*, size_t, uint32_t) override; - -#ifdef REALM_DEBUG - void dump(); -#endif - - size_t get_free_space_size() const - { - return m_free_space_size; - } - - size_t get_locked_space_size() const - { - return m_locked_space_size; - } - -private: - class MapWindow; - Group& m_group; - SlabAlloc& m_alloc; - ArrayInteger m_free_positions; // 4th slot in Group::m_top - ArrayInteger m_free_lengths; // 5th slot in Group::m_top - ArrayInteger m_free_versions; // 6th slot in Group::m_top - uint64_t m_current_version = 0; - uint64_t m_readlock_version; - size_t m_window_alignment; - size_t m_free_space_size = 0; - size_t m_locked_space_size = 0; - Durability m_durability; - - struct FreeSpaceEntry { - FreeSpaceEntry(size_t r, size_t s, uint64_t v) - : ref(r) - , size(s) - , released_at_version(v) - { - } - size_t ref; - size_t size; - uint64_t released_at_version; - }; - class FreeList : public std::vector { - public: - FreeList() = default; - // Merge adjacent chunks - void merge_adjacent_entries_in_freelist(); - // Copy free space entries to structure where entries are sorted by size - void move_free_in_file_to_size_map(std::multimap& size_map); - }; - // m_free_in_file; - std::vector m_not_free_in_file; - std::multimap m_size_map; - using FreeListElement = std::multimap::iterator; - - void read_in_freelist(); - size_t recreate_freelist(size_t reserve_pos); - // Currently cached memory mappings. We keep as many as 16 1MB windows - // open for writing. The allocator will favor sequential allocation - // from a modest number of windows, depending upon fragmentation, so - // 16 windows should be more than enough. If more than 16 windows are - // needed, the least recently used is sync'ed and closed to make room - // for a new one. The windows are kept in MRU (most recently used) order. - const static int num_map_windows = 16; - std::vector> m_map_windows; - - // Get a suitable memory mapping for later access: - // potentially adding it to the cache, potentially closing - // the least recently used and sync'ing it to disk - MapWindow* get_window(ref_type start_ref, size_t size); - - // Sync all cached memory mappings - void sync_all_mappings(); - - /// Allocate a chunk of free space of the specified size. The - /// specified size must be 8-byte aligned. Extend the file if - /// required. The returned chunk is removed from the amount of - /// remaing free space. The returned chunk is guaranteed to be - /// within a single contiguous memory mapping. - /// - /// \return The position within the database file of the allocated - /// chunk. - size_t get_free_space(size_t size); - - /// Find a block of free space that is at least as big as the - /// specified size and which will allow an allocation that is mapped - /// inside a contiguous address range. The specified size does not - /// need to be 8-byte aligned. Extend the file if required. - /// The returned chunk is not removed from the amount of remaing - /// free space. - /// - /// \return A pair (`chunk_ndx`, `chunk_size`) where `chunk_ndx` - /// is the index of a chunk whose size is at least the requestd - /// size, and `chunk_size` is the size of that chunk. - FreeListElement reserve_free_space(size_t size); - - FreeListElement search_free_space_in_free_list_element(FreeListElement element, size_t size); - - /// Search only a range of the free list for a block as big as the - /// specified size. Return a pair with index and size of the found chunk. - /// \param found indicates whether a suitable block was found. - FreeListElement search_free_space_in_part_of_freelist(size_t size); - - /// Extend the file to ensure that a chunk of free space of the - /// specified size is available. The specified size does not need - /// to be 8-byte aligned. This function guarantees that it will - /// add at most one entry to the free-lists. - /// - /// \return A pair (`chunk_ndx`, `chunk_size`) where `chunk_ndx` - /// is the index of a chunk whose size is at least the requestd - /// size, and `chunk_size` is the size of that chunk. - FreeListElement extend_free_space(size_t requested_size); - - void write_array_at(MapWindow* window, ref_type, const char* data, size_t size); - FreeListElement split_freelist_chunk(FreeListElement, size_t alloc_pos); -}; - - -// Implementation: - -inline void GroupWriter::set_versions(uint64_t current, uint64_t read_lock) noexcept -{ - REALM_ASSERT(read_lock <= current); - m_current_version = current; - m_readlock_version = read_lock; -} - -} // namespace realm - -#endif // REALM_GROUP_WRITER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/handover_defs.hpp b/Lesson14/Pods/Realm/include/core/realm/handover_defs.hpp deleted file mode 100644 index cd8be27..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/handover_defs.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_HANDOVER_DEFS -#define REALM_HANDOVER_DEFS - -#include -#include - -namespace realm { - -enum class ConstSourcePayload { Copy, Stay }; -enum class MutableSourcePayload { Move }; - -struct RowBaseHandoverPatch; -struct TableViewHandoverPatch; - -struct TableHandoverPatch { - bool m_is_sub_table; - size_t m_table_num; - size_t m_col_ndx; - size_t m_row_ndx; -}; - -struct LinkViewHandoverPatch { - std::unique_ptr m_table; - size_t m_col_num; - size_t m_row_ndx; -}; - -// Base class for handover patches for query nodes. Subclasses are declared in query_engine.hpp. -struct QueryNodeHandoverPatch { - virtual ~QueryNodeHandoverPatch() = default; -}; - -using QueryNodeHandoverPatches = std::vector>; - -struct QueryHandoverPatch { - std::unique_ptr m_table; - std::unique_ptr table_view_data; - std::unique_ptr link_view_data; - QueryNodeHandoverPatches m_node_data; -}; - -enum class DescriptorType { Sort, Distinct, Limit, Include }; - -struct DescriptorLinkPath { - DescriptorLinkPath(size_t column_index, size_t table_index, bool column_is_backlink) - : col_ndx(column_index) - , table_ndx(table_index) - , is_backlink(column_is_backlink) - { - } - - size_t col_ndx; - size_t table_ndx; - bool is_backlink = false; -}; - -struct DescriptorExport { - DescriptorType type; - std::vector> columns; - std::vector ordering; - size_t limit; -}; - -struct DescriptorOrderingHandoverPatch { - std::vector descriptors; -}; - -struct TableViewHandoverPatch { - std::unique_ptr m_table; - std::unique_ptr linked_row; - size_t linked_col; - bool was_in_sync; - QueryHandoverPatch query_patch; - std::unique_ptr linkview_patch; - std::unique_ptr descriptors_patch; -}; - - -struct RowBaseHandoverPatch { - std::unique_ptr m_table; - size_t row_ndx; -}; - - -} // end namespace Realm - -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/history.hpp b/Lesson14/Pods/Realm/include/core/realm/history.hpp deleted file mode 100644 index 9710d0b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/history.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_HISTORY_HPP -#define REALM_HISTORY_HPP - -#include -#include - -#include - - -namespace realm { - -std::unique_ptr make_in_realm_history(const std::string& realm_path); - -} // namespace realm - - -#endif // REALM_HISTORY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/array_writer.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/array_writer.hpp deleted file mode 100644 index f039ad5..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/array_writer.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ARRAY_WRITER_HPP -#define REALM_ARRAY_WRITER_HPP - -#include - -namespace realm { -namespace _impl { - -class ArrayWriterBase { -public: - virtual ~ArrayWriterBase() - { - } - - /// Write the specified array data and its checksum into free - /// space. - /// - /// Returns the ref (position in the target stream) of the written copy of - /// the specified array data. - virtual ref_type write_array(const char* data, size_t size, uint32_t checksum) = 0; -}; - -} // namespace impl_ -} // namespace realm - -#endif // REALM_ARRAY_WRITER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp deleted file mode 100644 index 353e546..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/clamped_hex_dump.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_IMPL_CLAMPED_HEX_DUMP_HPP -#define REALM_IMPL_CLAMPED_HEX_DUMP_HPP - -#include -#include - -namespace realm { -namespace _impl { - -/// Limit the amount of dumped data to 1024 bytes. For use in connection with -/// logging. -inline std::string clamped_hex_dump(BinaryData blob, std::size_t max_size = 1024) -{ - bool was_clipped = false; - std::size_t size_2 = blob.size(); - if (size_2 > max_size) { - size_2 = max_size; - was_clipped = true; - } - std::string str = util::hex_dump(blob.data(), size_2); // Throws - if (was_clipped) - str += "..."; // Throws - return str; -} - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_CLAMPED_HEX_DUMP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/clock.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/clock.hpp deleted file mode 100644 index fdf8aa3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/clock.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_IMPL_CLOCK_HPP -#define REALM_IMPL_CLOCK_HPP - -#include -#include - -#include - -namespace realm { -namespace _impl { - -inline sync::milliseconds_type realtime_clock_now() noexcept -{ - using clock = std::chrono::system_clock; - auto time_since_epoch = clock::now().time_since_epoch(); - auto millis_since_epoch = - std::chrono::duration_cast(time_since_epoch).count(); - return sync::milliseconds_type(millis_since_epoch); -} - - -inline sync::milliseconds_type monotonic_clock_now() noexcept -{ - using clock = std::chrono::steady_clock; - auto time_since_epoch = clock::now().time_since_epoch(); - auto millis_since_epoch = - std::chrono::duration_cast(time_since_epoch).count(); - return sync::milliseconds_type(millis_since_epoch); -} - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_CLOCK_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp deleted file mode 100644 index deb0f8b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/cont_transact_hist.hpp +++ /dev/null @@ -1,147 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_CONT_TRANSACT_HIST_HPP -#define REALM_IMPL_CONT_TRANSACT_HIST_HPP - -#include -#include - -#include -#include - -namespace realm { - -class Group; - -namespace _impl { - -/// Read-only access to history of changesets as needed to enable continuous -/// transactions. -class History { -public: - using version_type = VersionID::version_type; - - virtual ~History() noexcept {} - - /// May be called during any transaction - /// - /// It is a precondition for calls to this function that the reader view is - /// updated - that is, the mapping is updated to provide full visibility to - /// the file. - /// - virtual void update_from_ref_and_version(ref_type ref, version_type version) = 0; - virtual void update_from_parent(version_type version) = 0; - - /// Get all changesets between the specified versions. References to those - /// changesets will be made available in successive entries of `buffer`. The - /// number of retrieved changesets is exactly `end_version - - /// begin_version`. If this number is greater than zero, the changeset made - /// available in `buffer[0]` is the one that brought the database from - /// `begin_version` to `begin_version + 1`. - /// - /// It is an error to specify a version (for \a begin_version or \a - /// end_version) that is outside the range [V,W] where V is the version that - /// immediately precedes the first changeset available in the history as the - /// history appears in the **latest** available snapshot, and W is the - /// version that immediately succeeds the last changeset available in the - /// history as the history appears in the snapshot bound to the **current** - /// transaction. This restriction is necessary to allow for different kinds - /// of implementations of the history (separate standalone history or - /// history as part of versioned Realm state). - /// - /// The callee retains ownership of the memory referenced by those entries, - /// i.e., the memory referenced by `buffer[i].changeset` is **not** handed - /// over to the caller. - /// - /// This function may be called only during a transaction (prior to - /// initiation of commit operation), and only after a successful invocation - /// of update_early_from_top_ref(). In that case, the caller may assume that - /// the memory references stay valid for the remainder of the transaction - /// (up until initiation of the commit operation). - virtual void get_changesets(version_type begin_version, version_type end_version, BinaryIterator* buffer) const - noexcept = 0; - - /// \brief Specify the version of the oldest bound snapshot. - /// - /// This function must be called by the associated SharedGroup object during - /// each successfully committed write transaction. It must be called before - /// the transaction is finalized (Replication::finalize_commit()) or aborted - /// (Replication::abort_transact()), but after the initiation of the commit - /// operation (Replication::prepare_commit()). This allows history - /// implementations to add new history entries before trimming off old ones, - /// and this, in turn, guarantees that the history never becomes empty, - /// except in the initial empty Realm state. - /// - /// The caller must pass the version (\a version) of the oldest snapshot - /// that is currently (or was recently) bound via a transaction of the - /// current session. This gives the history implementation an opportunity to - /// trim off leading (early) history entries. - /// - /// Since this function must be called during a write transaction, there - /// will always be at least one snapshot that is currently bound via a - /// transaction. - /// - /// The caller must guarantee that the passed version (\a version) is less - /// than or equal to `begin_version` in all future invocations of - /// get_changesets(). - /// - /// The caller is allowed to pass a version that is less than the version - /// passed in a preceding invocation. - /// - /// This function should be called as late as possible, to maximize the - /// trimming opportunity, but at a time where the write transaction is still - /// open for additional modifications. This is necessary because some types - /// of histories are stored inside the Realm file. - virtual void set_oldest_bound_version(version_type version) = 0; - - /// Get the list of uncommitted changes accumulated so far in the current - /// write transaction. - /// - /// The callee retains ownership of the referenced memory. The ownership is - /// not handed over to the caller. - /// - /// This function may be called only during a write transaction (prior to - /// initiation of commit operation). In that case, the caller may assume that the - /// returned memory reference stays valid for the remainder of the transaction (up - /// until initiation of the commit operation). - virtual BinaryData get_uncommitted_changes() noexcept = 0; - - virtual void verify() const = 0; - - void set_updated(bool updated) - { - m_updated = updated; - } - - void ensure_updated(version_type version) const - { - if (!m_updated) { - const_cast(this)->update_from_parent(version); - m_updated = true; - } - } - -private: - mutable bool m_updated = false; -}; - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_CONTINUOUS_TRANSACTIONS_HISTORY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/destroy_guard.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/destroy_guard.hpp deleted file mode 100644 index f5b5e37..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/destroy_guard.hpp +++ /dev/null @@ -1,237 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_DESTROY_GUARD_HPP -#define REALM_IMPL_DESTROY_GUARD_HPP - -#include -#include - -namespace realm { -namespace _impl { - - -/// Calls `ptr->destroy()` if the guarded pointer (`ptr`) is not null -/// when the guard is destroyed. For arrays (`T` = `Array`) this means -/// that the array is destroyed in a shallow fashion. See -/// `DeepArrayDestroyGuard` for an alternative. -template -class DestroyGuard { -public: - DestroyGuard() noexcept; - - DestroyGuard(T*) noexcept; - - ~DestroyGuard() noexcept; - - // Default implementations of copy/assign can trigger multiple destructions - DestroyGuard(const DestroyGuard&) = delete; - DestroyGuard& operator=(const DestroyGuard&) = delete; - - void reset(T*) noexcept; - - T* get() const noexcept; - - T* release() noexcept; - -private: - T* m_ptr; -}; - -using ShallowArrayDestroyGuard = DestroyGuard; - - -/// Calls `ptr->destroy_deep()` if the guarded Array pointer (`ptr`) -/// is not null when the guard is destroyed. -class DeepArrayDestroyGuard { -public: - DeepArrayDestroyGuard() noexcept; - - DeepArrayDestroyGuard(Array*) noexcept; - - ~DeepArrayDestroyGuard() noexcept; - - // Default implementations of copy/assign can trigger multiple destructions - DeepArrayDestroyGuard(const DeepArrayDestroyGuard&) = delete; - DeepArrayDestroyGuard& operator=(const DeepArrayDestroyGuard&) = delete; - - void reset(Array*) noexcept; - - Array* get() const noexcept; - - Array* release() noexcept; - -private: - Array* m_ptr; -}; - - -/// Calls `Array::destroy_deep(ref, alloc)` if the guarded 'ref' -/// (`ref`) is not zero when the guard is destroyed. -class DeepArrayRefDestroyGuard { -public: - DeepArrayRefDestroyGuard(Allocator&) noexcept; - - DeepArrayRefDestroyGuard(ref_type, Allocator&) noexcept; - - ~DeepArrayRefDestroyGuard() noexcept; - - // Default implementations of copy/assign can trigger multiple destructions - DeepArrayRefDestroyGuard(const DeepArrayRefDestroyGuard&) = delete; - DeepArrayRefDestroyGuard& operator=(const DeepArrayRefDestroyGuard&) = delete; - - void reset(ref_type) noexcept; - - ref_type get() const noexcept; - - ref_type release() noexcept; - -private: - ref_type m_ref; - Allocator& m_alloc; -}; - - -// Implementation: - -// DestroyGuard - -template -inline DestroyGuard::DestroyGuard() noexcept - : m_ptr(nullptr) -{ -} - -template -inline DestroyGuard::DestroyGuard(T* ptr) noexcept - : m_ptr(ptr) -{ -} - -template -inline DestroyGuard::~DestroyGuard() noexcept -{ - if (m_ptr) - m_ptr->destroy(); -} - -template -inline void DestroyGuard::reset(T* ptr) noexcept -{ - if (m_ptr) - m_ptr->destroy(); - m_ptr = ptr; -} - -template -inline T* DestroyGuard::get() const noexcept -{ - return m_ptr; -} - -template -inline T* DestroyGuard::release() noexcept -{ - T* ptr = m_ptr; - m_ptr = nullptr; - return ptr; -} - - -// DeepArrayDestroyGuard - -inline DeepArrayDestroyGuard::DeepArrayDestroyGuard() noexcept - : m_ptr(nullptr) -{ -} - -inline DeepArrayDestroyGuard::DeepArrayDestroyGuard(Array* ptr) noexcept - : m_ptr(ptr) -{ -} - -inline DeepArrayDestroyGuard::~DeepArrayDestroyGuard() noexcept -{ - if (m_ptr) - m_ptr->destroy_deep(); -} - -inline void DeepArrayDestroyGuard::reset(Array* ptr) noexcept -{ - if (m_ptr) - m_ptr->destroy_deep(); - m_ptr = ptr; -} - -inline Array* DeepArrayDestroyGuard::get() const noexcept -{ - return m_ptr; -} - -inline Array* DeepArrayDestroyGuard::release() noexcept -{ - Array* ptr = m_ptr; - m_ptr = nullptr; - return ptr; -} - - -// DeepArrayRefDestroyGuard - -inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(Allocator& alloc) noexcept - : m_ref(0) - , m_alloc(alloc) -{ -} - -inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(ref_type ref, Allocator& alloc) noexcept - : m_ref(ref) - , m_alloc(alloc) -{ -} - -inline DeepArrayRefDestroyGuard::~DeepArrayRefDestroyGuard() noexcept -{ - if (m_ref) - Array::destroy_deep(m_ref, m_alloc); -} - -inline void DeepArrayRefDestroyGuard::reset(ref_type ref) noexcept -{ - if (m_ref) - Array::destroy_deep(m_ref, m_alloc); - m_ref = ref; -} - -inline ref_type DeepArrayRefDestroyGuard::get() const noexcept -{ - return m_ref; -} - -inline ref_type DeepArrayRefDestroyGuard::release() noexcept -{ - ref_type ref = m_ref; - m_ref = 0; - return ref; -} - - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_DESTROY_GUARD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/input_stream.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/input_stream.hpp deleted file mode 100644 index 80db30a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/input_stream.hpp +++ /dev/null @@ -1,255 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_INPUT_STREAM_HPP -#define REALM_IMPL_INPUT_STREAM_HPP - -#include - -#include -#include -#include - - -namespace realm { -namespace _impl { - - -class InputStream { -public: - /// Read bytes from this input stream and place them in the specified - /// buffer. The returned value is the actual number of bytes that were read, - /// and this is some number `n` such that `n <= min(size, m)` where `m` is - /// the number of bytes that could have been read from this stream before - /// reaching its end. Also, `n` cannot be zero unless `m` or `size` is - /// zero. The intention is that `size` should be non-zero, a the return - /// value used as the end-of-input indicator. - /// - /// Implementations are only allowed to block (put the calling thread to - /// sleep) up until the point in time where the first byte can be made - /// availble. - virtual size_t read(char* buffer, size_t size) = 0; - - virtual ~InputStream() noexcept - { - } -}; - - -class SimpleInputStream : public InputStream { -public: - SimpleInputStream(const char* data, size_t size) noexcept - : m_ptr(data) - , m_end(data + size) - { - } - size_t read(char* buffer, size_t size) override - { - size_t n = std::min(size, size_t(m_end - m_ptr)); - const char* begin = m_ptr; - m_ptr += n; - realm::safe_copy_n(begin, n, buffer); - return n; - } - -private: - const char* m_ptr; - const char* const m_end; -}; - - -class NoCopyInputStream { -public: - /// \return if any bytes was read. - /// A value of false indicates end-of-input. - /// If return value is true, \a begin and \a end are - /// updated to reflect the start and limit of a - /// contiguous memory chunk. - virtual bool next_block(const char*& begin, const char*& end) = 0; - - virtual ~NoCopyInputStream() noexcept - { - } -}; - - -class NoCopyInputStreamAdaptor : public NoCopyInputStream { -public: - NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept - : m_in(in) - , m_buffer(buffer) - , m_buffer_size(buffer_size) - { - } - bool next_block(const char*& begin, const char*& end) override - { - size_t n = m_in.read(m_buffer, m_buffer_size); - begin = m_buffer; - end = m_buffer + n; - return n; - } - -private: - InputStream& m_in; - char* m_buffer; - size_t m_buffer_size; -}; - - -class SimpleNoCopyInputStream : public NoCopyInputStream { -public: - SimpleNoCopyInputStream(const char* data, size_t size) - : m_data(data) - , m_size(size) - { - } - - bool next_block(const char*& begin, const char*& end) override - { - if (m_size == 0) - return 0; - size_t size = m_size; - begin = m_data; - end = m_data + size; - m_size = 0; - return size; - } - -private: - const char* m_data; - size_t m_size; -}; - -class MultiLogNoCopyInputStream : public NoCopyInputStream { -public: - MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end) - : m_logs_begin(logs_begin) - , m_logs_end(logs_end) - { - if (m_logs_begin != m_logs_end) - m_curr_buf_remaining_size = m_logs_begin->size(); - } - - size_t read(char* buffer, size_t size) - { - if (m_logs_begin == m_logs_end) - return 0; - for (;;) { - if (m_curr_buf_remaining_size > 0) { - size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size; - const char* data = m_logs_begin->data() + offset; - size_t size_2 = std::min(m_curr_buf_remaining_size, size); - m_curr_buf_remaining_size -= size_2; - // FIXME: Eliminate the need for copying by changing the API of - // Replication::InputStream such that blocks can be handed over - // without copying. This is a straight forward change, but the - // result is going to be more complicated and less conventional. - realm::safe_copy_n(data, size_2, buffer); - return size_2; - } - - ++m_logs_begin; - if (m_logs_begin == m_logs_end) - return 0; - m_curr_buf_remaining_size = m_logs_begin->size(); - } - } - - bool next_block(const char*& begin, const char*& end) override - { - while (m_logs_begin < m_logs_end) { - size_t result = m_logs_begin->size(); - const char* data = m_logs_begin->data(); - m_logs_begin++; - if (result == 0) - continue; // skip empty blocks - begin = data; - end = data + result; - return result; - } - return 0; - } - -private: - const BinaryData* m_logs_begin; - const BinaryData* m_logs_end; - size_t m_curr_buf_remaining_size; -}; - - -class ChangesetInputStream : public NoCopyInputStream { -public: - using version_type = History::version_type; - static constexpr unsigned NB_BUFFERS = 8; - - ChangesetInputStream(History& hist, version_type begin_version, version_type end_version) - : m_history(hist) - , m_begin_version(begin_version) - , m_end_version(end_version) - { - get_changeset(); - } - - bool next_block(const char*& begin, const char*& end) override - { - while (m_valid) { - BinaryData actual = m_changesets_begin->get_next(); - - if (actual.size() > 0) { - begin = actual.data(); - end = actual.data() + actual.size(); - return true; - } - - m_changesets_begin++; - - if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) { - get_changeset(); - } - } - return false; // End of input - } - -private: - History& m_history; - version_type m_begin_version, m_end_version; - BinaryIterator m_changesets[NB_BUFFERS]; // Buffer - BinaryIterator* m_changesets_begin = nullptr; - BinaryIterator* m_changesets_end = nullptr; - bool m_valid; - - void get_changeset() - { - auto versions_to_get = m_end_version - m_begin_version; - m_valid = versions_to_get > 0; - if (m_valid) { - if (versions_to_get > NB_BUFFERS) - versions_to_get = NB_BUFFERS; - version_type end_version = m_begin_version + versions_to_get; - m_history.get_changesets(m_begin_version, end_version, m_changesets); - m_begin_version = end_version; - m_changesets_begin = m_changesets; - m_changesets_end = m_changesets_begin + versions_to_get; - } - } -}; - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_INPUT_STREAM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/output_stream.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/output_stream.hpp deleted file mode 100644 index 1d022cd..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/output_stream.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_OUTPUT_STREAM_HPP -#define REALM_IMPL_OUTPUT_STREAM_HPP - -#include -#include - -#include - -#include - -#include - -namespace realm { -namespace _impl { - - -class OutputStream : public ArrayWriterBase { -public: - OutputStream(std::ostream&); - ~OutputStream() noexcept; - - ref_type get_ref_of_next_array() const noexcept; - - void write(const char* data, size_t size); - - ref_type write_array(const char* data, size_t size, uint32_t checksum) override; - -private: - ref_type m_next_ref; - std::ostream& m_out; - - void do_write(const char* data, size_t size); -}; - - -// Implementation: - -inline OutputStream::OutputStream(std::ostream& out) - : m_next_ref(0) - , m_out(out) -{ -} - -inline OutputStream::~OutputStream() noexcept -{ -} - -inline size_t OutputStream::get_ref_of_next_array() const noexcept -{ - return m_next_ref; -} - - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_OUTPUT_STREAM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/sequential_getter.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/sequential_getter.hpp deleted file mode 100644 index c7dd866..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/sequential_getter.hpp +++ /dev/null @@ -1,130 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_SEQUENTIAL_GETTER_HPP -#define REALM_IMPL_SEQUENTIAL_GETTER_HPP - -namespace realm { - -class SequentialGetterBase { -public: - virtual ~SequentialGetterBase() noexcept - { - } -}; - -template -class SequentialGetter : public SequentialGetterBase { -public: - using T = typename ColType::value_type; - using ArrayType = typename ColType::LeafType; - - SequentialGetter() - { - } - - SequentialGetter(const Table& table, size_t column_ndx) - { - init(static_cast(&table.get_column_base(column_ndx))); - } - - SequentialGetter(const ColType* column) - { - init(column); - } - - ~SequentialGetter() noexcept override - { - } - - void init(const ColType* column) - { - REALM_ASSERT(column != nullptr); - m_array_ptr.reset(); // Explicitly destroy the old one first, because we're reusing the memory. - m_array_ptr.reset(new (&m_leaf_accessor_storage) ArrayType(column->get_alloc())); - m_column = column; - m_leaf_end = 0; - } - - REALM_FORCEINLINE bool cache_next(size_t index) - { - // Set m_leaf_ptr to point at the leaf that contains the value at column row `index`. Return whether or not - // the leaf has changed (could be useful to know for caller). - - // FIXME: Below line has been commented away because array leafs might relocate during the lifetime of the - // object that owns this SequentialGetter. Enable again when we have proper support for that. - // if (index >= m_leaf_end || index < m_leaf_start) - { - typename ColType::LeafInfo leaf{&m_leaf_ptr, m_array_ptr.get()}; - size_t ndx_in_leaf; - m_column->get_leaf(index, ndx_in_leaf, leaf); - m_leaf_start = index - ndx_in_leaf; - const size_t leaf_size = m_leaf_ptr->size(); - m_leaf_end = m_leaf_start + leaf_size; - return true; - } - return false; - } - - - REALM_FORCEINLINE T get_next(size_t index) - { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4800) // Disable the Microsoft warning about bool performance issue. -#endif - return m_column->get(index); - - // FIXME: Below optimization is skipped because array leafs might relocate during the lifetime of the - // object that owns this SequentialGetter. Enable again when we have proper support for that. -// -// cache_next(index); -// T av = m_leaf_ptr->get(index - m_leaf_start); -// return av; - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - } - - size_t local_end(size_t global_end) - { - if (global_end > m_leaf_end) - return m_leaf_end - m_leaf_start; - else - return global_end - m_leaf_start; - } - - size_t m_leaf_start = 0; - size_t m_leaf_end = 0; - const ColType* m_column = nullptr; - - const ArrayType* m_leaf_ptr = nullptr; - -private: - // Leaf cache for when the root of the column is not a leaf. - // This dog and pony show is because Array has a reference to Allocator internally, - // but we need to be able to transfer queries between contexts, so init() reinitializes - // the leaf cache in the context of the current column. - typename std::aligned_storage::type m_leaf_accessor_storage; - std::unique_ptr m_array_ptr; -}; - -} // namespace realm - -#endif // REALM_IMPL_SEQUENTIAL_GETTER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/simulated_failure.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/simulated_failure.hpp deleted file mode 100644 index 4958151..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/simulated_failure.hpp +++ /dev/null @@ -1,228 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_SIMULATED_FAILURE_HPP -#define REALM_IMPL_SIMULATED_FAILURE_HPP - -#include -#include - -#include - -#ifdef REALM_DEBUG -#define REALM_ENABLE_SIMULATED_FAILURE -#endif - -namespace realm { -namespace _impl { - -class SimulatedFailure : public std::system_error { -public: - enum FailureType { - generic, - slab_alloc__reset_free_space_tracking, - slab_alloc__remap, - shared_group__grow_reader_mapping, - sync_client__read_head, - sync_server__read_head, - _num_failure_types - }; - - class OneShotPrimeGuard; - class RandomPrimeGuard; - - /// Prime the specified failure type on the calling thread for triggering - /// once. - static void prime_one_shot(FailureType); - - /// Prime the specified failure type on the calling thread for triggering - /// randomly \a n out of \a m times. - static void prime_random(FailureType, int n, int m, uint_fast64_t seed = 0); - - /// Unprime the specified failure type on the calling thread. - static void unprime(FailureType) noexcept; - - /// Returns true according to the mode of priming of the specified failure - /// type on the calling thread, but only if REALM_ENABLE_SIMULATED_FAILURE - /// was defined during compilation. If REALM_ENABLE_SIMULATED_FAILURE was - /// not defined, this function always return false. - static bool check_trigger(FailureType) noexcept; - - /// The specified error code is set to `make_error_code(failure_type)` if - /// check_trigger() returns true. Otherwise it is set to - /// `std::error_code()`. Returns a copy of the updated error code. - static std::error_code trigger(FailureType failure_type, std::error_code&) noexcept; - - /// Throws SimulatedFailure if check_trigger() returns true. The exception - /// will be constructed with an error code equal to - /// `make_error_code(failure_type)`. - static void trigger(FailureType failure_type); - - /// Returns true when, and only when REALM_ENABLE_SIMULATED_FAILURE was - /// defined during compilation. - static constexpr bool is_enabled(); - - SimulatedFailure(std::error_code); - -private: -#ifdef REALM_ENABLE_SIMULATED_FAILURE - static void do_prime_one_shot(FailureType); - static void do_prime_random(FailureType, int n, int m, uint_fast64_t seed); - static void do_unprime(FailureType) noexcept; - static bool do_check_trigger(FailureType) noexcept; -#endif -}; - -std::error_code make_error_code(SimulatedFailure::FailureType) noexcept; - -class SimulatedFailure::OneShotPrimeGuard { -public: - OneShotPrimeGuard(FailureType); - ~OneShotPrimeGuard() noexcept; - -private: - const FailureType m_type; -}; - - -class SimulatedFailure::RandomPrimeGuard { -public: - RandomPrimeGuard(FailureType, int n, int m, uint_fast64_t seed = 0); - ~RandomPrimeGuard() noexcept; - -private: - const FailureType m_type; -}; - -std::error_code make_error_code(SimulatedFailure::FailureType) noexcept; - -} // namespace _impl -} // namespace realm - -namespace std { - -template<> struct is_error_code_enum { - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace _impl { - - -// Implementation - -inline void SimulatedFailure::prime_one_shot(FailureType failure_type) -{ -#ifdef REALM_ENABLE_SIMULATED_FAILURE - do_prime_one_shot(failure_type); -#else - static_cast(failure_type); -#endif -} - -inline void SimulatedFailure::prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed) -{ -#ifdef REALM_ENABLE_SIMULATED_FAILURE - do_prime_random(failure_type, n, m, seed); -#else - static_cast(failure_type); - static_cast(n); - static_cast(m); - static_cast(seed); -#endif -} - -inline void SimulatedFailure::unprime(FailureType failure_type) noexcept -{ -#ifdef REALM_ENABLE_SIMULATED_FAILURE - do_unprime(failure_type); -#else - static_cast(failure_type); -#endif -} - -inline bool SimulatedFailure::check_trigger(FailureType failure_type) noexcept -{ -#ifdef REALM_ENABLE_SIMULATED_FAILURE - return do_check_trigger(failure_type); -#else - static_cast(failure_type); - return false; -#endif -} - -inline std::error_code SimulatedFailure::trigger(FailureType failure_type, std::error_code& ec) noexcept -{ - if (check_trigger(failure_type)) { - ec = make_error_code(failure_type); - } - else { - ec = std::error_code(); - } - return ec; -} - -inline void SimulatedFailure::trigger(FailureType failure_type) -{ - if (check_trigger(failure_type)) - throw SimulatedFailure(make_error_code(failure_type)); -} - -inline constexpr bool SimulatedFailure::is_enabled() -{ -#ifdef REALM_ENABLE_SIMULATED_FAILURE - return true; -#else - return false; -#endif -} - -inline SimulatedFailure::SimulatedFailure(std::error_code ec) - : std::system_error(ec) -{ -} - -inline SimulatedFailure::OneShotPrimeGuard::OneShotPrimeGuard(FailureType failure_type) - : m_type(failure_type) -{ - prime_one_shot(m_type); -} - -inline SimulatedFailure::OneShotPrimeGuard::~OneShotPrimeGuard() noexcept -{ - unprime(m_type); -} - -inline SimulatedFailure::RandomPrimeGuard::RandomPrimeGuard(FailureType failure_type, int n, int m, - uint_fast64_t seed) - : m_type(failure_type) -{ - prime_random(m_type, n, m, seed); -} - -inline SimulatedFailure::RandomPrimeGuard::~RandomPrimeGuard() noexcept -{ - unprime(m_type); -} - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_SIMULATED_FAILURE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/impl/transact_log.hpp b/Lesson14/Pods/Realm/include/core/realm/impl/transact_log.hpp deleted file mode 100644 index edace6c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/impl/transact_log.hpp +++ /dev/null @@ -1,2808 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_IMPL_TRANSACT_LOG_HPP -#define REALM_IMPL_TRANSACT_LOG_HPP - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace realm { -namespace _impl { - -/// Transaction log instruction encoding -/// NOTE: Any change to this enum is a file-format breaking change. -enum Instruction { - instr_InsertGroupLevelTable = 1, - instr_EraseGroupLevelTable = 2, // Remove columnless table from group - instr_RenameGroupLevelTable = 3, - instr_MoveGroupLevelTable = 4, // UNSUPPORTED/UNUSED. FIXME: remove in next breaking change - instr_SelectTable = 5, - instr_Set = 6, - instr_SetUnique = 7, - instr_SetDefault = 8, - instr_AddInteger = 9, // Add value to integer field - instr_NullifyLink = 10, // Set link to null due to target being erased - instr_InsertSubstring = 11, - instr_EraseFromString = 12, - instr_InsertEmptyRows = 13, - instr_EraseRows = 14, // Remove (multiple) rows - instr_SwapRows = 15, - instr_MoveRow = 16, - instr_MergeRows = 17, // Replace links pointing to row A with links to row B - instr_ClearTable = 18, // Remove all rows in selected table - instr_OptimizeTable = 19, - instr_SelectDescriptor = 20, // Select descriptor from currently selected root table - instr_InsertColumn = - 21, // Insert new non-nullable column into to selected descriptor (nullable is instr_InsertNullableColumn) - instr_InsertLinkColumn = 22, // do, but for a link-type column - instr_InsertNullableColumn = 23, // Insert nullable column - instr_EraseColumn = 24, // Remove column from selected descriptor - instr_EraseLinkColumn = 25, // Remove link-type column from selected descriptor - instr_RenameColumn = 26, // Rename column in selected descriptor - instr_MoveColumn = 27, // Move column in selected descriptor (UNSUPPORTED/UNUSED) FIXME: remove - instr_AddSearchIndex = 28, // Add a search index to a column - instr_RemoveSearchIndex = 29, // Remove a search index from a column - instr_SetLinkType = 30, // Strong/weak - instr_SelectLinkList = 31, - instr_LinkListSet = 32, // Assign to link list entry - instr_LinkListInsert = 33, // Insert entry into link list - instr_LinkListMove = 34, // Move an entry within a link list - instr_LinkListSwap = 35, // Swap two entries within a link list - instr_LinkListErase = 36, // Remove an entry from a link list - instr_LinkListNullify = 37, // Remove an entry from a link list due to linked row being erased - instr_LinkListClear = 38, // Ramove all entries from a link list - instr_LinkListSetAll = 39, // Assign to link list entry - instr_AddRowWithKey = 40, // Insert a row with a given key -}; - -class TransactLogStream { -public: - /// Ensure contiguous free space in the transaction log - /// buffer. This method must update `out_free_begin` - /// and `out_free_end` such that they refer to a chunk - /// of free space whose size is at least \a n. - /// - /// \param n The required amount of contiguous free space. Must be - /// small (probably not greater than 1024) - /// \param n Must be small (probably not greater than 1024) - virtual void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) = 0; - - /// Copy the specified data into the transaction log buffer. This - /// function should be called only when the specified data does - /// not fit inside the chunk of free space currently referred to - /// by `out_free_begin` and `out_free_end`. - /// - /// This method must update `out_begin` and - /// `out_end` such that, upon return, they still - /// refer to a (possibly empty) chunk of free space. - virtual void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) = 0; -}; - -class TransactLogBufferStream : public TransactLogStream { -public: - void transact_log_reserve(size_t size, char** out_free_begin, char** out_free_end) override; - void transact_log_append(const char* data, size_t size, char** out_free_begin, char** out_free_end) override; - - const char* transact_log_data() const; - - util::Buffer m_buffer; -}; - - -// LCOV_EXCL_START (because the NullInstructionObserver is trivial) -class NullInstructionObserver { -public: - /// The following methods are also those that TransactLogParser expects - /// to find on the `InstructionHandler`. - - // No selection needed: - bool select_table(size_t, size_t, const size_t*) - { - return true; - } - bool select_descriptor(size_t, const size_t*) - { - return true; - } - bool select_link_list(size_t, size_t, size_t) - { - return true; - } - bool insert_group_level_table(size_t, size_t, StringData) - { - return true; - } - bool erase_group_level_table(size_t, size_t) - { - return true; - } - bool rename_group_level_table(size_t, StringData) - { - return true; - } - - // Must have table selected: - bool insert_empty_rows(size_t, size_t, size_t, bool) - { - return true; - } - bool add_row_with_key(size_t, size_t, size_t, int64_t) - { - return true; - } - bool erase_rows(size_t, size_t, size_t, bool) - { - return true; - } - bool swap_rows(size_t, size_t) - { - return true; - } - bool move_row(size_t, size_t) - { - return true; - } - bool merge_rows(size_t, size_t) - { - return true; - } - bool clear_table(size_t) - { - return true; - } - bool set_int(size_t, size_t, int_fast64_t, Instruction, size_t) - { - return true; - } - bool add_int(size_t, size_t, int_fast64_t) - { - return true; - } - bool set_bool(size_t, size_t, bool, Instruction) - { - return true; - } - bool set_float(size_t, size_t, float, Instruction) - { - return true; - } - bool set_double(size_t, size_t, double, Instruction) - { - return true; - } - bool set_string(size_t, size_t, StringData, Instruction, size_t) - { - return true; - } - bool set_binary(size_t, size_t, BinaryData, Instruction) - { - return true; - } - bool set_olddatetime(size_t, size_t, OldDateTime, Instruction) - { - return true; - } - bool set_timestamp(size_t, size_t, Timestamp, Instruction) - { - return true; - } - bool set_table(size_t, size_t, Instruction) - { - return true; - } - bool set_mixed(size_t, size_t, const Mixed&, Instruction) - { - return true; - } - bool set_link(size_t, size_t, size_t, size_t, Instruction) - { - return true; - } - bool set_null(size_t, size_t, Instruction, size_t) - { - return true; - } - bool nullify_link(size_t, size_t, size_t) - { - return true; - } - bool insert_substring(size_t, size_t, size_t, StringData) - { - return true; - } - bool erase_substring(size_t, size_t, size_t, size_t) - { - return true; - } - bool optimize_table() - { - return true; - } - - // Must have descriptor selected: - bool insert_link_column(size_t, DataType, StringData, size_t, size_t) - { - return true; - } - bool insert_column(size_t, DataType, StringData, bool) - { - return true; - } - bool erase_link_column(size_t, size_t, size_t) - { - return true; - } - bool erase_column(size_t) - { - return true; - } - bool rename_column(size_t, StringData) - { - return true; - } - bool add_search_index(size_t) - { - return true; - } - bool remove_search_index(size_t) - { - return true; - } - bool set_link_type(size_t, LinkType) - { - return true; - } - - // Must have linklist selected: - bool link_list_set(size_t, size_t, size_t) - { - return true; - } - bool link_list_insert(size_t, size_t, size_t) - { - return true; - } - bool link_list_move(size_t, size_t) - { - return true; - } - bool link_list_swap(size_t, size_t) - { - return true; - } - bool link_list_erase(size_t, size_t) - { - return true; - } - bool link_list_nullify(size_t, size_t) - { - return true; - } - bool link_list_clear(size_t) - { - return true; - } - - void parse_complete() - { - } -}; -// LCOV_EXCL_STOP (NullInstructionObserver) - - -/// See TransactLogConvenientEncoder for information about the meaning of the -/// arguments of each of the functions in this class. -class TransactLogEncoder { -public: - /// The following methods are also those that TransactLogParser expects - /// to find on the `InstructionHandler`. - - // No selection needed: - bool select_table(size_t group_level_ndx, size_t levels, const size_t* path); - bool select_descriptor(size_t levels, const size_t* path); - bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx); - bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name); - bool erase_group_level_table(size_t table_ndx, size_t num_tables); - bool rename_group_level_table(size_t table_ndx, StringData new_name); - - /// Must have table selected. - bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool unordered); - bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, int64_t key); - bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool unordered); - bool swap_rows(size_t row_ndx_1, size_t row_ndx_2); - bool move_row(size_t from_ndx, size_t to_ndx); - bool merge_rows(size_t row_ndx, size_t new_row_ndx); - bool clear_table(size_t old_table_size); - - bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t, Instruction = instr_Set, size_t = 0); - bool add_int(size_t col_ndx, size_t row_ndx, int_fast64_t); - bool set_bool(size_t col_ndx, size_t row_ndx, bool, Instruction = instr_Set); - bool set_float(size_t col_ndx, size_t row_ndx, float, Instruction = instr_Set); - bool set_double(size_t col_ndx, size_t row_ndx, double, Instruction = instr_Set); - bool set_string(size_t col_ndx, size_t row_ndx, StringData, Instruction = instr_Set, size_t = 0); - bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData, Instruction = instr_Set); - bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime, Instruction = instr_Set); - bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp, Instruction = instr_Set); - bool set_table(size_t col_ndx, size_t row_ndx, Instruction = instr_Set); - bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed&, Instruction = instr_Set); - bool set_link(size_t col_ndx, size_t row_ndx, size_t, size_t target_group_level_ndx, Instruction = instr_Set); - bool set_null(size_t col_ndx, size_t row_ndx, Instruction = instr_Set, size_t = 0); - bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx); - bool insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData); - bool erase_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t size); - bool optimize_table(); - - // Must have descriptor selected: - bool insert_link_column(size_t col_ndx, DataType, StringData name, size_t link_target_table_ndx, - size_t backlink_col_ndx); - bool insert_column(size_t col_ndx, DataType, StringData name, bool nullable = false); - bool erase_link_column(size_t col_ndx, size_t link_target_table_ndx, size_t backlink_col_ndx); - bool erase_column(size_t col_ndx); - bool rename_column(size_t col_ndx, StringData new_name); - bool add_search_index(size_t col_ndx); - bool remove_search_index(size_t col_ndx); - bool set_link_type(size_t col_ndx, LinkType); - - // Must have linklist selected: - bool link_list_set(size_t link_ndx, size_t value, size_t prior_size); - bool link_list_set_all(const IntegerColumn& values); - bool link_list_insert(size_t link_ndx, size_t value, size_t prior_size); - bool link_list_move(size_t from_link_ndx, size_t to_link_ndx); - bool link_list_swap(size_t link1_ndx, size_t link2_ndx); - bool link_list_erase(size_t link_ndx, size_t prior_size); - bool link_list_nullify(size_t link_ndx, size_t prior_size); - bool link_list_clear(size_t old_list_size); - - /// End of methods expected by parser. - - - TransactLogEncoder(TransactLogStream& out_stream); - void set_buffer(char* new_free_begin, char* new_free_end); - char* write_position() const - { - return m_transact_log_free_begin; - } - -private: - using IntegerList = std::tuple; - using UnsignedList = std::tuple; - - // Make sure this is in agreement with the actual integer encoding - // scheme (see encode_int()). - static constexpr int max_enc_bytes_per_int = 10; - static constexpr int max_enc_bytes_per_double = sizeof(double); - static constexpr int max_enc_bytes_per_num = - max_enc_bytes_per_int < max_enc_bytes_per_double ? max_enc_bytes_per_double : max_enc_bytes_per_int; -// Space is reserved in chunks to avoid excessive over allocation. -#ifdef REALM_DEBUG - static constexpr int max_numbers_per_chunk = 2; // Increase the chance of chunking in debug mode -#else - static constexpr int max_numbers_per_chunk = 8; -#endif - - // This value is used in Set* instructions in place of the 'type' field in - // the stream to indicate that the value of the Set* instruction is NULL, - // which doesn't have a type. - static constexpr int set_null_sentinel() - { - return -1; - } - - TransactLogStream& m_stream; - - // These two delimit a contiguous region of free space in a - // transaction log buffer following the last written data. It may - // be empty. - char* m_transact_log_free_begin = nullptr; - char* m_transact_log_free_end = nullptr; - - char* reserve(size_t size); - /// \param ptr Must be in the range [m_transact_log_free_begin, m_transact_log_free_end] - void advance(char* ptr) noexcept; - - template - size_t max_size(T); - - size_t max_size_list() - { - return 0; - } - - template - size_t max_size_list(T val, Args... args) - { - return max_size(val) + max_size_list(args...); - } - - template - char* encode(char* ptr, T value); - - char* encode_list(char* ptr) - { - advance(ptr); - return ptr; - } - - template - char* encode_list(char* ptr, T value, Args... args) - { - return encode_list(encode(ptr, value), args...); - } - - template - void append_simple_instr(L... numbers); - - template - void append_mixed_instr(Instruction instr, const Mixed& value, L... numbers); - - template - static char* encode_int(char*, T value); - friend class TransactLogParser; -}; - -class TransactLogConvenientEncoder { -public: - virtual void insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name); - virtual void erase_group_level_table(size_t table_ndx, size_t num_tables); - virtual void rename_group_level_table(size_t table_ndx, StringData new_name); - virtual void insert_column(const Descriptor&, size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link, - bool nullable = false); - virtual void erase_column(const Descriptor&, size_t col_ndx); - virtual void rename_column(const Descriptor&, size_t col_ndx, StringData name); - - virtual void set_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value, Instruction variant = instr_Set); - virtual void add_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value); - virtual void set_bool(const Table*, size_t col_ndx, size_t ndx, bool value, Instruction variant = instr_Set); - virtual void set_float(const Table*, size_t col_ndx, size_t ndx, float value, Instruction variant = instr_Set); - virtual void set_double(const Table*, size_t col_ndx, size_t ndx, double value, Instruction variant = instr_Set); - virtual void set_string(const Table*, size_t col_ndx, size_t ndx, StringData value, Instruction variant = instr_Set); - virtual void set_binary(const Table*, size_t col_ndx, size_t ndx, BinaryData value, Instruction variant = instr_Set); - virtual void set_olddatetime(const Table*, size_t col_ndx, size_t ndx, OldDateTime value, - Instruction variant = instr_Set); - virtual void set_timestamp(const Table*, size_t col_ndx, size_t ndx, Timestamp value, Instruction variant = instr_Set); - virtual void set_table(const Table*, size_t col_ndx, size_t ndx, Instruction variant = instr_Set); - virtual void set_mixed(const Table*, size_t col_ndx, size_t ndx, const Mixed& value, Instruction variant = instr_Set); - virtual void set_link(const Table*, size_t col_ndx, size_t ndx, size_t value, Instruction variant = instr_Set); - virtual void set_null(const Table*, size_t col_ndx, size_t ndx, Instruction variant = instr_Set); - virtual void set_link_list(const LinkView&, const IntegerColumn& values); - virtual void insert_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, StringData); - virtual void erase_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, size_t size); - - /// \param prior_num_rows The number of rows in the table prior to the - /// modification. - virtual void insert_empty_rows(const Table*, size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows); - virtual void add_row_with_key(const Table* t, size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, - int64_t key); - - /// \param prior_num_rows The number of rows in the table prior to the - /// modification. - virtual void erase_rows(const Table*, size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, - bool is_move_last_over); - - virtual void swap_rows(const Table*, size_t row_ndx_1, size_t row_ndx_2); - virtual void move_row(const Table*, size_t from_ndx, size_t to_ndx); - virtual void merge_rows(const Table*, size_t row_ndx, size_t new_row_ndx); - virtual void add_search_index(const Descriptor&, size_t col_ndx); - virtual void remove_search_index(const Descriptor&, size_t col_ndx); - virtual void set_link_type(const Table*, size_t col_ndx, LinkType); - virtual void clear_table(const Table*, size_t prior_num_rows); - virtual void optimize_table(const Table*); - - virtual void link_list_set(const LinkView&, size_t link_ndx, size_t value); - virtual void link_list_insert(const LinkView&, size_t link_ndx, size_t value); - virtual void link_list_move(const LinkView&, size_t from_link_ndx, size_t to_link_ndx); - virtual void link_list_swap(const LinkView&, size_t link_ndx_1, size_t link_ndx_2); - virtual void link_list_erase(const LinkView&, size_t link_ndx); - virtual void link_list_clear(const LinkView&); - - //@{ - - /// Implicit nullifications due to removal of target row. This is redundant - /// information from the point of view of replication, as the removal of the - /// target row will reproduce the implicit nullifications in the target - /// Realm anyway. The purpose of this instruction is to allow observers - /// (reactor pattern) to be explicitly notified about the implicit - /// nullifications. - - virtual void nullify_link(const Table*, size_t col_ndx, size_t ndx); - virtual void link_list_nullify(const LinkView&, size_t link_ndx); - - //@} - - void on_table_destroyed(const Table*) noexcept; - void on_spec_destroyed(const Spec*) noexcept; - void on_link_list_destroyed(const LinkView&) noexcept; - -protected: - TransactLogConvenientEncoder(TransactLogStream& encoder); - - void reset_selection_caches() noexcept; - void set_buffer(char* new_free_begin, char* new_free_end) - { - m_encoder.set_buffer(new_free_begin, new_free_end); - } - char* write_position() const - { - return m_encoder.write_position(); - } - -private: - TransactLogEncoder m_encoder; - // These are mutable because they are caches. - mutable util::Buffer m_subtab_path_buf; - mutable const Table* m_selected_table; - mutable const Spec* m_selected_spec; - // Has to be atomic to support concurrent reset when a linklist - // is unselected. This can happen on a different thread. In case - // of races, setting of a new value must win. - mutable std::atomic m_selected_link_list; - - void unselect_all() noexcept; - void select_table(const Table*); // unselects descriptor and link list - void select_desc(const Descriptor&); // unselects link list - void select_link_list(const LinkView&); // unselects descriptor - - void record_subtable_path(const Table&, size_t*& out_begin, size_t*& out_end); - void do_select_table(const Table*); - void do_select_desc(const Descriptor&); - void do_select_link_list(const LinkView&); - - friend class TransactReverser; -}; - - -class TransactLogParser { -public: - class BadTransactLog; // Exception - - TransactLogParser(); - ~TransactLogParser() noexcept; - - /// See `TransactLogEncoder` for a list of methods that the `InstructionHandler` must define. - /// parse() promises that the path passed by reference to - /// InstructionHandler::select_descriptor() will remain valid - /// during subsequent calls to all descriptor modifying functions. - template - void parse(InputStream&, InstructionHandler&); - - template - void parse(NoCopyInputStream&, InstructionHandler&); - -private: - util::Buffer m_input_buffer; - - // The input stream is assumed to consist of chunks of memory organised such that - // every instruction resides in a single chunk only. - NoCopyInputStream* m_input; - // pointer into transaction log, each instruction is parsed from m_input_begin and onwards. - // Each instruction are assumed to be contiguous in memory. - const char* m_input_begin; - // pointer to one past current instruction log chunk. If m_input_begin reaches m_input_end, - // a call to next_input_buffer will move m_input_begin and m_input_end to a new chunk of - // memory. Setting m_input_end to 0 disables this check, and is used if it is already known - // that all of the instructions are in memory. - const char* m_input_end; - util::StringBuffer m_string_buffer; - static const int m_max_levels = 1024; - util::Buffer m_path; - - REALM_NORETURN void parser_error() const; - - template - void parse_one(InstructionHandler&); - bool has_next() noexcept; - - template - T read_int(); - - void read_bytes(char* data, size_t size); - BinaryData read_buffer(util::StringBuffer&, size_t size); - - bool read_bool(); - float read_float(); - double read_double(); - - StringData read_string(util::StringBuffer&); - BinaryData read_binary(util::StringBuffer&); - Timestamp read_timestamp(); - void read_mixed(Mixed*); - - // Advance m_input_begin and m_input_end to reflect the next block of instructions - // Returns false if no more input was available - bool next_input_buffer(); - - // return true if input was available - bool read_char(char&); // throws - - bool is_valid_data_type(int type); - bool is_valid_link_type(int type); -}; - - -class TransactLogParser::BadTransactLog : public std::exception { -public: - const char* what() const noexcept override - { - return "Bad transaction log"; - } -}; - - -/// Implementation: - -inline void TransactLogBufferStream::transact_log_reserve(size_t n, char** inout_new_begin, char** out_new_end) -{ - char* data = m_buffer.data(); - REALM_ASSERT(*inout_new_begin >= data); - REALM_ASSERT(*inout_new_begin <= (data + m_buffer.size())); - size_t size = *inout_new_begin - data; - m_buffer.reserve_extra(size, n); - data = m_buffer.data(); // May have changed - *inout_new_begin = data + size; - *out_new_end = data + m_buffer.size(); -} - -inline void TransactLogBufferStream::transact_log_append(const char* data, size_t size, char** out_new_begin, - char** out_new_end) -{ - transact_log_reserve(size, out_new_begin, out_new_end); - *out_new_begin = realm::safe_copy_n(data, size, *out_new_begin); -} - -inline const char* TransactLogBufferStream::transact_log_data() const -{ - return m_buffer.data(); -} - -inline TransactLogEncoder::TransactLogEncoder(TransactLogStream& stream) - : m_stream(stream) -{ -} - -inline void TransactLogEncoder::set_buffer(char* free_begin, char* free_end) -{ - REALM_ASSERT(free_begin <= free_end); - m_transact_log_free_begin = free_begin; - m_transact_log_free_end = free_end; -} - -inline void TransactLogConvenientEncoder::reset_selection_caches() noexcept -{ - unselect_all(); -} - -inline char* TransactLogEncoder::reserve(size_t n) -{ - if (size_t(m_transact_log_free_end - m_transact_log_free_begin) < n) { - m_stream.transact_log_reserve(n, &m_transact_log_free_begin, &m_transact_log_free_end); - } - return m_transact_log_free_begin; -} - -inline void TransactLogEncoder::advance(char* ptr) noexcept -{ - REALM_ASSERT_DEBUG(m_transact_log_free_begin <= ptr); - REALM_ASSERT_DEBUG(ptr <= m_transact_log_free_end); - m_transact_log_free_begin = ptr; -} - - -// The integer encoding is platform independent. Also, it does not -// depend on the type of the specified integer. Integers of any type -// can be encoded as long as the specified buffer is large enough (see -// below). The decoding does not have to use the same type. Decoding -// will fail if, and only if the encoded value falls outside the range -// of the requested destination type. -// -// The encoding uses one or more bytes. It never uses more than 8 bits -// per byte. The last byte in the sequence is the first one that has -// its 8th bit set to zero. -// -// Consider a particular non-negative value V. Let W be the number of -// bits needed to encode V using the trivial binary encoding of -// integers. The total number of bytes produced is then -// ceil((W+1)/7). The first byte holds the 7 least significant bits of -// V. The last byte holds at most 6 bits of V including the most -// significant one. The value of the first bit of the last byte is -// always 2**((N-1)*7) where N is the total number of bytes. -// -// A negative value W is encoded by setting the sign bit to one and -// then encoding the positive result of -(W+1) as described above. The -// advantage of this representation is that it converts small negative -// values to small positive values which require a small number of -// bytes. This would not have been true for 2's complements -// representation, for example. The sign bit is always stored as the -// 7th bit of the last byte. -// -// value bits value + sign max bytes -// -------------------------------------------------- -// int8_t 7 8 2 -// uint8_t 8 9 2 -// int16_t 15 16 3 -// uint16_t 16 17 3 -// int32_t 31 32 5 -// uint32_t 32 33 5 -// int64_t 63 64 10 -// uint64_t 64 65 10 -// -template -char* TransactLogEncoder::encode_int(char* ptr, T value) -{ - static_assert(std::numeric_limits::is_integer, "Integer required"); - bool negative = util::is_negative(value); - if (negative) { - // The following conversion is guaranteed by C++11 to never - // overflow (contrast this with "-value" which indeed could - // overflow). See C99+TC3 section 6.2.6.2 paragraph 2. - REALM_DIAG_PUSH(); - REALM_DIAG_IGNORE_UNSIGNED_MINUS(); - value = -(value + 1); - REALM_DIAG_POP(); - } - // At this point 'value' is always a positive number. Also, small - // negative numbers have been converted to small positive numbers. - REALM_ASSERT(!util::is_negative(value)); - // One sign bit plus number of value bits - const int num_bits = 1 + std::numeric_limits::digits; - // Only the first 7 bits are available per byte. Had it not been - // for the fact that maximum guaranteed bit width of a char is 8, - // this value could have been increased to 15 (one less than the - // number of value bits in 'unsigned'). - const int bits_per_byte = 7; - const int max_bytes = (num_bits + (bits_per_byte - 1)) / bits_per_byte; - static_assert(max_bytes <= max_enc_bytes_per_int, "Bad max_enc_bytes_per_int"); - // An explicit constant maximum number of iterations is specified - // in the hope that it will help the optimizer (to do loop - // unrolling, for example). - typedef unsigned char uchar; - for (int i = 0; i < max_bytes; ++i) { - if (value >> (bits_per_byte - 1) == 0) - break; - *reinterpret_cast(ptr) = uchar((1U << bits_per_byte) | unsigned(value & ((1U << bits_per_byte) - 1))); - ++ptr; - value >>= bits_per_byte; - } - *reinterpret_cast(ptr) = uchar(negative ? (1U << (bits_per_byte - 1)) | unsigned(value) : value); - return ++ptr; -} - -template -char* TransactLogEncoder::encode(char* ptr, T value) -{ - auto value_2 = value + 0; // Perform integral promotion - return encode_int(ptr, value_2); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, char value) -{ - // Write the char as-is without encoding. - *ptr++ = value; - return ptr; -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, Instruction inst) -{ - return encode(ptr, inst); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, bool value) -{ - return encode(ptr, value); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, float value) -{ - static_assert(std::numeric_limits::is_iec559 && - sizeof(float) * std::numeric_limits::digits == 32, - "Unsupported 'float' representation"); - const char* val_ptr = reinterpret_cast(&value); - return realm::safe_copy_n(val_ptr, sizeof value, ptr); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, double value) -{ - static_assert(std::numeric_limits::is_iec559 && - sizeof(double) * std::numeric_limits::digits == 64, - "Unsupported 'double' representation"); - const char* val_ptr = reinterpret_cast(&value); - return realm::safe_copy_n(val_ptr, sizeof value, ptr); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, DataType type) -{ - return encode(ptr, type); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, StringData s) -{ - ptr = encode_int(ptr, s.size()); - return std::copy_n(s.data(), s.size(), ptr); -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, - TransactLogEncoder::IntegerList list) -{ - IntegerColumnIterator i = std::get<0>(list); - IntegerColumnIterator end = std::get<1>(list); - - while (end - i > max_numbers_per_chunk) { - for (int j = 0; j < max_numbers_per_chunk; ++j) - ptr = encode_int(ptr, *i++); - advance(ptr); - size_t max_required_bytes_2 = max_enc_bytes_per_num * max_numbers_per_chunk; - ptr = reserve(max_required_bytes_2); // Throws - } - - while (i != end) - ptr = encode_int(ptr, *i++); - - return ptr; -} - -template <> -inline char* TransactLogEncoder::encode(char* ptr, - TransactLogEncoder::UnsignedList list) -{ - const size_t* i = std::get<0>(list); - const size_t* end = std::get<1>(list); - - while (i != end) - ptr = encode_int(ptr, *i++); - - return ptr; -} - -template -size_t TransactLogEncoder::max_size(T) -{ - return max_enc_bytes_per_num; -} - -template <> -inline size_t TransactLogEncoder::max_size(char) -{ - return 1; -} - -template <> -inline size_t TransactLogEncoder::max_size(bool) -{ - return 1; -} - -template <> -inline size_t TransactLogEncoder::max_size(Instruction) -{ - return 1; -} - -template <> -inline size_t TransactLogEncoder::max_size(DataType) -{ - return 1; -} - -template <> -inline size_t TransactLogEncoder::max_size(StringData s) -{ - return max_enc_bytes_per_num + s.size(); -} - -template <> -inline size_t TransactLogEncoder::max_size(IntegerList) -{ - // We only allocate space for 'max_numbers_per_chunk' at a time - return max_enc_bytes_per_num * max_numbers_per_chunk; -} - -template <> -inline size_t TransactLogEncoder::max_size(UnsignedList list) -{ - const size_t* begin = std::get<0>(list); - const size_t* end = std::get<1>(list); - // list contains (end - begin) elements - return max_enc_bytes_per_num * (end - begin); -} - -template -void TransactLogEncoder::append_simple_instr(L... numbers) -{ - size_t max_required_bytes = max_size_list(numbers...); - char* ptr = reserve(max_required_bytes); // Throws - encode_list(ptr, numbers...); -} - -template -void TransactLogEncoder::append_mixed_instr(Instruction instr, const Mixed& value, L... numbers) -{ - DataType type = value.get_type(); - switch (type) { - case type_Int: - append_simple_instr(instr, numbers..., type, value.get_int()); // Throws - return; - case type_Bool: - append_simple_instr(instr, numbers..., type, value.get_bool()); // Throws - return; - case type_Float: - append_simple_instr(instr, numbers..., type, value.get_float()); // Throws - return; - case type_Double: - append_simple_instr(instr, numbers..., type, value.get_double()); // Throws - return; - case type_OldDateTime: { - auto value_2 = value.get_olddatetime().get_olddatetime(); - append_simple_instr(instr, numbers..., type, value_2); // Throws - return; - } - case type_String: { - append_simple_instr(instr, numbers..., type, value.get_string()); // Throws - return; - } - case type_Binary: { - BinaryData value_2 = value.get_binary(); - StringData value_3(value_2.data(), value_2.size()); - append_simple_instr(instr, numbers..., type, value_3); // Throws - return; - } - case type_Timestamp: { - Timestamp ts = value.get_timestamp(); - int64_t seconds = ts.get_seconds(); - int32_t nano_seconds = ts.get_nanoseconds(); - append_simple_instr(instr, numbers..., type, seconds, nano_seconds); // Throws - return; - } - case type_Table: - append_simple_instr(instr, numbers..., type); // Throws - return; - case type_Mixed: - // Mixed in mixed is not possible - REALM_TERMINATE("Mixed in Mixed not possible"); - case type_Link: - case type_LinkList: - // FIXME: Need to handle new link types here. - REALM_TERMINATE("Link types in Mixed not supported."); - } - REALM_TERMINATE("Invalid Mixed."); -} - -inline void TransactLogConvenientEncoder::unselect_all() noexcept -{ - m_selected_table = nullptr; - m_selected_spec = nullptr; - // no race with on_link_list_destroyed since both are setting to nullptr - m_selected_link_list = nullptr; -} - -inline void TransactLogConvenientEncoder::select_table(const Table* table) -{ - if (table != m_selected_table) - do_select_table(table); // Throws - m_selected_spec = nullptr; - // no race with on_link_list_destroyed since both are setting to nullptr - m_selected_link_list = nullptr; -} - -inline void TransactLogConvenientEncoder::select_desc(const Descriptor& desc) -{ - typedef _impl::DescriptorFriend df; - if (&df::get_spec(desc) != m_selected_spec) - do_select_desc(desc); // Throws - // no race with on_link_list_destroyed since both are setting to nullptr - m_selected_link_list = nullptr; -} - -inline void TransactLogConvenientEncoder::select_link_list(const LinkView& list) -{ - // A race between this and a call to on_link_list_destroyed() must - // end up with m_selected_link_list pointing to the list argument given - // here. We assume that the list given to on_link_list_destroyed() can - // *never* be the same as the list argument given here. We resolve the - // race by a) always updating m_selected_link_list in do_select_link_list() - // and b) only atomically and conditionally updating it in - // on_link_list_destroyed(). - if (&list != m_selected_link_list) { - do_select_link_list(list); // Throws - } - m_selected_spec = nullptr; -} - - -inline bool TransactLogEncoder::insert_group_level_table(size_t table_ndx, size_t prior_num_tables, StringData name) -{ - append_simple_instr(instr_InsertGroupLevelTable, table_ndx, prior_num_tables, name); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::insert_group_level_table(size_t table_ndx, size_t prior_num_tables, - StringData name) -{ - unselect_all(); - m_encoder.insert_group_level_table(table_ndx, prior_num_tables, name); // Throws -} - -inline bool TransactLogEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables) -{ - append_simple_instr(instr_EraseGroupLevelTable, table_ndx, prior_num_tables); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::erase_group_level_table(size_t table_ndx, size_t prior_num_tables) -{ - unselect_all(); - m_encoder.erase_group_level_table(table_ndx, prior_num_tables); // Throws -} - -inline bool TransactLogEncoder::rename_group_level_table(size_t table_ndx, StringData new_name) -{ - append_simple_instr(instr_RenameGroupLevelTable, table_ndx, new_name); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::rename_group_level_table(size_t table_ndx, StringData new_name) -{ - unselect_all(); - m_encoder.rename_group_level_table(table_ndx, new_name); // Throws -} - -inline bool TransactLogEncoder::insert_column(size_t col_ndx, DataType type, StringData name, bool nullable) -{ - Instruction instr = (nullable ? instr_InsertNullableColumn : instr_InsertColumn); - append_simple_instr(instr, col_ndx, type, name); // Throws - return true; -} - -inline bool TransactLogEncoder::insert_link_column(size_t col_ndx, DataType type, StringData name, - size_t link_target_table_ndx, size_t backlink_col_ndx) -{ - REALM_ASSERT(_impl::TableFriend::is_link_type(ColumnType(type))); - append_simple_instr(instr_InsertLinkColumn, col_ndx, type, link_target_table_ndx, backlink_col_ndx, - name); // Throws - return true; -} - - -inline void TransactLogConvenientEncoder::insert_column(const Descriptor& desc, size_t col_ndx, DataType type, - StringData name, LinkTargetInfo& link, bool nullable) -{ - select_desc(desc); // Throws - if (link.is_valid()) { - typedef _impl::TableFriend tf; - typedef _impl::DescriptorFriend df; - size_t target_table_ndx = link.m_target_table->get_index_in_group(); - const Table& origin_table = df::get_root_table(desc); - REALM_ASSERT(origin_table.is_group_level()); - const Spec& target_spec = tf::get_spec(*(link.m_target_table)); - size_t origin_table_ndx = origin_table.get_index_in_group(); - size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx); - REALM_ASSERT_3(backlink_col_ndx, ==, link.m_backlink_col_ndx); - m_encoder.insert_link_column(col_ndx, type, name, target_table_ndx, backlink_col_ndx); // Throws - } - else { - m_encoder.insert_column(col_ndx, type, name, nullable); // Throws - } -} - -inline bool TransactLogEncoder::erase_column(size_t col_ndx) -{ - append_simple_instr(instr_EraseColumn, col_ndx); // Throws - return true; -} - -inline bool TransactLogEncoder::erase_link_column(size_t col_ndx, size_t link_target_table_ndx, - size_t backlink_col_ndx) -{ - append_simple_instr(instr_EraseLinkColumn, col_ndx, link_target_table_ndx, backlink_col_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::erase_column(const Descriptor& desc, size_t col_ndx) -{ - select_desc(desc); // Throws - - DataType type = desc.get_column_type(col_ndx); - typedef _impl::TableFriend tf; - if (!tf::is_link_type(ColumnType(type))) { - m_encoder.erase_column(col_ndx); // Throws - } - else { // it's a link column: - REALM_ASSERT(desc.is_root()); - typedef _impl::DescriptorFriend df; - const Table& origin_table = df::get_root_table(desc); - REALM_ASSERT(origin_table.is_group_level()); - const Table& target_table = *tf::get_link_target_table_accessor(origin_table, col_ndx); - size_t target_table_ndx = target_table.get_index_in_group(); - const Spec& target_spec = tf::get_spec(target_table); - size_t origin_table_ndx = origin_table.get_index_in_group(); - size_t backlink_col_ndx = target_spec.find_backlink_column(origin_table_ndx, col_ndx); - m_encoder.erase_link_column(col_ndx, target_table_ndx, backlink_col_ndx); // Throws - } -} - -inline bool TransactLogEncoder::rename_column(size_t col_ndx, StringData new_name) -{ - append_simple_instr(instr_RenameColumn, col_ndx, new_name); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::rename_column(const Descriptor& desc, size_t col_ndx, StringData name) -{ - select_desc(desc); // Throws - m_encoder.rename_column(col_ndx, name); // Throws -} - - -inline bool TransactLogEncoder::set_int(size_t col_ndx, size_t ndx, int_fast64_t value, Instruction variant, - size_t prior_num_rows) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); - if (REALM_UNLIKELY(variant == instr_SetUnique)) - append_simple_instr(variant, type_Int, col_ndx, ndx, prior_num_rows, value); // Throws - else - append_simple_instr(variant, type_Int, col_ndx, ndx, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_int(const Table* t, size_t col_ndx, size_t ndx, int_fast64_t value, - Instruction variant) -{ - select_table(t); // Throws - size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); - m_encoder.set_int(col_ndx, ndx, value, variant, prior_num_rows); // Throws -} - - -inline bool TransactLogEncoder::add_int(size_t col_ndx, size_t ndx, int_fast64_t value) -{ - append_simple_instr(instr_AddInteger, col_ndx, ndx, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::add_int(const Table* t, size_t col_ndx, size_t ndx, int_fast64_t value) -{ - select_table(t); // Throws - m_encoder.add_int(col_ndx, ndx, value); -} - -inline bool TransactLogEncoder::set_bool(size_t col_ndx, size_t ndx, bool value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(variant, type_Bool, col_ndx, ndx, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_bool(const Table* t, size_t col_ndx, size_t ndx, bool value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_bool(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_float(size_t col_ndx, size_t ndx, float value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(variant, type_Float, col_ndx, ndx, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_float(const Table* t, size_t col_ndx, size_t ndx, float value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_float(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_double(size_t col_ndx, size_t ndx, double value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(instr_Set, type_Double, col_ndx, ndx, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_double(const Table* t, size_t col_ndx, size_t ndx, double value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_double(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_string(size_t col_ndx, size_t ndx, StringData value, Instruction variant, - size_t prior_num_rows) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); - if (value.is_null()) { - set_null(col_ndx, ndx, variant, prior_num_rows); // Throws - } - else { - if (REALM_UNLIKELY(variant == instr_SetUnique)) - append_simple_instr(variant, type_String, col_ndx, ndx, prior_num_rows, value); // Throws - else - append_simple_instr(variant, type_String, col_ndx, ndx, value); // Throws - } - return true; -} - -inline void TransactLogConvenientEncoder::set_string(const Table* t, size_t col_ndx, size_t ndx, StringData value, - Instruction variant) -{ - select_table(t); // Throws - size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); - m_encoder.set_string(col_ndx, ndx, value, variant, prior_num_rows); // Throws -} - -inline bool TransactLogEncoder::set_binary(size_t col_ndx, size_t row_ndx, BinaryData value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - if (value.is_null()) { - set_null(col_ndx, row_ndx, variant); // Throws - } - else { - StringData value_2(value.data(), value.size()); - append_simple_instr(variant, type_Binary, col_ndx, row_ndx, value_2); // Throws - } - return true; -} - -inline void TransactLogConvenientEncoder::set_binary(const Table* t, size_t col_ndx, size_t ndx, BinaryData value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_binary(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_olddatetime(size_t col_ndx, size_t ndx, OldDateTime value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(variant, type_OldDateTime, col_ndx, ndx, value.get_olddatetime()); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_olddatetime(const Table* t, size_t col_ndx, size_t ndx, - OldDateTime value, Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_olddatetime(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_timestamp(size_t col_ndx, size_t ndx, Timestamp value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(variant, type_Timestamp, col_ndx, ndx, value.get_seconds(), - value.get_nanoseconds()); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_timestamp(const Table* t, size_t col_ndx, size_t ndx, Timestamp value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_timestamp(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_table(size_t col_ndx, size_t ndx, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_simple_instr(variant, type_Table, col_ndx, ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_table(const Table* t, size_t col_ndx, size_t ndx, Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_table(col_ndx, ndx, variant); // Throws -} - -inline bool TransactLogEncoder::set_mixed(size_t col_ndx, size_t ndx, const Mixed& value, Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - append_mixed_instr(variant, value, type_Mixed, col_ndx, ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_mixed(const Table* t, size_t col_ndx, size_t ndx, const Mixed& value, - Instruction variant) -{ - select_table(t); // Throws - m_encoder.set_mixed(col_ndx, ndx, value, variant); // Throws -} - -inline bool TransactLogEncoder::set_link(size_t col_ndx, size_t ndx, size_t value, size_t target_group_level_ndx, - Instruction variant) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault, variant); - // Map `realm::npos` to zero, and `n` to `n+1`, where `n` is a target row - // index. - size_t value_2 = size_t(1) + value; - append_simple_instr(variant, type_Link, col_ndx, ndx, value_2, target_group_level_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_link(const Table* t, size_t col_ndx, size_t ndx, size_t value, - Instruction variant) -{ - select_table(t); // Throws - size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx); - m_encoder.set_link(col_ndx, ndx, value, target_group_level_ndx, variant); // Throws -} - -inline bool TransactLogEncoder::set_null(size_t col_ndx, size_t ndx, Instruction variant, size_t prior_num_rows) -{ - REALM_ASSERT_EX(variant == instr_Set || variant == instr_SetDefault || variant == instr_SetUnique, variant); - if (REALM_UNLIKELY(variant == instr_SetUnique)) { - append_simple_instr(variant, set_null_sentinel(), col_ndx, ndx, prior_num_rows); // Throws - } - else { - append_simple_instr(variant, set_null_sentinel(), col_ndx, ndx); // Throws - } - return true; -} - -inline void TransactLogConvenientEncoder::set_null(const Table* t, size_t col_ndx, size_t row_ndx, - Instruction variant) -{ - select_table(t); // Throws - size_t prior_num_rows = (variant == instr_SetUnique ? t->size() : 0); - m_encoder.set_null(col_ndx, row_ndx, variant, prior_num_rows); // Throws -} - -inline bool TransactLogEncoder::nullify_link(size_t col_ndx, size_t ndx, size_t target_group_level_ndx) -{ - append_simple_instr(instr_NullifyLink, col_ndx, ndx, target_group_level_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::nullify_link(const Table* t, size_t col_ndx, size_t ndx) -{ - select_table(t); // Throws - size_t target_group_level_ndx = t->get_descriptor()->get_column_link_target(col_ndx); - m_encoder.nullify_link(col_ndx, ndx, target_group_level_ndx); // Throws -} - -inline bool TransactLogEncoder::insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData value) -{ - append_simple_instr(instr_InsertSubstring, col_ndx, row_ndx, pos, value); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::insert_substring(const Table* t, size_t col_ndx, size_t row_ndx, size_t pos, - StringData value) -{ - if (value.size() > 0) { - select_table(t); // Throws - m_encoder.insert_substring(col_ndx, row_ndx, pos, value); // Throws - } -} - -inline bool TransactLogEncoder::erase_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t size) -{ - append_simple_instr(instr_EraseFromString, col_ndx, row_ndx, pos, size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::erase_substring(const Table* t, size_t col_ndx, size_t row_ndx, size_t pos, - size_t size) -{ - if (size > 0) { - select_table(t); // Throws - m_encoder.erase_substring(col_ndx, row_ndx, pos, size); // Throws - } -} - -inline bool TransactLogEncoder::insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, - bool unordered) -{ - append_simple_instr(instr_InsertEmptyRows, row_ndx, num_rows_to_insert, prior_num_rows, unordered); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::insert_empty_rows(const Table* t, size_t row_ndx, size_t num_rows_to_insert, - size_t prior_num_rows) -{ - select_table(t); // Throws - bool unordered = false; - m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows, unordered); // Throws -} - -inline bool TransactLogEncoder::add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, - int64_t key) -{ - append_simple_instr(instr_AddRowWithKey, row_ndx, prior_num_rows, key_col_ndx, key); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::add_row_with_key(const Table* t, size_t row_ndx, size_t prior_num_rows, - size_t key_col_ndx, int64_t key) -{ - select_table(t); // Throws - m_encoder.add_row_with_key(row_ndx, prior_num_rows, key_col_ndx, key); // Throws -} - -inline bool TransactLogEncoder::erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, - bool unordered) -{ - append_simple_instr(instr_EraseRows, row_ndx, num_rows_to_erase, prior_num_rows, unordered); // Throws - return true; -} - - -inline void TransactLogConvenientEncoder::erase_rows(const Table* t, size_t row_ndx, size_t num_rows_to_erase, - size_t prior_num_rows, bool is_move_last_over) -{ - select_table(t); // Throws - bool unordered = is_move_last_over; - m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, unordered); // Throws -} - -inline bool TransactLogEncoder::swap_rows(size_t row_ndx_1, size_t row_ndx_2) -{ - append_simple_instr(instr_SwapRows, row_ndx_1, row_ndx_2); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::swap_rows(const Table* t, size_t row_ndx_1, size_t row_ndx_2) -{ - REALM_ASSERT(row_ndx_1 < row_ndx_2); - select_table(t); // Throws - m_encoder.swap_rows(row_ndx_1, row_ndx_2); -} - -inline bool TransactLogEncoder::move_row(size_t from_ndx, size_t to_ndx) -{ - append_simple_instr(instr_MoveRow, from_ndx, to_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::move_row(const Table* t, size_t from_ndx, size_t to_ndx) -{ - REALM_ASSERT(from_ndx != to_ndx); - select_table(t); // Throws - m_encoder.move_row(from_ndx, to_ndx); -} - -inline bool TransactLogEncoder::merge_rows(size_t row_ndx, size_t new_row_ndx) -{ - append_simple_instr(instr_MergeRows, row_ndx, new_row_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::merge_rows(const Table* t, size_t row_ndx, size_t new_row_ndx) -{ - select_table(t); // Throws - m_encoder.merge_rows(row_ndx, new_row_ndx); -} - -inline bool TransactLogEncoder::add_search_index(size_t col_ndx) -{ - append_simple_instr(instr_AddSearchIndex, col_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::add_search_index(const Descriptor& desc, size_t col_ndx) -{ - select_desc(desc); // Throws - m_encoder.add_search_index(col_ndx); // Throws -} - - -inline bool TransactLogEncoder::remove_search_index(size_t col_ndx) -{ - append_simple_instr(instr_RemoveSearchIndex, col_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::remove_search_index(const Descriptor& desc, size_t col_ndx) -{ - select_desc(desc); // Throws - m_encoder.remove_search_index(col_ndx); // Throws -} - -inline bool TransactLogEncoder::set_link_type(size_t col_ndx, LinkType link_type) -{ - append_simple_instr(instr_SetLinkType, col_ndx, int(link_type)); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_link_type(const Table* t, size_t col_ndx, LinkType link_type) -{ - select_table(t); // Throws - m_encoder.set_link_type(col_ndx, link_type); // Throws -} - - -inline bool TransactLogEncoder::clear_table(size_t old_size) -{ - append_simple_instr(instr_ClearTable, old_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::clear_table(const Table* t, size_t prior_num_rows) -{ - select_table(t); // Throws - m_encoder.clear_table(prior_num_rows); // Throws -} - -inline bool TransactLogEncoder::optimize_table() -{ - append_simple_instr(instr_OptimizeTable); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::optimize_table(const Table* t) -{ - select_table(t); // Throws - m_encoder.optimize_table(); // Throws -} - -inline bool TransactLogEncoder::link_list_set(size_t link_ndx, size_t value, size_t prior_size) -{ - append_simple_instr(instr_LinkListSet, link_ndx, value, prior_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_set(const LinkView& list, size_t link_ndx, size_t value) -{ - select_link_list(list); // Throws - m_encoder.link_list_set(link_ndx, value, list.size()); // Throws -} - -inline bool TransactLogEncoder::link_list_nullify(size_t link_ndx, size_t prior_size) -{ - append_simple_instr(instr_LinkListNullify, link_ndx, prior_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_nullify(const LinkView& list, size_t link_ndx) -{ - select_link_list(list); // Throws - size_t prior_size = list.size(); // Instruction is emitted before the fact. - m_encoder.link_list_nullify(link_ndx, prior_size); // Throws -} - -inline bool TransactLogEncoder::link_list_set_all(const IntegerColumn& values) -{ - size_t num_values = values.size(); - append_simple_instr( - instr_LinkListSetAll, num_values, - std::make_tuple(IntegerColumnIterator(&values, 0), IntegerColumnIterator(&values, num_values))); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::set_link_list(const LinkView& list, const IntegerColumn& values) -{ - select_link_list(list); // Throws - m_encoder.link_list_set_all(values); // Throws -} - -inline bool TransactLogEncoder::link_list_insert(size_t link_ndx, size_t value, size_t prior_size) -{ - append_simple_instr(instr_LinkListInsert, link_ndx, value, prior_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_insert(const LinkView& list, size_t link_ndx, size_t value) -{ - select_link_list(list); // Throws - size_t prior_size = list.size() - 1; // The instruction is emitted after the fact. - m_encoder.link_list_insert(link_ndx, value, prior_size); // Throws -} - -inline bool TransactLogEncoder::link_list_move(size_t from_link_ndx, size_t to_link_ndx) -{ - REALM_ASSERT(from_link_ndx != to_link_ndx); - append_simple_instr(instr_LinkListMove, from_link_ndx, to_link_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_move(const LinkView& list, size_t from_link_ndx, - size_t to_link_ndx) -{ - select_link_list(list); // Throws - m_encoder.link_list_move(from_link_ndx, to_link_ndx); // Throws -} - -inline bool TransactLogEncoder::link_list_swap(size_t link1_ndx, size_t link2_ndx) -{ - append_simple_instr(instr_LinkListSwap, link1_ndx, link2_ndx); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_swap(const LinkView& list, size_t link1_ndx, size_t link2_ndx) -{ - select_link_list(list); // Throws - m_encoder.link_list_swap(link1_ndx, link2_ndx); // Throws -} - -inline bool TransactLogEncoder::link_list_erase(size_t link_ndx, size_t prior_size) -{ - append_simple_instr(instr_LinkListErase, link_ndx, prior_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::link_list_erase(const LinkView& list, size_t link_ndx) -{ - select_link_list(list); // Throws - size_t prior_size = list.size(); // The instruction is emitted before the fact. - m_encoder.link_list_erase(link_ndx, prior_size); // Throws -} - -inline bool TransactLogEncoder::link_list_clear(size_t old_list_size) -{ - append_simple_instr(instr_LinkListClear, old_list_size); // Throws - return true; -} - -inline void TransactLogConvenientEncoder::on_table_destroyed(const Table* t) noexcept -{ - if (m_selected_table == t) - m_selected_table = nullptr; -} - -inline void TransactLogConvenientEncoder::on_spec_destroyed(const Spec* s) noexcept -{ - if (m_selected_spec == s) - m_selected_spec = nullptr; -} - - -inline void TransactLogConvenientEncoder::on_link_list_destroyed(const LinkView& list) noexcept -{ - const LinkView* lw_ptr = &list; - // atomically clear m_selected_link_list iff it already points to 'list': - // (lw_ptr will be modified if the swap fails, but we ignore that) - m_selected_link_list.compare_exchange_strong(lw_ptr, nullptr, std::memory_order_relaxed, - std::memory_order_relaxed); -} - - -inline TransactLogParser::TransactLogParser() - : m_input_buffer(1024) // Throws -{ -} - - -inline TransactLogParser::~TransactLogParser() noexcept -{ -} - - -template -void TransactLogParser::parse(NoCopyInputStream& in, InstructionHandler& handler) -{ - m_input = ∈ - m_input_begin = m_input_end = nullptr; - - while (has_next()) - parse_one(handler); // Throws -} - -template -void TransactLogParser::parse(InputStream& in, InstructionHandler& handler) -{ - NoCopyInputStreamAdaptor in_2(in, m_input_buffer.data(), m_input_buffer.size()); - parse(in_2, handler); // Throws -} - -inline bool TransactLogParser::has_next() noexcept -{ - return m_input_begin != m_input_end || next_input_buffer(); -} - -template -void TransactLogParser::parse_one(InstructionHandler& handler) -{ - char instr_ch = 0; - if (!read_char(instr_ch)) - parser_error(); // Throws - // std::cerr << "parsing " << util::promote(instr) << " @ " << std::hex << long(m_input_begin) << std::dec << - // "\n"; - Instruction instr = Instruction(instr_ch); - switch (instr) { - case instr_SetDefault: - case instr_SetUnique: - case instr_Set: { - int type = read_int(); // Throws - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - size_t prior_num_rows = 0; - if (REALM_UNLIKELY(instr == instr_SetUnique)) - prior_num_rows = read_int(); // Throws - - if (type == TransactLogEncoder::set_null_sentinel()) { - // Special case for set_null - if (!handler.set_null(col_ndx, row_ndx, instr, prior_num_rows)) // Throws - parser_error(); - return; - } - - switch (DataType(type)) { - case type_Int: { - int_fast64_t value = read_int(); // Throws - if (!handler.set_int(col_ndx, row_ndx, value, instr, prior_num_rows)) // Throws - parser_error(); - return; - } - case type_Bool: { - bool value = read_bool(); // Throws - if (!handler.set_bool(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_Float: { - float value = read_float(); // Throws - if (!handler.set_float(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_Double: { - double value = read_double(); // Throws - if (!handler.set_double(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_String: { - StringData value = read_string(m_string_buffer); // Throws - if (!handler.set_string(col_ndx, row_ndx, value, instr, prior_num_rows)) // Throws - parser_error(); - return; - } - case type_Binary: { - BinaryData value = read_binary(m_string_buffer); // Throws - if (!handler.set_binary(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_OldDateTime: { - int_fast64_t value = read_int(); // Throws - if (!handler.set_olddatetime(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_Timestamp: { - int64_t seconds = read_int(); // Throws - int32_t nanoseconds = read_int(); // Throws - Timestamp value = Timestamp(seconds, nanoseconds); - if (!handler.set_timestamp(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_Table: { - if (!handler.set_table(col_ndx, row_ndx, instr)) // Throws - parser_error(); - return; - } - case type_Mixed: { - Mixed value; - read_mixed(&value); // Throws - if (!handler.set_mixed(col_ndx, row_ndx, value, instr)) // Throws - parser_error(); - return; - } - case type_Link: { - size_t value = read_int(); // Throws - // Map zero to realm::npos, and `n+1` to `n`, where `n` is a target row index. - size_t target_row_ndx = size_t(value - 1); - size_t target_group_level_ndx = read_int(); // Throws - if (!handler.set_link(col_ndx, row_ndx, target_row_ndx, target_group_level_ndx, instr)) // Throws - parser_error(); - return; - } - case type_LinkList: { - // Unsupported column type for Set. - parser_error(); - return; - } - } - parser_error(); - return; - } - case instr_AddInteger: { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - int_fast64_t value = read_int(); // Throws - if (!handler.add_int(col_ndx, row_ndx, value)) // Throws - parser_error(); - return; - } - case instr_NullifyLink: { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - size_t target_group_level_ndx = read_int(); // Throws - if (!handler.nullify_link(col_ndx, row_ndx, target_group_level_ndx)) // Throws - parser_error(); - return; - } - case instr_InsertSubstring: { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - size_t pos = read_int(); // Throws - StringData value = read_string(m_string_buffer); // Throws - if (!handler.insert_substring(col_ndx, row_ndx, pos, value)) // Throws - parser_error(); - return; - } - case instr_EraseFromString: { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - size_t pos = read_int(); // Throws - size_t size = read_int(); // Throws - if (!handler.erase_substring(col_ndx, row_ndx, pos, size)) // Throws - parser_error(); - return; - } - case instr_InsertEmptyRows: { - size_t row_ndx = read_int(); // Throws - size_t num_rows_to_insert = read_int(); // Throws - size_t prior_num_rows = read_int(); // Throws - bool unordered = read_bool(); // Throws - if (!handler.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows, unordered)) // Throws - parser_error(); - return; - } - case instr_AddRowWithKey: { - size_t row_ndx = read_int(); // Throws - size_t prior_num_rows = read_int(); // Throws - size_t key_col_ndx = read_int(); // Throws - int64_t key = read_int(); // Throws - if (!handler.add_row_with_key(row_ndx, prior_num_rows, key_col_ndx, key)) // Throws - parser_error(); - return; - } - case instr_EraseRows: { - size_t row_ndx = read_int(); // Throws - size_t num_rows_to_erase = read_int(); // Throws - size_t prior_num_rows = read_int(); // Throws - bool unordered = read_bool(); // Throws - if (!handler.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, unordered)) // Throws - parser_error(); - return; - } - case instr_SwapRows: { - size_t row_ndx_1 = read_int(); // Throws - size_t row_ndx_2 = read_int(); // Throws - if (!handler.swap_rows(row_ndx_1, row_ndx_2)) // Throws - parser_error(); - return; - } - case instr_MoveRow: { - size_t from_ndx = read_int(); // Throws - size_t to_ndx = read_int(); // Throws - if (!handler.move_row(from_ndx, to_ndx)) // Throws - parser_error(); - return; - } - case instr_MergeRows: { - size_t row_ndx = read_int(); // Throws - size_t new_row_ndx = read_int(); // Throws - if (!handler.merge_rows(row_ndx, new_row_ndx)) // Throws - parser_error(); - return; - } - case instr_SelectTable: { - int levels = read_int(); // Throws - if (levels < 0 || levels > m_max_levels) - parser_error(); - m_path.reserve(0, 2 * levels); // Throws - size_t* path = m_path.data(); - size_t group_level_ndx = read_int(); // Throws - for (int i = 0; i != levels; ++i) { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - path[2 * i + 0] = col_ndx; - path[2 * i + 1] = row_ndx; - } - if (!handler.select_table(group_level_ndx, levels, path)) // Throws - parser_error(); - return; - } - case instr_ClearTable: { - size_t old_size = read_int(); // Throws - if (!handler.clear_table(old_size)) // Throws - parser_error(); - return; - } - case instr_LinkListSet: { - size_t link_ndx = read_int(); // Throws - size_t value = read_int(); // Throws - size_t prior_size = read_int(); // Throws - if (!handler.link_list_set(link_ndx, value, prior_size)) // Throws - parser_error(); - return; - } - case instr_LinkListSetAll: { - // todo, log that it's a SetAll we're doing - size_t size = read_int(); // Throws - for (size_t i = 0; i < size; i++) { - size_t link = read_int(); // Throws - if (!handler.link_list_set(i, link, size)) // Throws - parser_error(); - } - return; - } - case instr_LinkListInsert: { - size_t link_ndx = read_int(); // Throws - size_t value = read_int(); // Throws - size_t prior_size = read_int(); // Throws - if (!handler.link_list_insert(link_ndx, value, prior_size)) // Throws - parser_error(); - return; - } - case instr_LinkListMove: { - size_t from_link_ndx = read_int(); // Throws - size_t to_link_ndx = read_int(); // Throws - if (!handler.link_list_move(from_link_ndx, to_link_ndx)) // Throws - parser_error(); - return; - } - case instr_LinkListSwap: { - size_t link1_ndx = read_int(); // Throws - size_t link2_ndx = read_int(); // Throws - if (!handler.link_list_swap(link1_ndx, link2_ndx)) // Throws - parser_error(); - return; - } - case instr_LinkListErase: { - size_t link_ndx = read_int(); // Throws - size_t prior_size = read_int(); // Throws - if (!handler.link_list_erase(link_ndx, prior_size)) // Throws - parser_error(); - return; - } - case instr_LinkListNullify: { - size_t link_ndx = read_int(); // Throws - size_t prior_size = read_int(); // Throws - if (!handler.link_list_nullify(link_ndx, prior_size)) // Throws - parser_error(); - return; - } - case instr_LinkListClear: { - size_t old_list_size = read_int(); // Throws - if (!handler.link_list_clear(old_list_size)) // Throws - parser_error(); - return; - } - case instr_SelectLinkList: { - size_t col_ndx = read_int(); // Throws - size_t row_ndx = read_int(); // Throws - size_t target_group_level_ndx = read_int(); // Throws - if (!handler.select_link_list(col_ndx, row_ndx, target_group_level_ndx)) // Throws - parser_error(); - return; - } - case instr_MoveColumn: { - // FIXME: remove this in the next breaking change. - // This instruction is no longer supported and not used by either - // bindings or sync, so if we see it here, there was a problem parsing. - parser_error(); - return; - } - case instr_AddSearchIndex: { - size_t col_ndx = read_int(); // Throws - if (!handler.add_search_index(col_ndx)) // Throws - parser_error(); - return; - } - case instr_RemoveSearchIndex: { - size_t col_ndx = read_int(); // Throws - if (!handler.remove_search_index(col_ndx)) // Throws - parser_error(); - return; - } - case instr_SetLinkType: { - size_t col_ndx = read_int(); // Throws - int link_type = read_int(); // Throws - if (!is_valid_link_type(link_type)) - parser_error(); - if (!handler.set_link_type(col_ndx, LinkType(link_type))) // Throws - parser_error(); - return; - } - case instr_InsertColumn: - case instr_InsertNullableColumn: { - size_t col_ndx = read_int(); // Throws - int type = read_int(); // Throws - if (!is_valid_data_type(type)) - parser_error(); - if (REALM_UNLIKELY(type == type_Link || type == type_LinkList)) - parser_error(); - StringData name = read_string(m_string_buffer); // Throws - bool nullable = (Instruction(instr) == instr_InsertNullableColumn); - if (REALM_UNLIKELY(nullable && (type == type_Mixed))) { - // Nullability not supported for Mixed columns. - parser_error(); - } - if (!handler.insert_column(col_ndx, DataType(type), name, nullable)) // Throws - parser_error(); - return; - } - case instr_InsertLinkColumn: { - size_t col_ndx = read_int(); // Throws - int type = read_int(); // Throws - if (!is_valid_data_type(type)) - parser_error(); - if (REALM_UNLIKELY(type != type_Link && type != type_LinkList)) - parser_error(); - size_t link_target_table_ndx = read_int(); // Throws - size_t backlink_col_ndx = read_int(); // Throws - StringData name = read_string(m_string_buffer); // Throws - if (!handler.insert_link_column(col_ndx, DataType(type), name, link_target_table_ndx, - backlink_col_ndx)) // Throws - parser_error(); - return; - } - case instr_EraseColumn: { - size_t col_ndx = read_int(); // Throws - if (!handler.erase_column(col_ndx)) // Throws - parser_error(); - return; - } - case instr_EraseLinkColumn: { - size_t col_ndx = read_int(); // Throws - size_t link_target_table_ndx = read_int(); // Throws - size_t backlink_col_ndx = read_int(); // Throws - if (!handler.erase_link_column(col_ndx, link_target_table_ndx, backlink_col_ndx)) // Throws - parser_error(); - return; - } - case instr_RenameColumn: { - size_t col_ndx = read_int(); // Throws - StringData name = read_string(m_string_buffer); // Throws - if (!handler.rename_column(col_ndx, name)) // Throws - parser_error(); - return; - } - case instr_SelectDescriptor: { - int levels = read_int(); // Throws - if (levels < 0 || levels > m_max_levels) - parser_error(); - m_path.reserve(0, levels); // Throws - size_t* path = m_path.data(); - for (int i = 0; i != levels; ++i) { - size_t col_ndx = read_int(); // Throws - path[i] = col_ndx; - } - if (!handler.select_descriptor(levels, path)) // Throws - parser_error(); - return; - } - case instr_InsertGroupLevelTable: { - size_t table_ndx = read_int(); // Throws - size_t num_tables = read_int(); // Throws - StringData name = read_string(m_string_buffer); // Throws - if (!handler.insert_group_level_table(table_ndx, num_tables, name)) // Throws - parser_error(); - return; - } - case instr_EraseGroupLevelTable: { - size_t table_ndx = read_int(); // Throws - size_t prior_num_tables = read_int(); // Throws - if (!handler.erase_group_level_table(table_ndx, prior_num_tables)) // Throws - parser_error(); - return; - } - case instr_RenameGroupLevelTable: { - size_t table_ndx = read_int(); // Throws - StringData new_name = read_string(m_string_buffer); // Throws - if (!handler.rename_group_level_table(table_ndx, new_name)) // Throws - parser_error(); - return; - } - case instr_MoveGroupLevelTable: { - // This instruction is no longer supported and not used by either - // bindings or sync, so if we see it here, there was a problem parsing. - // FIXME: remove this in the next breaking change. - parser_error(); - return; - } - case instr_OptimizeTable: { - if (!handler.optimize_table()) // Throws - parser_error(); - return; - } - } - - throw BadTransactLog(); -} - - -template -T TransactLogParser::read_int() -{ - T value = 0; - int part = 0; - const int max_bytes = (std::numeric_limits::digits + 1 + 6) / 7; - for (int i = 0; i != max_bytes; ++i) { - char c; - if (!read_char(c)) - goto bad_transact_log; - part = static_cast(c); - if (0xFF < part) - goto bad_transact_log; // Only the first 8 bits may be used in each byte - if ((part & 0x80) == 0) { - T p = part & 0x3F; - if (util::int_shift_left_with_overflow_detect(p, i * 7)) - goto bad_transact_log; - value |= p; - break; - } - if (i == max_bytes - 1) - goto bad_transact_log; // Too many bytes - value |= T(part & 0x7F) << (i * 7); - } - if (part & 0x40) { - // The real value is negative. Because 'value' is positive at - // this point, the following negation is guaranteed by C++11 - // to never overflow. See C99+TC3 section 6.2.6.2 paragraph 2. - REALM_DIAG_PUSH(); - REALM_DIAG_IGNORE_UNSIGNED_MINUS(); - value = -value; - REALM_DIAG_POP(); - if (util::int_subtract_with_overflow_detect(value, 1)) - goto bad_transact_log; - } - return value; - -bad_transact_log: - throw BadTransactLog(); -} - - -inline void TransactLogParser::read_bytes(char* data, size_t size) -{ - for (;;) { - const size_t avail = m_input_end - m_input_begin; - if (size <= avail) - break; - realm::safe_copy_n(m_input_begin, avail, data); - if (!next_input_buffer()) - throw BadTransactLog(); - data += avail; - size -= avail; - } - const char* to = m_input_begin + size; - realm::safe_copy_n(m_input_begin, size, data); - m_input_begin = to; -} - - -inline BinaryData TransactLogParser::read_buffer(util::StringBuffer& buf, size_t size) -{ - const size_t avail = m_input_end - m_input_begin; - if (avail >= size) { - m_input_begin += size; - return BinaryData(m_input_begin - size, size); - } - - buf.clear(); - buf.resize(size); // Throws - read_bytes(buf.data(), size); - return BinaryData(buf.data(), size); -} - - -inline bool TransactLogParser::read_bool() -{ - return read_int(); -} - - -inline float TransactLogParser::read_float() -{ - static_assert(std::numeric_limits::is_iec559 && - sizeof(float) * std::numeric_limits::digits == 32, - "Unsupported 'float' representation"); - float value; - read_bytes(reinterpret_cast(&value), sizeof value); // Throws - return value; -} - - -inline double TransactLogParser::read_double() -{ - static_assert(std::numeric_limits::is_iec559 && - sizeof(double) * std::numeric_limits::digits == 64, - "Unsupported 'double' representation"); - double value; - read_bytes(reinterpret_cast(&value), sizeof value); // Throws - return value; -} - - -inline StringData TransactLogParser::read_string(util::StringBuffer& buf) -{ - size_t size = read_int(); // Throws - - if (size > Table::max_string_size) - parser_error(); - - BinaryData buffer = read_buffer(buf, size); - return StringData{buffer.data(), size}; -} - -inline Timestamp TransactLogParser::read_timestamp() -{ - int64_t seconds = read_int(); // Throws - int32_t nanoseconds = read_int(); // Throws - return Timestamp(seconds, nanoseconds); -} - - -inline BinaryData TransactLogParser::read_binary(util::StringBuffer& buf) -{ - size_t size = read_int(); // Throws - - return read_buffer(buf, size); -} - - -inline void TransactLogParser::read_mixed(Mixed* mixed) -{ - DataType type = DataType(read_int()); // Throws - switch (type) { - case type_Int: { - int_fast64_t value = read_int(); // Throws - mixed->set_int(value); - return; - } - case type_Bool: { - bool value = read_bool(); // Throws - mixed->set_bool(value); - return; - } - case type_Float: { - float value = read_float(); // Throws - mixed->set_float(value); - return; - } - case type_Double: { - double value = read_double(); // Throws - mixed->set_double(value); - return; - } - case type_OldDateTime: { - int_fast64_t value = read_int(); // Throws - mixed->set_olddatetime(value); - return; - } - case type_Timestamp: { - Timestamp value = read_timestamp(); // Throws - mixed->set_timestamp(value); - return; - } - case type_String: { - StringData value = read_string(m_string_buffer); // Throws - mixed->set_string(value); - return; - } - case type_Binary: { - BinaryData value = read_binary(m_string_buffer); // Throws - mixed->set_binary(value); - return; - } - case type_Table: { - *mixed = Mixed::subtable_tag(); - return; - } - case type_Mixed: - break; - case type_Link: - case type_LinkList: - // FIXME: Need to handle new link types here - break; - } - throw BadTransactLog(); -} - - -inline bool TransactLogParser::next_input_buffer() -{ - return m_input->next_block(m_input_begin, m_input_end); -} - - -inline bool TransactLogParser::read_char(char& c) -{ - if (m_input_begin == m_input_end && !next_input_buffer()) - return false; - c = *m_input_begin++; - return true; -} - - -inline bool TransactLogParser::is_valid_data_type(int type) -{ - switch (DataType(type)) { - case type_Int: - case type_Bool: - case type_Float: - case type_Double: - case type_String: - case type_Binary: - case type_OldDateTime: - case type_Timestamp: - case type_Table: - case type_Mixed: - case type_Link: - case type_LinkList: - return true; - } - return false; -} - - -inline bool TransactLogParser::is_valid_link_type(int type) -{ - switch (LinkType(type)) { - case link_Strong: - case link_Weak: - return true; - } - return false; -} - - -class TransactReverser { -public: - bool select_table(size_t group_level_ndx, size_t levels, const size_t* path) - { - sync_table(); - m_encoder.select_table(group_level_ndx, levels, path); - m_pending_ts_instr = get_inst(); - return true; - } - - bool select_descriptor(size_t levels, const size_t* path) - { - sync_descriptor(); - m_encoder.select_descriptor(levels, path); - m_pending_ds_instr = get_inst(); - return true; - } - - bool insert_group_level_table(size_t table_ndx, size_t num_tables, StringData) - { - sync_table(); - m_encoder.erase_group_level_table(table_ndx, num_tables + 1); - append_instruction(); - return true; - } - - bool erase_group_level_table(size_t table_ndx, size_t num_tables) - { - sync_table(); - m_encoder.insert_group_level_table(table_ndx, num_tables - 1, ""); - append_instruction(); - return true; - } - - bool rename_group_level_table(size_t, StringData) - { - sync_table(); - return true; - } - - bool optimize_table() - { - return true; // No-op - } - - bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool unordered) - { - size_t num_rows_to_erase = num_rows_to_insert; - size_t prior_num_rows_2 = prior_num_rows + num_rows_to_insert; - m_encoder.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows_2, unordered); // Throws - append_instruction(); - return true; - } - - bool add_row_with_key(size_t row_ndx, size_t prior_num_rows, size_t, int64_t) - { - bool unordered = true; - m_encoder.erase_rows(row_ndx, 1, prior_num_rows + 1, unordered); // Throws - append_instruction(); - return true; - } - - bool erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows, bool unordered) - { - size_t num_rows_to_insert = num_rows_to_erase; - // Number of rows in table after removal, but before inverse insertion - size_t prior_num_rows_2 = prior_num_rows - num_rows_to_erase; - m_encoder.insert_empty_rows(row_ndx, num_rows_to_insert, prior_num_rows_2, unordered); // Throws - append_instruction(); - return true; - } - - bool swap_rows(size_t row_ndx_1, size_t row_ndx_2) - { - m_encoder.swap_rows(row_ndx_1, row_ndx_2); - append_instruction(); - return true; - } - - bool move_row(size_t from_ndx, size_t to_ndx) - { - m_encoder.move_row(to_ndx, from_ndx); - append_instruction(); - return true; - } - - bool merge_rows(size_t row_ndx, size_t new_row_ndx) - { - // There is no instruction we can generate here to change back. - // However, we do need to refresh accessors for any tables - // connected through backlinks, so we generate updates on each - // affected row by merging to itself. - m_encoder.merge_rows(row_ndx, row_ndx); - append_instruction(); - m_encoder.merge_rows(new_row_ndx, new_row_ndx); - append_instruction(); - return true; - } - - bool set_int(size_t col_ndx, size_t row_ndx, int_fast64_t value, Instruction variant, size_t prior_num_rows) - { - m_encoder.set_int(col_ndx, row_ndx, value, variant, prior_num_rows); - append_instruction(); - return true; - } - - bool add_int(size_t col_ndx, size_t row_ndx, int_fast64_t value) - { - m_encoder.add_int(col_ndx, row_ndx, -value); - append_instruction(); - return true; - } - - bool set_bool(size_t col_ndx, size_t row_ndx, bool value, Instruction variant) - { - m_encoder.set_bool(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_float(size_t col_ndx, size_t row_ndx, float value, Instruction variant) - { - m_encoder.set_float(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_double(size_t col_ndx, size_t row_ndx, double value, Instruction variant) - { - m_encoder.set_double(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_string(size_t col_ndx, size_t row_ndx, StringData value, Instruction variant, size_t prior_num_rows) - { - m_encoder.set_string(col_ndx, row_ndx, value, variant, prior_num_rows); - append_instruction(); - return true; - } - - bool set_binary(size_t col_ndx, size_t row_ndx, BinaryData value, Instruction variant) - { - m_encoder.set_binary(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_olddatetime(size_t col_ndx, size_t row_ndx, OldDateTime value, Instruction variant) - { - m_encoder.set_olddatetime(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_timestamp(size_t col_ndx, size_t row_ndx, Timestamp value, Instruction variant) - { - m_encoder.set_timestamp(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_table(size_t col_ndx, size_t row_ndx, Instruction variant) - { - m_encoder.set_table(col_ndx, row_ndx, variant); - append_instruction(); - return true; - } - - bool set_mixed(size_t col_ndx, size_t row_ndx, const Mixed& value, Instruction variant) - { - m_encoder.set_mixed(col_ndx, row_ndx, value, variant); - append_instruction(); - return true; - } - - bool set_null(size_t col_ndx, size_t row_ndx, Instruction variant, size_t prior_num_rows) - { - m_encoder.set_null(col_ndx, row_ndx, variant, prior_num_rows); - append_instruction(); - return true; - } - - bool set_link(size_t col_ndx, size_t row_ndx, size_t value, size_t target_group_level_ndx, Instruction variant) - { - m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx, variant); - append_instruction(); - return true; - } - - bool insert_substring(size_t, size_t, size_t, StringData) - { - return true; // No-op - } - - bool erase_substring(size_t, size_t, size_t, size_t) - { - return true; // No-op - } - - bool clear_table(size_t old_size) - { - bool unordered = false; - m_encoder.insert_empty_rows(0, old_size, 0, unordered); - append_instruction(); - return true; - } - - bool add_search_index(size_t) - { - return true; // No-op - } - - bool remove_search_index(size_t) - { - return true; // No-op - } - - bool set_link_type(size_t, LinkType) - { - return true; // No-op - } - - bool insert_link_column(size_t col_idx, DataType, StringData, size_t target_table_idx, size_t backlink_col_ndx) - { - m_encoder.erase_link_column(col_idx, target_table_idx, backlink_col_ndx); - append_instruction(); - return true; - } - - bool erase_link_column(size_t col_idx, size_t target_table_idx, size_t backlink_col_idx) - { - DataType type = type_Link; // The real type of the column doesn't matter here, - // but the encoder asserts that it's actually a link type. - m_encoder.insert_link_column(col_idx, type, "", target_table_idx, backlink_col_idx); - append_instruction(); - return true; - } - - bool insert_column(size_t col_idx, DataType, StringData, bool) - { - m_encoder.erase_column(col_idx); - append_instruction(); - return true; - } - - bool erase_column(size_t col_idx) - { - m_encoder.insert_column(col_idx, DataType(), ""); - append_instruction(); - return true; - } - - bool rename_column(size_t, StringData) - { - return true; // No-op - } - - bool select_link_list(size_t col_ndx, size_t row_ndx, size_t link_target_group_level_ndx) - { - sync_linkview(); - m_encoder.select_link_list(col_ndx, row_ndx, link_target_group_level_ndx); - m_pending_lv_instr = get_inst(); - return true; - } - - bool link_list_set(size_t row, size_t value, size_t prior_size) - { - m_encoder.link_list_set(row, value, prior_size); - append_instruction(); - return true; - } - - bool link_list_insert(size_t link_ndx, size_t, size_t prior_size) - { - m_encoder.link_list_erase(link_ndx, prior_size + 1); - append_instruction(); - return true; - } - - bool link_list_move(size_t from_link_ndx, size_t to_link_ndx) - { - m_encoder.link_list_move(from_link_ndx, to_link_ndx); - append_instruction(); - return true; - } - - bool link_list_swap(size_t link1_ndx, size_t link2_ndx) - { - m_encoder.link_list_swap(link1_ndx, link2_ndx); - append_instruction(); - return true; - } - - bool link_list_erase(size_t link_ndx, size_t prior_size) - { - m_encoder.link_list_insert(link_ndx, 0, prior_size - 1); - append_instruction(); - return true; - } - - bool link_list_clear(size_t old_list_size) - { - // Append in reverse order because the reversed log is itself applied - // in reverse, and this way it generates all back-insertions rather than - // all front-insertions - for (size_t i = old_list_size; i > 0; --i) { - m_encoder.link_list_insert(i - 1, 0, old_list_size - i); - append_instruction(); - } - return true; - } - - bool nullify_link(size_t col_ndx, size_t row_ndx, size_t target_group_level_ndx) - { - size_t value = 0; - // FIXME: Is zero this right value to pass here, or should - // TransactReverser::nullify_link() also have taken a - // `target_group_level_ndx` argument. - m_encoder.set_link(col_ndx, row_ndx, value, target_group_level_ndx); - append_instruction(); - return true; - } - - bool link_list_nullify(size_t link_ndx, size_t prior_size) - { - m_encoder.link_list_insert(link_ndx, 0, prior_size - 1); - append_instruction(); - return true; - } - -private: - _impl::TransactLogBufferStream m_buffer; - _impl::TransactLogEncoder m_encoder{m_buffer}; - struct Instr { - size_t begin; - size_t end; - }; - std::vector m_instructions; - size_t current_instr_start = 0; - Instr m_pending_ts_instr{0, 0}; - Instr m_pending_ds_instr{0, 0}; - Instr m_pending_lv_instr{0, 0}; - - Instr get_inst() - { - Instr instr; - instr.begin = current_instr_start; - current_instr_start = transact_log_size(); - instr.end = current_instr_start; - return instr; - } - - size_t transact_log_size() const - { - REALM_ASSERT_3(m_encoder.write_position(), >=, m_buffer.transact_log_data()); - return m_encoder.write_position() - m_buffer.transact_log_data(); - } - - void append_instruction() - { - m_instructions.push_back(get_inst()); - } - - void append_instruction(Instr instr) - { - m_instructions.push_back(instr); - } - - void sync_select(Instr& pending_instr) - { - if (pending_instr.begin != pending_instr.end) { - append_instruction(pending_instr); - pending_instr = {0, 0}; - } - } - - void sync_linkview() - { - sync_select(m_pending_lv_instr); - } - - void sync_descriptor() - { - sync_linkview(); - sync_select(m_pending_ds_instr); - } - - void sync_table() - { - sync_descriptor(); - sync_select(m_pending_ts_instr); - } - - friend class ReversedNoCopyInputStream; -}; - - -class ReversedNoCopyInputStream : public NoCopyInputStream { -public: - ReversedNoCopyInputStream(TransactReverser& reverser) - : m_instr_order(reverser.m_instructions) - { - // push any pending select_table or select_descriptor into the buffer - reverser.sync_table(); - - m_buffer = reverser.m_buffer.transact_log_data(); - m_current = m_instr_order.size(); - } - - bool next_block(const char*& begin, const char*& end) override - { - if (m_current != 0) { - m_current--; - begin = m_buffer + m_instr_order[m_current].begin; - end = m_buffer + m_instr_order[m_current].end; - return (end > begin); - } - return false; - } - -private: - const char* m_buffer; - std::vector& m_instr_order; - size_t m_current; -}; - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_TRANSACT_LOG_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/index_string.hpp b/Lesson14/Pods/Realm/include/core/realm/index_string.hpp deleted file mode 100644 index 1c27039..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/index_string.hpp +++ /dev/null @@ -1,606 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_INDEX_STRING_HPP -#define REALM_INDEX_STRING_HPP - -#include -#include -#include - -#include -#include - -/* -The StringIndex class is used for both type_String and all integral types, such as type_Bool, type_OldDateTime and -type_Int. When used for integral types, the 64-bit integer is simply casted to a string of 8 bytes through a -pretty simple "wrapper layer" in all public methods. - -The StringIndex data structure is like an "inversed" B+ tree where the leafs contain row indexes and the non-leafs -contain 4-byte chunks of payload. Imagine a table with following strings: - - hello, kitty, kitten, foobar, kitty, foobar - -The topmost level of the index tree contains prefixes of the payload strings of length <= 4. The next level contains -prefixes of the remaining parts of the strings. Unnecessary levels of the tree are optimized away; the prefix "foob" -is shared only by rows that are identical ("foobar"), so "ar" is not needed to be stored in the tree. - - hell kitt foob - | /\ | - 0 en y {3, 5} - | \ - {1, 4} 2 - -Each non-leafs consists of two integer arrays of the same length, one containing payload and the other containing -references to the sublevel nodes. - -The leafs can be either a single value or a Column. If the reference in its parent node has its least significant -bit set, then the remaining upper bits specify the row index at which the string is stored. If the bit is clear, -it must be interpreted as a reference to a Column that stores the row indexes at which the string is stored. - -If a Column is used, then all row indexes are guaranteed to be sorted increasingly, which means you an search in it -using our binary search functions such as upper_bound() and lower_bound(). Each duplicate value will be stored in -the same Column, but Columns may contain more than just duplicates if the depth of the tree exceeds the value -`s_max_offset` This is to avoid stack overflow problems with many of our recursive functions if we have two very -long strings that have a long common prefix but differ in the last couple bytes. If a Column stores more than just -duplicates, then the list is kept sorted in ascending order by string value and within the groups of common -strings, the rows are sorted in ascending order. -*/ - -namespace realm { - -class Spec; -class Timestamp; - -class IndexArray : public Array { -public: - IndexArray(Allocator& allocator) - : Array(allocator) - { - } - - size_t index_string_find_first(StringData value, ColumnBase* column) const; - void index_string_find_all(IntegerColumn& result, StringData value, ColumnBase* column, bool case_insensitive = false) const; - FindRes index_string_find_all_no_copy(StringData value, ColumnBase* column, InternalFindResult& result) const; - size_t index_string_count(StringData value, ColumnBase* column) const; - -private: - template - size_t from_list(StringData value, InternalFindResult& result_ref, const IntegerColumn& rows, - ColumnBase* column) const; - - void from_list_all(StringData value, IntegerColumn& result, const IntegerColumn& rows, ColumnBase* column) const; - - void from_list_all_ins(StringData value, std::vector& result, const IntegerColumn& rows, - ColumnBase* column) const; - - template - size_t index_string(StringData value, InternalFindResult& result_ref, ColumnBase* column) const; - - void index_string_all(StringData value, IntegerColumn& result, ColumnBase* column) const; - - void index_string_all_ins(StringData value, IntegerColumn& result, ColumnBase* column) const; -}; - - -class StringIndex { -public: - StringIndex(ColumnBase* target_column, Allocator&); - StringIndex(ref_type, ArrayParent*, size_t ndx_in_parent, ColumnBase* target_column, Allocator&); - ~StringIndex() noexcept - { - } - - static ref_type create_empty(Allocator& alloc); - - void set_target(ColumnBase* target_column) noexcept; - - // Accessor concept: - Allocator& get_alloc() const noexcept; - void destroy() noexcept; - void detach(); - bool is_attached() const noexcept; - void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept; - size_t get_ndx_in_parent() const noexcept; - void set_ndx_in_parent(size_t ndx_in_parent) noexcept; - void update_from_parent(size_t old_baseline) noexcept; - void refresh_accessor_tree(size_t, const Spec&); - ref_type get_ref() const noexcept; - - // StringIndex interface: - - // 12 is the biggest element size of any non-string/binary Realm type - static const size_t string_conversion_buffer_size = 12; - using StringConversionBuffer = std::array; - - bool is_empty() const; - - template - void insert(size_t row_ndx, T value, size_t num_rows, bool is_append); - template - void insert(size_t row_ndx, util::Optional value, size_t num_rows, bool is_append); - - template - void set(size_t row_ndx, T new_value); - template - void set(size_t row_ndx, util::Optional new_value); - - template - void erase(size_t row_ndx, bool is_last); - - template - size_t find_first(T value) const; - template - void find_all(IntegerColumn& result, T value, bool case_insensitive = false) const; - template - FindRes find_all_no_copy(T value, InternalFindResult& result) const; - template - size_t count(T value) const; - template - void update_ref(T value, size_t old_row_ndx, size_t new_row_ndx); - - void clear(); - - void distinct(IntegerColumn& result) const; - bool has_duplicate_values() const noexcept; - - void verify() const; -#ifdef REALM_DEBUG - template - void verify_entries(const T& column) const; - void do_dump_node_structure(std::ostream&, int) const; - void to_dot() const; - void to_dot(std::ostream&, StringData title = StringData()) const; - void to_dot_2(std::ostream&, StringData title = StringData()) const; -#endif - - typedef int32_t key_type; - - // s_max_offset specifies the number of levels of recursive string indexes - // allowed before storing everything in lists. This is to avoid nesting - // to too deep of a level. Since every SubStringIndex stores 4 bytes, this - // means that a StringIndex is helpful for strings of a common prefix up to - // 4 times this limit (200 bytes shared). Lists are stored in sorted order, - // so strings sharing a common prefix of more than this limit will use a - // binary search of approximate complexity log2(n) from `std::lower_bound`. - static const size_t s_max_offset = 200; // max depth * s_index_key_length - static const size_t s_index_key_length = 4; - static key_type create_key(StringData) noexcept; - static key_type create_key(StringData, size_t) noexcept; - -private: - // m_array is a compact representation for storing the children of this StringIndex. - // Children can be: - // 1) a row number - // 2) a reference to a list which stores row numbers (for duplicate strings). - // 3) a reference to a sub-index - // m_array[0] is always a reference to a values array which stores the 4 byte chunk - // of payload data for quick string chunk comparisons. The array stored - // at m_array[0] lines up with the indices of values in m_array[1] so for example - // starting with an empty StringIndex: - // StringColumn::insert(target_row_ndx=42, value="test_string") would result with - // get_array_from_ref(m_array[0])[0] == create_key("test") and - // m_array[1] == 42 - // In this way, m_array which stores one child has a size of two. - // Children are type 1 (row number) if the LSB of the value is set. - // To get the actual row value, shift value down by one. - // If the LSB of the value is 0 then the value is a reference and can be either - // type 2, or type 3 (no shifting in either case). - // References point to a list if the context header flag is NOT set. - // If the header flag is set, references point to a sub-StringIndex (nesting). - std::unique_ptr m_array; - ColumnBase* m_target_column; - - struct inner_node_tag { - }; - StringIndex(inner_node_tag, Allocator&); - - static IndexArray* create_node(Allocator&, bool is_leaf); - - void insert_with_offset(size_t row_ndx, StringData value, size_t offset); - void insert_row_list(size_t ref, size_t offset, StringData value); - void insert_to_existing_list(size_t row, StringData value, IntegerColumn& list); - void insert_to_existing_list_at_lower(size_t row, StringData value, IntegerColumn& list, - const IntegerColumnIterator& lower); - key_type get_last_key() const; - - /// Add small signed \a diff to all elements that are greater than, or equal - /// to \a min_row_ndx. - void adjust_row_indexes(size_t min_row_ndx, int diff); - - struct NodeChange { - size_t ref1; - size_t ref2; - enum ChangeType { change_None, change_InsertBefore, change_InsertAfter, change_Split } type; - NodeChange(ChangeType t, size_t r1 = 0, size_t r2 = 0) - : ref1(r1) - , ref2(r2) - , type(t) - { - } - NodeChange() - : ref1(0) - , ref2(0) - , type(change_None) - { - } - }; - - // B-Tree functions - void TreeInsert(size_t row_ndx, key_type, size_t offset, StringData value); - NodeChange do_insert(size_t ndx, key_type, size_t offset, StringData value); - /// Returns true if there is room or it can join existing entries - bool leaf_insert(size_t row_ndx, key_type, size_t offset, StringData value, bool noextend = false); - void node_insert_split(size_t ndx, size_t new_ref); - void node_insert(size_t ndx, size_t ref); - void do_delete(size_t ndx, StringData, size_t offset); - void do_update_ref(StringData value, size_t row_ndx, size_t new_row_ndx, size_t offset); - - StringData get(size_t ndx, StringConversionBuffer& buffer) const; - - void node_add_key(ref_type ref); - -#ifdef REALM_DEBUG - static void dump_node_structure(const Array& node, std::ostream&, int level); - static void array_to_dot(std::ostream&, const Array&); - static void keys_to_dot(std::ostream&, const Array&, StringData title = StringData()); -#endif -}; - - -class SortedListComparator { -public: - SortedListComparator(ColumnBase& column_values); - bool operator()(int64_t ndx, StringData needle); - bool operator()(StringData needle, int64_t ndx); - -private: - ColumnBase& values; -}; - - -// Implementation: - -template -struct GetIndexData; - -template <> -struct GetIndexData { - static StringData get_index_data(const int64_t& value, StringIndex::StringConversionBuffer& buffer) - { - const char* c = reinterpret_cast(&value); - realm::safe_copy_n(c, sizeof(int64_t), buffer.data()); - return StringData{buffer.data(), sizeof(int64_t)}; - } -}; - -template <> -struct GetIndexData { - static StringData get_index_data(StringData data, StringIndex::StringConversionBuffer&) - { - return data; - } -}; - -template <> -struct GetIndexData { - static StringData get_index_data(null, StringIndex::StringConversionBuffer&) - { - return null{}; - } -}; - -template <> -struct GetIndexData { - static StringData get_index_data(const Timestamp&, StringIndex::StringConversionBuffer&); -}; - -template -struct GetIndexData> { - static StringData get_index_data(const util::Optional& value, StringIndex::StringConversionBuffer& buffer) - { - if (value) - return GetIndexData::get_index_data(*value, buffer); - return null{}; - } -}; - -template <> -struct GetIndexData { - static StringData get_index_data(float, StringIndex::StringConversionBuffer&) - { - REALM_ASSERT_RELEASE(false); // LCOV_EXCL_LINE; Index on float not supported - } -}; - -template <> -struct GetIndexData { - static StringData get_index_data(double, StringIndex::StringConversionBuffer&) - { - REALM_ASSERT_RELEASE(false); // LCOV_EXCL_LINE; Index on float not supported - } -}; - -template <> -struct GetIndexData : GetIndexData { -}; - -// to_str() is used by the integer index. The existing StringIndex is re-used for this -// by making IntegerColumn convert its integers to strings by calling to_str(). - -template -inline StringData to_str(T&& value, StringIndex::StringConversionBuffer& buffer) -{ - return GetIndexData::type>::get_index_data(value, buffer); -} - - -inline StringIndex::StringIndex(ColumnBase* target_column, Allocator& alloc) - : m_array(create_node(alloc, true)) // Throws - , m_target_column(target_column) -{ -} - -inline StringIndex::StringIndex(ref_type ref, ArrayParent* parent, size_t ndx_in_parent, ColumnBase* target_column, - Allocator& alloc) - : m_array(new IndexArray(alloc)) - , m_target_column(target_column) -{ - REALM_ASSERT_EX(Array::get_context_flag_from_header(alloc.translate(ref)), ref, size_t(alloc.translate(ref))); - m_array->init_from_ref(ref); - set_parent(parent, ndx_in_parent); -} - -inline StringIndex::StringIndex(inner_node_tag, Allocator& alloc) - : m_array(create_node(alloc, false)) // Throws - , m_target_column(nullptr) -{ -} - -// Byte order of the key is *reversed*, so that for the integer index, the least significant -// byte comes first, so that it fits little-endian machines. That way we can perform fast -// range-lookups and iterate in order, etc, as future features. This, however, makes the same -// features slower for string indexes. Todo, we should reverse the order conditionally, depending -// on the column type. -inline StringIndex::key_type StringIndex::create_key(StringData str) noexcept -{ - key_type key = 0; - - if (str.size() >= 4) - goto four; - if (str.size() < 2) { - if (str.size() == 0) - goto none; - goto one; - } - if (str.size() == 2) - goto two; - goto three; - -// Create 4 byte index key -// (encoded like this to allow literal comparisons -// independently of endianness) -four: - key |= (key_type(static_cast(str[3])) << 0); -three: - key |= (key_type(static_cast(str[2])) << 8); -two: - key |= (key_type(static_cast(str[1])) << 16); -one: - key |= (key_type(static_cast(str[0])) << 24); -none: - return key; -} - -// Index works as follows: All non-NULL values are stored as if they had appended an 'X' character at the end. So -// "foo" is stored as if it was "fooX", and "" (empty string) is stored as "X". And NULLs are stored as empty strings. -inline StringIndex::key_type StringIndex::create_key(StringData str, size_t offset) noexcept -{ - if (str.is_null()) - return 0; - - if (offset > str.size()) - return 0; - - // for very short strings - size_t tail = str.size() - offset; - if (tail <= sizeof(key_type) - 1) { - char buf[sizeof(key_type)]; - memset(buf, 0, sizeof(key_type)); - buf[tail] = 'X'; - memcpy(buf, str.data() + offset, tail); - return create_key(StringData(buf, tail + 1)); - } - // else fallback - return create_key(str.substr(offset)); -} - -template -void StringIndex::insert(size_t row_ndx, T value, size_t num_rows, bool is_append) -{ - REALM_ASSERT_3(row_ndx, !=, npos); - - // If the new row is inserted after the last row in the table, we don't need - // to adjust any row indexes. - if (!is_append) { - for (size_t i = 0; i < num_rows; ++i) { - size_t row_ndx_2 = row_ndx + i; - adjust_row_indexes(row_ndx_2, 1); // Throws - } - } - - StringConversionBuffer buffer; - - for (size_t i = 0; i < num_rows; ++i) { - size_t row_ndx_2 = row_ndx + i; - size_t offset = 0; // First key from beginning of string - insert_with_offset(row_ndx_2, to_str(value, buffer), offset); // Throws - } -} - -template -void StringIndex::insert(size_t row_ndx, util::Optional value, size_t num_rows, bool is_append) -{ - if (value) { - insert(row_ndx, *value, num_rows, is_append); - } - else { - insert(row_ndx, null{}, num_rows, is_append); - } -} - -template -void StringIndex::set(size_t row_ndx, T new_value) -{ - StringConversionBuffer buffer; - StringConversionBuffer buffer2; - StringData old_value = get(row_ndx, buffer); - StringData new_value2 = to_str(new_value, buffer2); - - // Note that insert_with_offset() throws UniqueConstraintViolation. - - if (REALM_LIKELY(new_value2 != old_value)) { - // We must erase this row first because erase uses find_first which - // might find the duplicate if we insert before erasing. - bool is_last = true; // To avoid updating refs - erase(row_ndx, is_last); // Throws - - size_t offset = 0; // First key from beginning of string - insert_with_offset(row_ndx, new_value2, offset); // Throws - } -} - -template -void StringIndex::set(size_t row_ndx, util::Optional new_value) -{ - if (new_value) { - set(row_ndx, *new_value); - } - else { - set(row_ndx, null{}); - } -} - -template -void StringIndex::erase(size_t row_ndx, bool is_last) -{ - StringConversionBuffer buffer; - StringData value = get(row_ndx, buffer); - - do_delete(row_ndx, value, 0); - - // Collapse top nodes with single item - while (m_array->is_inner_bptree_node()) { - REALM_ASSERT(m_array->size() > 1); // node cannot be empty - if (m_array->size() > 2) - break; - - ref_type ref = m_array->get_as_ref(1); - m_array->set(1, 1); // avoid destruction of the extracted ref - m_array->destroy_deep(); - m_array->init_from_ref(ref); - m_array->update_parent(); - } - - // If it is last item in column, we don't have to update refs - if (!is_last) - adjust_row_indexes(row_ndx, -1); -} - -template -size_t StringIndex::find_first(T value) const -{ - // Use direct access method - StringConversionBuffer buffer; - return m_array->index_string_find_first(to_str(value, buffer), m_target_column); -} - -template -void StringIndex::find_all(IntegerColumn& result, T value, bool case_insensitive) const -{ - // Use direct access method - StringConversionBuffer buffer; - return m_array->index_string_find_all(result, to_str(value, buffer), m_target_column, case_insensitive); -} - -template -FindRes StringIndex::find_all_no_copy(T value, InternalFindResult& result) const -{ - // Use direct access method - StringConversionBuffer buffer; - return m_array->index_string_find_all_no_copy(to_str(value, buffer), m_target_column, result); -} - -template -size_t StringIndex::count(T value) const -{ - // Use direct access method - StringConversionBuffer buffer; - return m_array->index_string_count(to_str(value, buffer), m_target_column); -} - -template -void StringIndex::update_ref(T value, size_t old_row_ndx, size_t new_row_ndx) -{ - StringConversionBuffer buffer; - do_update_ref(to_str(value, buffer), old_row_ndx, new_row_ndx, 0); -} - -inline void StringIndex::destroy() noexcept -{ - return m_array->destroy_deep(); -} - -inline bool StringIndex::is_attached() const noexcept -{ - return m_array->is_attached(); -} - -inline void StringIndex::refresh_accessor_tree(size_t, const Spec&) -{ - m_array->init_from_parent(); -} - -inline ref_type StringIndex::get_ref() const noexcept -{ - return m_array->get_ref(); -} - -inline void StringIndex::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept -{ - m_array->set_parent(parent, ndx_in_parent); -} - -inline size_t StringIndex::get_ndx_in_parent() const noexcept -{ - return m_array->get_ndx_in_parent(); -} - -inline void StringIndex::set_ndx_in_parent(size_t ndx_in_parent) noexcept -{ - m_array->set_ndx_in_parent(ndx_in_parent); -} - -inline void StringIndex::update_from_parent(size_t old_baseline) noexcept -{ - m_array->update_from_parent(old_baseline); -} - -} // namespace realm - -#endif // REALM_INDEX_STRING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/lang_bind_helper.hpp b/Lesson14/Pods/Realm/include/core/realm/lang_bind_helper.hpp deleted file mode 100644 index de287bf..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/lang_bind_helper.hpp +++ /dev/null @@ -1,378 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_LANG_BIND_HELPER_HPP -#define REALM_LANG_BIND_HELPER_HPP - -#include - -#include -#include -#include -#include -#include - -#include - -namespace realm { - - -/// These functions are only to be used by language bindings to gain -/// access to certain memebers that are othewise private. -/// -/// \note Applications are not supposed to call any of these functions -/// directly. -/// -/// All of the get_subtable_ptr() functions bind the table accessor pointer -/// before it is returned (bind_table_ptr()). The caller is then responsible for -/// making the corresponding call to unbind_table_ptr(). -class LangBindHelper { -public: - /// Increment the reference counter of the specified table accessor. This is - /// done automatically by all of the functions in this class that return - /// table accessor pointers, but if the binding/application makes a copy of - /// such a pointer, and the copy needs to have an "independent life", then - /// the binding/application must bind that copy using this function. - static void bind_table_ptr(const Table*) noexcept; - - /// Decrement the reference counter of the specified table accessor. The - /// binding/application must call this function for every bound table - /// accessor pointer object, when that pointer object ends its life. - static void unbind_table_ptr(const Table*) noexcept; - - /// Construct a new freestanding table. The table accessor pointer is bound - /// by the callee before it is returned (bind_table_ptr()). - static Table* new_table(); - - /// Construct a new freestanding table as a copy of the specified one. The - /// table accessor pointer is bound by the callee before it is returned - /// (bind_table_ptr()). - static Table* copy_table(const Table&); - - //@{ - - /// These functions are like their namesakes in Group, but these bypass the - /// construction of a smart-pointer object (TableRef). The table accessor - /// pointer is bound by the callee before it is returned (bind_table_ptr()). - - static Table* get_table(Group&, size_t index_in_group); - static const Table* get_table(const Group&, size_t index_in_group); - - static Table* get_table(Group&, StringData name); - static const Table* get_table(const Group&, StringData name); - - static Table* add_table(Group&, StringData name, bool require_unique_name = true); - static Table* get_or_add_table(Group&, StringData name, bool* was_added = nullptr); - - //@} - - static Table* get_subtable_ptr(Table*, size_t column_ndx, size_t row_ndx); - static const Table* get_subtable_ptr(const Table*, size_t column_ndx, size_t row_ndx); - - // FIXME: This is an 'oddball', do we really need it? If we do, - // please provide a comment that explains why it is needed! - static Table* get_subtable_ptr_during_insert(Table*, size_t col_ndx, size_t row_ndx); - - static Table* get_subtable_ptr(TableView*, size_t column_ndx, size_t row_ndx); - static const Table* get_subtable_ptr(const TableView*, size_t column_ndx, size_t row_ndx); - static const Table* get_subtable_ptr(const ConstTableView*, size_t column_ndx, size_t row_ndx); - - /// Calls parent.set_mixed_subtable(col_ndx, row_ndx, &source). Note - /// that the source table must have a descriptor that is - /// compatible with the target subtable column. - static void set_mixed_subtable(Table& parent, size_t col_ndx, size_t row_ndx, const Table& source); - - static const LinkViewRef& get_linklist_ptr(Row&, size_t col_ndx); - static void unbind_linklist_ptr(const LinkViewRef&); - - using VersionID = SharedGroup::VersionID; - - /// \defgroup lang_bind_helper_transactions Continuous Transactions - /// - /// advance_read() is equivalent to terminating the current read transaction - /// (SharedGroup::end_read()), and initiating a new one - /// (SharedGroup::begin_read()), except that all subordinate accessors - /// (Table, Row, Descriptor) will remain attached to the underlying objects, - /// unless those objects were removed in the target snapshot. By default, - /// the read transaction is advanced to the latest available snapshot, but - /// see SharedGroup::begin_read() for information about \a version. - /// - /// promote_to_write() is equivalent to terminating the current read - /// transaction (SharedGroup::end_read()), and initiating a new write - /// transaction (SharedGroup::begin_write()), except that all subordinate - /// accessors (Table, Row, Descriptor) will remain attached to the - /// underlying objects, unless those objects were removed in the target - /// snapshot. - /// - /// commit_and_continue_as_read() is equivalent to committing the current - /// write transaction (SharedGroup::commit()) and initiating a new read - /// transaction, which is bound to the snapshot produced by the write - /// transaction (SharedGroup::begin_read()), except that all subordinate - /// accessors (Table, Row, Descriptor) will remain attached to the - /// underlying objects. commit_and_continue_as_read() returns the version - /// produced by the committed transaction. - /// - /// rollback_and_continue_as_read() is equivalent to rolling back the - /// current write transaction (SharedGroup::rollback()) and initiating a new - /// read transaction, which is bound to the snapshot, that the write - /// transaction was based on (SharedGroup::begin_read()), except that all - /// subordinate accessors (Table, Row, Descriptor) will remain attached to - /// the underlying objects, unless they were attached to object that were - /// added during the rolled back transaction. - /// - /// If advance_read(), promote_to_write(), commit_and_continue_as_read(), or - /// rollback_and_continue_as_read() throws, the associated group accessor - /// and all of its subordinate accessors are left in a state that may not be - /// fully consistent. Only minimal consistency is guaranteed (see - /// AccessorConsistencyLevels). In this case, the application is required to - /// either destroy the SharedGroup object, forcing all associated accessors - /// to become detached, or take some other equivalent action that involves a - /// complete accessor detachment, such as terminating the transaction in - /// progress. Until then it is an error, and unsafe if the application - /// attempts to access any of those accessors. - /// - /// The application must use SharedGroup::end_read() if it wants to - /// terminate the transaction after advance_read() or promote_to_write() has - /// thrown an exception. Likewise, it must use SharedGroup::rollback() if it - /// wants to terminate the transaction after commit_and_continue_as_read() - /// or rollback_and_continue_as_read() has thrown an exception. - /// - /// \param observer An optional custom replication instruction handler. The - /// application may pass such a handler to observe the sequence of - /// modifications that advances (or rolls back) the state of the Realm. - /// - /// \throw SharedGroup::BadVersion Thrown by advance_read() if the specified - /// version does not correspond to a bound (or tethered) snapshot. - /// - //@{ - - static void advance_read(SharedGroup&, VersionID = VersionID()); - template - static void advance_read(SharedGroup&, O&& observer, VersionID = VersionID()); - static void promote_to_write(SharedGroup&); - template - static void promote_to_write(SharedGroup&, O&& observer); - static SharedGroup::version_type commit_and_continue_as_read(SharedGroup&); - static void rollback_and_continue_as_read(SharedGroup&); - template - static void rollback_and_continue_as_read(SharedGroup&, O&& observer); - - //@} - - /// Returns the name of the specified data type. Examples: - /// - ///
-    ///
-    ///   type_Int          ->  "int"
-    ///   type_Bool         ->  "bool"
-    ///   type_Float        ->  "float"
-    ///   ...
-    ///
-    /// 
- static const char* get_data_type_name(DataType) noexcept; - - static SharedGroup::version_type get_version_of_latest_snapshot(SharedGroup&); -}; - - -// Implementation: - -inline Table* LangBindHelper::new_table() -{ - typedef _impl::TableFriend tf; - Allocator& alloc = Allocator::get_default(); - size_t ref = tf::create_empty_table(alloc); // Throws - Table::Parent* parent = nullptr; - size_t ndx_in_parent = 0; - Table* table = tf::create_accessor(alloc, ref, parent, ndx_in_parent); // Throws - bind_table_ptr(table); - return table; -} - -inline Table* LangBindHelper::copy_table(const Table& table) -{ - typedef _impl::TableFriend tf; - Allocator& alloc = Allocator::get_default(); - size_t ref = tf::clone(table, alloc); // Throws - Table::Parent* parent = nullptr; - size_t ndx_in_parent = 0; - Table* copy_of_table = tf::create_accessor(alloc, ref, parent, ndx_in_parent); // Throws - bind_table_ptr(copy_of_table); - return copy_of_table; -} - -inline Table* LangBindHelper::get_subtable_ptr(Table* t, size_t column_ndx, size_t row_ndx) -{ - TableRef subtab = t->get_subtable_tableref(column_ndx, row_ndx); // Throws - return subtab.release(); -} - -inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, size_t column_ndx, size_t row_ndx) -{ - ConstTableRef subtab = t->get_subtable_tableref(column_ndx, row_ndx); // Throws - return subtab.release(); -} - -inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, size_t column_ndx, size_t row_ndx) -{ - return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); -} - -inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, size_t column_ndx, size_t row_ndx) -{ - return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); -} - -inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, size_t column_ndx, size_t row_ndx) -{ - return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); -} - -inline Table* LangBindHelper::get_table(Group& group, size_t index_in_group) -{ - typedef _impl::GroupFriend gf; - Table* table = &gf::get_table(group, index_in_group); // Throws - table->bind_ptr(); - return table; -} - -inline const Table* LangBindHelper::get_table(const Group& group, size_t index_in_group) -{ - typedef _impl::GroupFriend gf; - const Table* table = &gf::get_table(group, index_in_group); // Throws - table->bind_ptr(); - return table; -} - -inline Table* LangBindHelper::get_table(Group& group, StringData name) -{ - typedef _impl::GroupFriend gf; - Table* table = gf::get_table(group, name); // Throws - if (table) - table->bind_ptr(); - return table; -} - -inline const Table* LangBindHelper::get_table(const Group& group, StringData name) -{ - typedef _impl::GroupFriend gf; - const Table* table = gf::get_table(group, name); // Throws - if (table) - table->bind_ptr(); - return table; -} - -inline Table* LangBindHelper::add_table(Group& group, StringData name, bool require_unique_name) -{ - typedef _impl::GroupFriend gf; - Table* table = &gf::add_table(group, name, require_unique_name); // Throws - table->bind_ptr(); - return table; -} - -inline Table* LangBindHelper::get_or_add_table(Group& group, StringData name, bool* was_added) -{ - typedef _impl::GroupFriend gf; - Table* table = &gf::get_or_add_table(group, name, was_added); // Throws - table->bind_ptr(); - return table; -} - -inline void LangBindHelper::unbind_table_ptr(const Table* t) noexcept -{ - t->unbind_ptr(); -} - -inline void LangBindHelper::bind_table_ptr(const Table* t) noexcept -{ - t->bind_ptr(); -} - -inline void LangBindHelper::set_mixed_subtable(Table& parent, size_t col_ndx, size_t row_ndx, const Table& source) -{ - parent.set_mixed_subtable(col_ndx, row_ndx, &source); -} - -inline const LinkViewRef& LangBindHelper::get_linklist_ptr(Row& row, size_t col_ndx) -{ - LinkViewRef* link_view = new LinkViewRef(row.get_linklist(col_ndx)); - return *link_view; -} - -inline void LangBindHelper::unbind_linklist_ptr(const LinkViewRef& link_view) -{ - delete (&link_view); -} - -inline void LangBindHelper::advance_read(SharedGroup& sg, VersionID version) -{ - using sgf = _impl::SharedGroupFriend; - _impl::NullInstructionObserver* observer = nullptr; - sgf::advance_read(sg, observer, version); // Throws -} - -template -inline void LangBindHelper::advance_read(SharedGroup& sg, O&& observer, VersionID version) -{ - using sgf = _impl::SharedGroupFriend; - sgf::advance_read(sg, &observer, version); // Throws -} - -inline void LangBindHelper::promote_to_write(SharedGroup& sg) -{ - using sgf = _impl::SharedGroupFriend; - _impl::NullInstructionObserver* observer = nullptr; - sgf::promote_to_write(sg, observer); // Throws -} - -template -inline void LangBindHelper::promote_to_write(SharedGroup& sg, O&& observer) -{ - using sgf = _impl::SharedGroupFriend; - sgf::promote_to_write(sg, &observer); // Throws -} - -inline SharedGroup::version_type LangBindHelper::commit_and_continue_as_read(SharedGroup& sg) -{ - using sgf = _impl::SharedGroupFriend; - return sgf::commit_and_continue_as_read(sg); // Throws -} - -inline void LangBindHelper::rollback_and_continue_as_read(SharedGroup& sg) -{ - using sgf = _impl::SharedGroupFriend; - _impl::NullInstructionObserver* observer = nullptr; - sgf::rollback_and_continue_as_read(sg, observer); // Throws -} - -template -inline void LangBindHelper::rollback_and_continue_as_read(SharedGroup& sg, O&& observer) -{ - using sgf = _impl::SharedGroupFriend; - sgf::rollback_and_continue_as_read(sg, &observer); // Throws -} - -inline SharedGroup::version_type LangBindHelper::get_version_of_latest_snapshot(SharedGroup& sg) -{ - using sgf = _impl::SharedGroupFriend; - return sgf::get_version_of_latest_snapshot(sg); // Throws -} - -} // namespace realm - -#endif // REALM_LANG_BIND_HELPER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/link_view.hpp b/Lesson14/Pods/Realm/include/core/realm/link_view.hpp deleted file mode 100644 index 14be525..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/link_view.hpp +++ /dev/null @@ -1,397 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_LINK_VIEW_HPP -#define REALM_LINK_VIEW_HPP - -#include -#include -#include -#include - -namespace realm { - -class LinkListColumn; - -namespace _impl { -class LinkListFriend; -class TransactLogConvenientEncoder; -} - - -/// The effect of calling most of the link list functions on a detached accessor -/// is unspecified and may lead to general corruption, or even a crash. The -/// exceptions are is_attached() and the destructor. -/// -/// FIXME: Rename this class to `LinkList`. -class LinkView : public RowIndexes, public std::enable_shared_from_this { -public: - ~LinkView() noexcept; - bool is_attached() const noexcept; - - /// This method will return true if the LinkView is detached (no assert). - bool is_empty() const noexcept; - - /// This method will return 0 if the LinkView is detached (no assert). - size_t size() const noexcept override; - - bool operator==(const LinkView&) const noexcept; - bool operator!=(const LinkView&) const noexcept; - - // Getting links - Table::ConstRowExpr operator[](size_t link_ndx) const noexcept; - Table::RowExpr operator[](size_t link_ndx) noexcept; - Table::ConstRowExpr get(size_t link_ndx) const noexcept; - Table::RowExpr get(size_t link_ndx) noexcept; - - // Modifiers - void add(size_t target_row_ndx); - void insert(size_t link_ndx, size_t target_row_ndx); - void set(size_t link_ndx, size_t target_row_ndx); - /// Move the link at \a from_ndx such that it ends up at \a to_ndx. Other - /// links are shifted as necessary in such a way that their order is - /// preserved. - /// - /// Note that \a to_ndx is the desired final index of the moved link, - /// therefore, `move(1,1)` is a no-op, while `move(1,2)` moves the link at - /// index 1 by one position, such that it ends up at index 2. A side-effect - /// of that, is that the link, that was originally at index 2, is moved to - /// index 1. - void move(size_t from_ndx, size_t to_ndx); - void swap(size_t link1_ndx, size_t link2_ndx); - void remove(size_t link_ndx); - void clear(); - - void sort(size_t column, bool ascending = true); - void sort(SortDescriptor&& order); - - TableView get_sorted_view(size_t column_index, bool ascending = true) const; - TableView get_sorted_view(SortDescriptor order) const; - - /// Remove the target row of the specified link from the target table. This - /// also removes the specified link from this link list, and any other link - /// pointing to that row. This is merely a shorthand for - /// `get_target_table.move_last_over(get(link_ndx))`. - void remove_target_row(size_t link_ndx); - - /// Remove all target rows pointed to by links in this link list, and clear - /// this link list. - void remove_all_target_rows(); - - /// Search this list for a link to the specified target table row (specified - /// by its index in the target table). If found, the index of the link to - /// that row within this list is returned, otherwise `realm::not_found` is - /// returned. - size_t find(size_t target_row_ndx, size_t start = 0) const noexcept; - - const ColumnBase& get_column_base(size_t index) - const override; // FIXME: `ColumnBase` is not part of the public API, so this function must be made private. - const Table& get_origin_table() const noexcept; - Table& get_origin_table() noexcept; - - size_t get_origin_row_index() const noexcept; - - const Table& get_target_table() const noexcept; - Table& get_target_table() noexcept; - - // No-op because LinkViews are always kept in sync. - uint_fast64_t sync_if_needed() const override; - bool is_in_sync() const override - { - return true; - } - -private: - struct ctor_cookie { - }; - - TableRef m_origin_table; - LinkListColumn* m_origin_column; - - using HandoverPatch = LinkViewHandoverPatch; - static void generate_patch(const ConstLinkViewRef& ref, std::unique_ptr& patch); - static LinkViewRef create_from_and_consume_patch(std::unique_ptr& patch, Group& group); - - void detach(); - void set_origin_row_index(size_t row_ndx) noexcept; - - void do_insert(size_t link_ndx, size_t target_row_ndx); - size_t do_set(size_t link_ndx, size_t target_row_ndx); - size_t do_remove(size_t link_ndx); - void do_clear(bool broken_reciprocal_backlinks); - - void do_nullify_link(size_t old_target_row_ndx); - void do_update_link(size_t old_target_row_ndx, size_t new_target_row_ndx); - void do_swap_link(size_t target_row_ndx_1, size_t target_row_ndx_2); - - void refresh_accessor_tree(size_t new_row_ndx) noexcept; - - void update_from_parent(size_t old_baseline) noexcept; - - Replication* get_repl() noexcept; - void repl_unselect() noexcept; - friend class _impl::TransactLogConvenientEncoder; - -#ifdef REALM_DEBUG - void verify(size_t row_ndx) const; -#endif - // allocate using make_shared: - static std::shared_ptr create(Table* origin_table, LinkListColumn&, size_t row_ndx); - static std::shared_ptr create_detached(); - - friend class _impl::LinkListFriend; - friend class LinkListColumn; - friend class LangBindHelper; - friend class SharedGroup; - friend class Query; - friend class TableViewBase; - - // must be public for use by make_shared, but cannot be called from outside, - // because ctor_cookie is private -public: - LinkView(const ctor_cookie&, Table* origin_table, LinkListColumn&, size_t row_ndx); - LinkView(const ctor_cookie&); -}; - - -// Implementation - -inline LinkView::LinkView(const ctor_cookie&, Table* origin_table, LinkListColumn& column, size_t row_ndx) - : RowIndexes(IntegerColumn::unattached_root_tag(), column.get_alloc()) // Throws - , m_origin_table(origin_table->get_table_ref()) - , m_origin_column(&column) -{ - m_row_indexes.set_parent(m_origin_column, row_ndx); - m_row_indexes.init_from_parent(); -} - -// create a detached LinkView. Only partially initialized, as it will never be used for -// anything, but indicating that it is detached. -inline LinkView::LinkView(const ctor_cookie&) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws - , m_origin_table(TableRef()) - , m_origin_column(nullptr) -{ -} - -inline std::shared_ptr LinkView::create(Table* origin_table, LinkListColumn& column, size_t row_ndx) -{ - return std::make_shared(ctor_cookie(), origin_table, column, row_ndx); -} - -inline std::shared_ptr LinkView::create_detached() -{ - return std::make_shared(ctor_cookie()); -} - -inline LinkView::~LinkView() noexcept -{ - if (is_attached()) { - repl_unselect(); - m_origin_column->unregister_linkview(); - } -} - -inline void LinkView::detach() -{ - REALM_ASSERT(is_attached()); - repl_unselect(); - m_origin_table.reset(); - m_row_indexes.detach(); -} - -inline bool LinkView::is_attached() const noexcept -{ - return static_cast(m_origin_table); -} - -inline bool LinkView::is_empty() const noexcept -{ - if (!is_attached()) - return true; - - if (!m_row_indexes.is_attached()) - return true; - - return m_row_indexes.is_empty(); -} - -inline size_t LinkView::size() const noexcept -{ - if (!is_attached()) - return 0; - - if (!m_row_indexes.is_attached()) - return 0; - - return m_row_indexes.size(); -} - -inline bool LinkView::operator==(const LinkView& link_list) const noexcept -{ - Table& target_table_1 = m_origin_column->get_target_table(); - Table& target_table_2 = link_list.m_origin_column->get_target_table(); - if (target_table_1.get_index_in_group() != target_table_2.get_index_in_group()) - return false; - if (!m_row_indexes.is_attached() || m_row_indexes.is_empty()) { - return !link_list.m_row_indexes.is_attached() || link_list.m_row_indexes.is_empty(); - } - return link_list.m_row_indexes.is_attached() && m_row_indexes.compare(link_list.m_row_indexes); -} - -inline bool LinkView::operator!=(const LinkView& link_list) const noexcept -{ - return !(*this == link_list); -} - -inline Table::ConstRowExpr LinkView::get(size_t link_ndx) const noexcept -{ - return const_cast(this)->get(link_ndx); -} - -inline Table::RowExpr LinkView::get(size_t link_ndx) noexcept -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT(m_row_indexes.is_attached()); - REALM_ASSERT_3(link_ndx, <, m_row_indexes.size()); - - Table& target_table = m_origin_column->get_target_table(); - size_t target_row_ndx = to_size_t(m_row_indexes.get(link_ndx)); - return target_table[target_row_ndx]; -} - -inline Table::ConstRowExpr LinkView::operator[](size_t link_ndx) const noexcept -{ - return get(link_ndx); -} - -inline Table::RowExpr LinkView::operator[](size_t link_ndx) noexcept -{ - return get(link_ndx); -} - -inline void LinkView::add(size_t target_row_ndx) -{ - REALM_ASSERT(is_attached()); - size_t ins_pos = (m_row_indexes.is_attached()) ? m_row_indexes.size() : 0; - insert(ins_pos, target_row_ndx); -} - -inline size_t LinkView::find(size_t target_row_ndx, size_t start) const noexcept -{ - REALM_ASSERT(is_attached()); - REALM_ASSERT_3(target_row_ndx, <, m_origin_column->get_target_table().size()); - REALM_ASSERT_3(start, <=, size()); - - if (!m_row_indexes.is_attached()) - return not_found; - - return m_row_indexes.find_first(target_row_ndx, start); -} - -inline const ColumnBase& LinkView::get_column_base(size_t index) const -{ - return get_target_table().get_column_base(index); -} - -inline const Table& LinkView::get_origin_table() const noexcept -{ - return *m_origin_table; -} - -inline Table& LinkView::get_origin_table() noexcept -{ - return *m_origin_table; -} - -inline size_t LinkView::get_origin_row_index() const noexcept -{ - REALM_ASSERT(is_attached()); - return m_row_indexes.get_root_array()->get_ndx_in_parent(); -} - -inline void LinkView::set_origin_row_index(size_t row_ndx) noexcept -{ - REALM_ASSERT(is_attached()); - m_row_indexes.get_root_array()->set_ndx_in_parent(row_ndx); -} - -inline const Table& LinkView::get_target_table() const noexcept -{ - return m_origin_column->get_target_table(); -} - -inline Table& LinkView::get_target_table() noexcept -{ - return m_origin_column->get_target_table(); -} - -inline void LinkView::refresh_accessor_tree(size_t new_row_ndx) noexcept -{ - set_origin_row_index(new_row_ndx); - m_row_indexes.init_from_parent(); -} - -inline void LinkView::update_from_parent(size_t old_baseline) noexcept -{ - if (m_row_indexes.is_attached()) - m_row_indexes.update_from_parent(old_baseline); -} - -inline Replication* LinkView::get_repl() noexcept -{ - typedef _impl::TableFriend tf; - return tf::get_repl(*m_origin_table); -} - - -// The purpose of this class is to give internal access to some, but not all of -// the non-public parts of LinkView. -class _impl::LinkListFriend { -public: - static void do_set(LinkView& list, size_t link_ndx, size_t target_row_ndx) - { - list.do_set(link_ndx, target_row_ndx); - } - - static void do_remove(LinkView& list, size_t link_ndx) - { - list.do_remove(link_ndx); - } - - static void do_clear(LinkView& list) - { - bool broken_reciprocal_backlinks = false; - list.do_clear(broken_reciprocal_backlinks); - } - - static void do_insert(LinkView& list, size_t link_ndx, size_t target_row_ndx) - { - list.do_insert(link_ndx, target_row_ndx); - } - - static const LinkListColumn& get_origin_column(const LinkView& list) - { - REALM_ASSERT(list.is_attached()); - return *list.m_origin_column; - } -}; - -} // namespace realm - -#endif // REALM_LINK_VIEW_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/link_view_fwd.hpp b/Lesson14/Pods/Realm/include/core/realm/link_view_fwd.hpp deleted file mode 100644 index cba8801..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/link_view_fwd.hpp +++ /dev/null @@ -1,32 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_LINK_VIEW_FWD_HPP -#define REALM_LINK_VIEW_FWD_HPP - -#include - -namespace realm { - -class LinkView; -using LinkViewRef = std::shared_ptr; -using ConstLinkViewRef = std::shared_ptr; - -} // namespace realm - -#endif // REALM_LINK_VIEW_FWD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/metrics/metric_timer.hpp b/Lesson14/Pods/Realm/include/core/realm/metrics/metric_timer.hpp deleted file mode 100644 index 27ff716..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/metrics/metric_timer.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_METRIC_TIMER_HPP -#define REALM_METRIC_TIMER_HPP - -#include - -#include -#include -#include - -namespace realm { -namespace metrics { - -using nanosecond_storage_t = int64_t; - -class MetricTimerResult -{ -public: - MetricTimerResult(); - ~MetricTimerResult(); - nanosecond_storage_t get_elapsed_nanoseconds() const; - void report_nanoseconds(nanosecond_storage_t time); -protected: - nanosecond_storage_t m_elapsed_nanoseconds; -}; - - -class MetricTimer { -public: - MetricTimer(std::shared_ptr destination = nullptr); - ~MetricTimer(); - - void reset(); - - /// Returns elapsed time in nanoseconds since last call to reset(). - nanosecond_storage_t get_elapsed_nanoseconds() const; - /// Same as get_elapsed_time(). - operator nanosecond_storage_t() const; - - /// Format the elapsed time on the form 0h00m, 00m00s, 00.00s, or - /// 000.0ms depending on magnitude. - static void format(nanosecond_storage_t nanoseconds, std::ostream&); - - static std::string format(nanosecond_storage_t nanoseconds); - -private: - using clock_type = std::chrono::high_resolution_clock; - using time_point = std::chrono::time_point; - time_point m_start; - time_point m_paused_at; - std::shared_ptr m_dest; - - time_point get_timer_ticks() const; - nanosecond_storage_t calc_elapsed_nanoseconds(time_point begin, time_point end) const; -}; - - -inline void MetricTimer::reset() -{ - m_start = get_timer_ticks(); -} - -inline nanosecond_storage_t MetricTimer::get_elapsed_nanoseconds() const -{ - return calc_elapsed_nanoseconds(m_start, get_timer_ticks()); -} - -inline MetricTimer::operator nanosecond_storage_t() const -{ - return get_elapsed_nanoseconds(); -} - -inline std::ostream& operator<<(std::ostream& out, const MetricTimer& timer) -{ - MetricTimer::format(timer, out); - return out; -} - - -} // namespace metrics -} // namespace realm - -#endif // REALM_METRIC_TIMER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/metrics/metrics.hpp b/Lesson14/Pods/Realm/include/core/realm/metrics/metrics.hpp deleted file mode 100644 index 27a526d..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/metrics/metrics.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_METRICS_HPP -#define REALM_METRICS_HPP - -#include - -#include -#include -#include -#include "realm/util/fixed_size_buffer.hpp" - -namespace realm { - -class Group; - -namespace metrics { - -class Metrics { -public: - Metrics(size_t max_history_size); - ~Metrics() noexcept; - size_t num_query_metrics() const; - size_t num_transaction_metrics() const; - - void add_query(QueryInfo info); - void add_transaction(TransactionInfo info); - - void start_read_transaction(); - void start_write_transaction(); - void end_read_transaction(size_t total_size, size_t free_space, size_t num_objects, size_t num_versions, - size_t num_decrypted_pages); - void end_write_transaction(size_t total_size, size_t free_space, size_t num_objects, size_t num_versions, - size_t num_decrypted_pages); - static std::unique_ptr report_fsync_time(const Group& g); - static std::unique_ptr report_write_time(const Group& g); - - using QueryInfoList = util::FixedSizeBuffer; - using TransactionInfoList = util::FixedSizeBuffer; - - // Get the list of metric objects tracked since the last take - std::unique_ptr take_queries(); - std::unique_ptr take_transactions(); -private: - std::unique_ptr m_query_info; - std::unique_ptr m_transaction_info; - - std::unique_ptr m_pending_read; - std::unique_ptr m_pending_write; - - size_t m_max_num_queries; - size_t m_max_num_transactions; -}; - -} // namespace metrics -} // namespace realm - - - -#endif // REALM_METRICS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/metrics/query_info.hpp b/Lesson14/Pods/Realm/include/core/realm/metrics/query_info.hpp deleted file mode 100644 index 54b78d8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/metrics/query_info.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_QUERY_INFO_HPP -#define REALM_QUERY_INFO_HPP - -#include -#include -#include - -#include -#include -#include - -namespace realm { - -class Query; // forward declare in namespace realm - -namespace metrics { - -class QueryInfo { -public: - - enum QueryType { - type_Find, - type_FindAll, - type_Count, - type_Sum, - type_Average, - type_Maximum, - type_Minimum, - type_Invalid - }; - - QueryInfo(const Query* query, QueryType type); - ~QueryInfo() noexcept; - - std::string get_description() const; - std::string get_table_name() const; - QueryType get_type() const; - nanosecond_storage_t get_query_time_nanoseconds() const; - - static std::unique_ptr track(const Query* query, QueryType type); - static QueryType type_from_action(Action action); - -private: - std::string m_description; - std::string m_table_name; - QueryType m_type; - std::shared_ptr m_query_time; -}; - -} // namespace metrics -} // namespace realm - -#endif // REALM_QUERY_INFO_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/metrics/transaction_info.hpp b/Lesson14/Pods/Realm/include/core/realm/metrics/transaction_info.hpp deleted file mode 100644 index efcc2a6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/metrics/transaction_info.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_TRANSACTION_INFO_HPP -#define REALM_TRANSACTION_INFO_HPP - -#include -#include - -#include -#include - -namespace realm { -namespace metrics { - -class Metrics; - -class TransactionInfo { -public: - enum TransactionType { - read_transaction, - write_transaction - }; - TransactionInfo(TransactionType type); - TransactionInfo(const TransactionInfo&) = default; - ~TransactionInfo() noexcept; - - TransactionType get_transaction_type() const; - // the transaction time is a total amount which includes fsync_time + write_time + user_time - nanosecond_storage_t get_transaction_time_nanoseconds() const; - nanosecond_storage_t get_fsync_time_nanoseconds() const; - nanosecond_storage_t get_write_time_nanoseconds() const; - size_t get_disk_size() const; - size_t get_free_space() const; - size_t get_total_objects() const; - size_t get_num_available_versions() const; - size_t get_num_decrypted_pages() const; - -private: - MetricTimerResult m_transaction_time; - std::shared_ptr m_fsync_time; - std::shared_ptr m_write_time; - MetricTimer m_transact_timer; - - size_t m_realm_disk_size; - size_t m_realm_free_space; - size_t m_total_objects; - TransactionType m_type; - size_t m_num_versions; - size_t m_num_decrypted_pages; - - friend class Metrics; - void update_stats(size_t disk_size, size_t free_space, size_t total_objects, size_t available_versions, - size_t num_decrypted_pages); - void finish_timer(); -}; - -} // namespace metrics -} // namespace realm - -#endif // REALM_TRANSACTION_INFO_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/mixed.hpp b/Lesson14/Pods/Realm/include/core/realm/mixed.hpp deleted file mode 100644 index 243ed45..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/mixed.hpp +++ /dev/null @@ -1,732 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_MIXED_HPP -#define REALM_MIXED_HPP - -#include // int64_t - not part of C++03, not even required by C++11 (see C++11 section 18.4.1) - -#include // size_t -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - - -/// This class represents a polymorphic Realm value. -/// -/// At any particular moment an instance of this class stores a -/// definite value of a definite type. If, for instance, that is an -/// integer value, you may call get_int() to extract that value. You -/// may call get_type() to discover what type of value is currently -/// stored. Calling get_int() on an instance that does not store an -/// integer, has undefined behavior, and likewise for all the other -/// types that can be stored. -/// -/// It is crucial to understand that the act of extracting a value of -/// a particular type requires definite knowledge about the stored -/// type. Calling a getter method for any particular type, that is not -/// the same type as the stored value, has undefined behavior. -/// -/// While values of numeric types are contained directly in a Mixed -/// instance, character and binary data are merely referenced. A Mixed -/// instance never owns the referenced data, nor does it in any other -/// way attempt to manage its lifetime. -/// -/// For compatibility with C style strings, when a string (character -/// data) is stored in a Realm database, it is always followed by a -/// terminating null character. This is also true when strings are -/// stored in a mixed type column. This means that in the following -/// code, if the 'mixed' value of the 8th row stores a string, then \c -/// c_str will always point to a null-terminated string: -/// -/// \code{.cpp} -/// -/// const char* c_str = my_table[7].mixed.data(); // Always null-terminated -/// -/// \endcode -/// -/// Note that this assumption does not hold in general for strings in -/// instances of Mixed. Indeed there is nothing stopping you from -/// constructing a new Mixed instance that refers to a string without -/// a terminating null character. -/// -/// At the present time no soultion has been found that would allow -/// for a Mixed instance to directly store a reference to a table. The -/// problem is roughly as follows: From most points of view, the -/// desirable thing to do, would be to store the table reference in a -/// Mixed instance as a plain pointer without any ownership -/// semantics. This would have no negative impact on the performance -/// of copying and destroying Mixed instances, and it would serve just -/// fine for passing a table as argument when setting the value of an -/// entry in a mixed column. In that case a copy of the referenced -/// table would be inserted into the mixed column. -/// -/// On the other hand, when retrieving a table reference from a mixed -/// column, storing it as a plain pointer in a Mixed instance is no -/// longer an acceptable option. The complex rules for managing the -/// lifetime of a Table instance, that represents a subtable, -/// necessitates the use of a "smart pointer" such as -/// TableRef. Enhancing the Mixed class to be able to act as a -/// TableRef would be possible, but would also lead to several new -/// problems. One problem is the risk of a Mixed instance outliving a -/// stack allocated Table instance that it references. This would be a -/// fatal error. Another problem is the impact that the nontrivial -/// table reference has on the performance of copying and destroying -/// Mixed instances. -/// -/// \sa StringData -class Mixed { -public: - Mixed() noexcept; - - Mixed(bool) noexcept; - Mixed(int64_t) noexcept; - Mixed(float) noexcept; - Mixed(double) noexcept; - Mixed(StringData) noexcept; - Mixed(BinaryData) noexcept; - Mixed(OldDateTime) noexcept; - Mixed(Timestamp) noexcept; - - // These are shortcuts for Mixed(StringData(c_str)), and are - // needed to avoid unwanted implicit conversion of char* to bool. - Mixed(char* c_str) noexcept - { - set_string(c_str); - } - Mixed(const char* c_str) noexcept - { - set_string(c_str); - } - - struct subtable_tag { - }; - Mixed(subtable_tag) noexcept - : m_type(type_Table) - { - } - - ~Mixed() noexcept - { - } - - DataType get_type() const noexcept - { - return m_type; - } - - template - T get() const noexcept; - - int64_t get_int() const noexcept; - bool get_bool() const noexcept; - float get_float() const noexcept; - double get_double() const noexcept; - StringData get_string() const noexcept; - BinaryData get_binary() const noexcept; - OldDateTime get_olddatetime() const noexcept; - Timestamp get_timestamp() const noexcept; - - void set_int(int64_t) noexcept; - void set_bool(bool) noexcept; - void set_float(float) noexcept; - void set_double(double) noexcept; - void set_string(StringData) noexcept; - void set_binary(BinaryData) noexcept; - void set_binary(const char* data, size_t size) noexcept; - void set_olddatetime(OldDateTime) noexcept; - void set_timestamp(Timestamp) noexcept; - - template - friend std::basic_ostream& operator<<(std::basic_ostream&, const Mixed&); - -private: - DataType m_type; - union { - int64_t m_int; - bool m_bool; - float m_float; - double m_double; - const char* m_data; - int_fast64_t m_date; - Timestamp m_timestamp; - }; - size_t m_size = 0; -}; - -// Note: We cannot compare two mixed values, since when the type of -// both is type_Table, we would have to compare the two tables, but -// the mixed values do not provide access to those tables. - -// Note: The mixed values are specified as Wrap. If they were -// not, these operators would apply to simple comparisons, such as int -// vs int64_t, and cause ambiguity. This is because the constructors -// of Mixed are not explicit. - -// Compare mixed with integer -template -bool operator==(Wrap, const T&) noexcept; -template -bool operator!=(Wrap, const T&) noexcept; -template -bool operator==(const T&, Wrap) noexcept; -template -bool operator!=(const T&, Wrap) noexcept; - -// Compare mixed with boolean -bool operator==(Wrap, bool) noexcept; -bool operator!=(Wrap, bool) noexcept; -bool operator==(bool, Wrap) noexcept; -bool operator!=(bool, Wrap) noexcept; - -// Compare mixed with float -bool operator==(Wrap, float); -bool operator!=(Wrap, float); -bool operator==(float, Wrap); -bool operator!=(float, Wrap); - -// Compare mixed with double -bool operator==(Wrap, double); -bool operator!=(Wrap, double); -bool operator==(double, Wrap); -bool operator!=(double, Wrap); - -// Compare mixed with string -bool operator==(Wrap, StringData) noexcept; -bool operator!=(Wrap, StringData) noexcept; -bool operator==(StringData, Wrap) noexcept; -bool operator!=(StringData, Wrap) noexcept; -bool operator==(Wrap, const char* c_str) noexcept; -bool operator!=(Wrap, const char* c_str) noexcept; -bool operator==(const char* c_str, Wrap) noexcept; -bool operator!=(const char* c_str, Wrap) noexcept; -bool operator==(Wrap, char* c_str) noexcept; -bool operator!=(Wrap, char* c_str) noexcept; -bool operator==(char* c_str, Wrap) noexcept; -bool operator!=(char* c_str, Wrap) noexcept; - -// Compare mixed with binary data -bool operator==(Wrap, BinaryData) noexcept; -bool operator!=(Wrap, BinaryData) noexcept; -bool operator==(BinaryData, Wrap) noexcept; -bool operator!=(BinaryData, Wrap) noexcept; - -// Compare mixed with date -bool operator==(Wrap, OldDateTime) noexcept; -bool operator!=(Wrap, OldDateTime) noexcept; -bool operator==(OldDateTime, Wrap) noexcept; -bool operator!=(OldDateTime, Wrap) noexcept; - -// Compare mixed with Timestamp -bool operator==(Wrap, Timestamp) noexcept; -bool operator!=(Wrap, Timestamp) noexcept; -bool operator==(Timestamp, Wrap) noexcept; -bool operator!=(Timestamp, Wrap) noexcept; - -// Implementation: - -inline Mixed::Mixed() noexcept -{ - m_type = type_Int; - m_int = 0; -} - -inline Mixed::Mixed(int64_t v) noexcept -{ - m_type = type_Int; - m_int = v; -} - -inline Mixed::Mixed(bool v) noexcept -{ - m_type = type_Bool; - m_bool = v; -} - -inline Mixed::Mixed(float v) noexcept -{ - m_type = type_Float; - m_float = v; -} - -inline Mixed::Mixed(double v) noexcept -{ - m_type = type_Double; - m_double = v; -} - -inline Mixed::Mixed(StringData v) noexcept -{ - m_type = type_String; - m_data = v.data(); - m_size = v.size(); -} - -inline Mixed::Mixed(BinaryData v) noexcept -{ - m_type = type_Binary; - m_data = v.data(); - m_size = v.size(); -} - -inline Mixed::Mixed(OldDateTime v) noexcept -{ - m_type = type_OldDateTime; - m_date = v.get_olddatetime(); -} - -inline Mixed::Mixed(Timestamp v) noexcept -{ - m_type = type_Timestamp; - m_timestamp = v; -} - -inline int64_t Mixed::get_int() const noexcept -{ - REALM_ASSERT(m_type == type_Int); - return m_int; -} - -inline bool Mixed::get_bool() const noexcept -{ - REALM_ASSERT(m_type == type_Bool); - return m_bool; -} - -inline float Mixed::get_float() const noexcept -{ - REALM_ASSERT(m_type == type_Float); - return m_float; -} - -inline double Mixed::get_double() const noexcept -{ - REALM_ASSERT(m_type == type_Double); - return m_double; -} - -inline StringData Mixed::get_string() const noexcept -{ - REALM_ASSERT(m_type == type_String); - return StringData(m_data, m_size); -} - -inline BinaryData Mixed::get_binary() const noexcept -{ - REALM_ASSERT(m_type == type_Binary); - return BinaryData(m_data, m_size); -} - -inline OldDateTime Mixed::get_olddatetime() const noexcept -{ - REALM_ASSERT(m_type == type_OldDateTime); - return m_date; -} - -inline Timestamp Mixed::get_timestamp() const noexcept -{ - REALM_ASSERT(m_type == type_Timestamp); - return m_timestamp; -} - -template <> -inline int64_t Mixed::get() const noexcept -{ - return get_int(); -} - -template <> -inline bool Mixed::get() const noexcept -{ - return get_bool(); -} - -template <> -inline float Mixed::get() const noexcept -{ - return get_float(); -} - -template <> -inline double Mixed::get() const noexcept -{ - return get_double(); -} - -template <> -inline OldDateTime Mixed::get() const noexcept -{ - return get_olddatetime(); -} - -template <> -inline StringData Mixed::get() const noexcept -{ - return get_string(); -} - -template <> -inline BinaryData Mixed::get() const noexcept -{ - return get_binary(); -} - -template <> -inline Timestamp Mixed::get() const noexcept -{ - return get_timestamp(); -} - - -inline void Mixed::set_int(int64_t v) noexcept -{ - m_type = type_Int; - m_int = v; -} - -inline void Mixed::set_bool(bool v) noexcept -{ - m_type = type_Bool; - m_bool = v; -} - -inline void Mixed::set_float(float v) noexcept -{ - m_type = type_Float; - m_float = v; -} - -inline void Mixed::set_double(double v) noexcept -{ - m_type = type_Double; - m_double = v; -} - -inline void Mixed::set_string(StringData v) noexcept -{ - m_type = type_String; - m_data = v.data(); - m_size = v.size(); -} - -inline void Mixed::set_binary(BinaryData v) noexcept -{ - set_binary(v.data(), v.size()); -} - -inline void Mixed::set_binary(const char* data, size_t size) noexcept -{ - m_type = type_Binary; - m_data = data; - m_size = size; -} - -inline void Mixed::set_olddatetime(OldDateTime v) noexcept -{ - m_type = type_OldDateTime; - m_date = v.get_olddatetime(); -} - -inline void Mixed::set_timestamp(Timestamp v) noexcept -{ - m_type = type_Timestamp; - m_timestamp = v; -} - -// LCOV_EXCL_START -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const Mixed& m) -{ - out << "Mixed("; - switch (m.m_type) { - case type_Int: - out << m.m_int; - break; - case type_Bool: - out << m.m_bool; - break; - case type_Float: - out << m.m_float; - break; - case type_Double: - out << m.m_double; - break; - case type_String: - out << StringData(m.m_data, m.m_size); - break; - case type_Binary: - out << BinaryData(m.m_data, m.m_size); - break; - case type_OldDateTime: - out << OldDateTime(m.m_date); - break; - case type_Timestamp: - out << Timestamp(m.m_timestamp); - break; - case type_Table: - out << "subtable"; - break; - case type_Mixed: - case type_Link: - case type_LinkList: - REALM_ASSERT(false); - } - out << ")"; - return out; -} -// LCOV_EXCL_STOP - - -// Compare mixed with integer - -template -inline bool operator==(Wrap a, const T& b) noexcept -{ - return Mixed(a).get_type() == type_Int && Mixed(a).get_int() == b; -} - -template -inline bool operator!=(Wrap a, const T& b) noexcept -{ - return Mixed(a).get_type() != type_Int || Mixed(a).get_int() != b; -} - -template -inline bool operator==(const T& a, Wrap b) noexcept -{ - return type_Int == Mixed(b).get_type() && a == Mixed(b).get_int(); -} - -template -inline bool operator!=(const T& a, Wrap b) noexcept -{ - return type_Int != Mixed(b).get_type() || a != Mixed(b).get_int(); -} - - -// Compare mixed with boolean - -inline bool operator==(Wrap a, bool b) noexcept -{ - return Mixed(a).get_type() == type_Bool && Mixed(a).get_bool() == b; -} - -inline bool operator!=(Wrap a, bool b) noexcept -{ - return Mixed(a).get_type() != type_Bool || Mixed(a).get_bool() != b; -} - -inline bool operator==(bool a, Wrap b) noexcept -{ - return type_Bool == Mixed(b).get_type() && a == Mixed(b).get_bool(); -} - -inline bool operator!=(bool a, Wrap b) noexcept -{ - return type_Bool != Mixed(b).get_type() || a != Mixed(b).get_bool(); -} - - -// Compare mixed with float - -inline bool operator==(Wrap a, float b) -{ - return Mixed(a).get_type() == type_Float && Mixed(a).get_float() == b; -} - -inline bool operator!=(Wrap a, float b) -{ - return Mixed(a).get_type() != type_Float || Mixed(a).get_float() != b; -} - -inline bool operator==(float a, Wrap b) -{ - return type_Float == Mixed(b).get_type() && a == Mixed(b).get_float(); -} - -inline bool operator!=(float a, Wrap b) -{ - return type_Float != Mixed(b).get_type() || a != Mixed(b).get_float(); -} - - -// Compare mixed with double - -inline bool operator==(Wrap a, double b) -{ - return Mixed(a).get_type() == type_Double && Mixed(a).get_double() == b; -} - -inline bool operator!=(Wrap a, double b) -{ - return Mixed(a).get_type() != type_Double || Mixed(a).get_double() != b; -} - -inline bool operator==(double a, Wrap b) -{ - return type_Double == Mixed(b).get_type() && a == Mixed(b).get_double(); -} - -inline bool operator!=(double a, Wrap b) -{ - return type_Double != Mixed(b).get_type() || a != Mixed(b).get_double(); -} - - -// Compare mixed with string - -inline bool operator==(Wrap a, StringData b) noexcept -{ - return Mixed(a).get_type() == type_String && Mixed(a).get_string() == b; -} - -inline bool operator!=(Wrap a, StringData b) noexcept -{ - return Mixed(a).get_type() != type_String || Mixed(a).get_string() != b; -} - -inline bool operator==(StringData a, Wrap b) noexcept -{ - return type_String == Mixed(b).get_type() && a == Mixed(b).get_string(); -} - -inline bool operator!=(StringData a, Wrap b) noexcept -{ - return type_String != Mixed(b).get_type() || a != Mixed(b).get_string(); -} - -inline bool operator==(Wrap a, const char* b) noexcept -{ - return a == StringData(b); -} - -inline bool operator!=(Wrap a, const char* b) noexcept -{ - return a != StringData(b); -} - -inline bool operator==(const char* a, Wrap b) noexcept -{ - return StringData(a) == b; -} - -inline bool operator!=(const char* a, Wrap b) noexcept -{ - return StringData(a) != b; -} - -inline bool operator==(Wrap a, char* b) noexcept -{ - return a == StringData(b); -} - -inline bool operator!=(Wrap a, char* b) noexcept -{ - return a != StringData(b); -} - -inline bool operator==(char* a, Wrap b) noexcept -{ - return StringData(a) == b; -} - -inline bool operator!=(char* a, Wrap b) noexcept -{ - return StringData(a) != b; -} - - -// Compare mixed with binary data - -inline bool operator==(Wrap a, BinaryData b) noexcept -{ - return Mixed(a).get_type() == type_Binary && Mixed(a).get_binary() == b; -} - -inline bool operator!=(Wrap a, BinaryData b) noexcept -{ - return Mixed(a).get_type() != type_Binary || Mixed(a).get_binary() != b; -} - -inline bool operator==(BinaryData a, Wrap b) noexcept -{ - return type_Binary == Mixed(b).get_type() && a == Mixed(b).get_binary(); -} - -inline bool operator!=(BinaryData a, Wrap b) noexcept -{ - return type_Binary != Mixed(b).get_type() || a != Mixed(b).get_binary(); -} - - -// Compare mixed with date - -inline bool operator==(Wrap a, OldDateTime b) noexcept -{ - return Mixed(a).get_type() == type_OldDateTime && OldDateTime(Mixed(a).get_olddatetime()) == b; -} - -inline bool operator!=(Wrap a, OldDateTime b) noexcept -{ - return Mixed(a).get_type() != type_OldDateTime || OldDateTime(Mixed(a).get_olddatetime()) != b; -} - -inline bool operator==(OldDateTime a, Wrap b) noexcept -{ - return type_OldDateTime == Mixed(b).get_type() && a == OldDateTime(Mixed(b).get_olddatetime()); -} - -inline bool operator!=(OldDateTime a, Wrap b) noexcept -{ - return type_OldDateTime != Mixed(b).get_type() || a != OldDateTime(Mixed(b).get_olddatetime()); -} - -// Compare mixed with Timestamp - -inline bool operator==(Wrap a, Timestamp b) noexcept -{ - return Mixed(a).get_type() == type_Timestamp && Timestamp(Mixed(a).get_timestamp()) == b; -} - -inline bool operator!=(Wrap a, Timestamp b) noexcept -{ - return Mixed(a).get_type() != type_Timestamp || Timestamp(Mixed(a).get_timestamp()) != b; -} - -inline bool operator==(Timestamp a, Wrap b) noexcept -{ - return type_Timestamp == Mixed(b).get_type() && a == Timestamp(Mixed(b).get_timestamp()); -} - -inline bool operator!=(Timestamp a, Wrap b) noexcept -{ - return type_Timestamp != Mixed(b).get_type() || a != Timestamp(Mixed(b).get_timestamp()); -} - - -} // namespace realm - -#endif // REALM_MIXED_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/null.hpp b/Lesson14/Pods/Realm/include/core/realm/null.hpp deleted file mode 100644 index 733e798..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/null.hpp +++ /dev/null @@ -1,172 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_NULL_HPP -#define REALM_NULL_HPP - -#include -#include - -#include -#include -#include -#include - -namespace realm { - -/* -Represents null in Query, find(), get(), set(), etc. - -Float/Double: Realm can both store user-given NaNs and null. Any user-given signaling NaN is converted to -0x7fa00000 (if float) or 0x7ff4000000000000 (if double). Any user-given quiet NaN is converted to -0x7fc00000 (if float) or 0x7ff8000000000000 (if double). So Realm does not preserve the optional bits in -user-given NaNs. - -However, since both clang and gcc on x64 and ARM, and also Java on x64, return these bit patterns when -requesting NaNs, these will actually seem to roundtrip bit-exact for the end-user in most cases. - -If set_null() is called, a null is stored in form of the bit pattern 0xffffffff (if float) or -0xffffffffffffffff (if double). These are quiet NaNs. - -Executing a query that involves a float/double column that contains NaNs gives an undefined result. If -it contains signaling NaNs, it may throw an exception. - -Notes on IEEE: - -A NaN float is any bit pattern `s 11111111 S xxxxxxxxxxxxxxxxxxxxxx` where `s` and `x` are arbitrary, but at -least 1 `x` must be 1. If `S` is 1, it's a quiet NaN, else it's a signaling NaN. - -A NaN doubule is the same as above, but for `s eeeeeeeeeee S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` - -The `S` bit is at position 22 (float) or 51 (double). -*/ - -struct null { - null() - { - } - operator int64_t() - { - throw(LogicError::type_mismatch); - } - template - operator util::Optional() - { - return util::none; - } - - template - bool operator==(const T&) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator!=(const T&) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator>(const T&) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator>=(const T&) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator<=(const T&) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator<(const T&) const - { - REALM_ASSERT(false); - return false; - } - - /// Returns whether `v` bitwise equals the null bit-pattern - template - static bool is_null_float(T v) - { - T i = null::get_null_float(); - return std::memcmp(&i, &v, sizeof(T)) == 0; - } - - /// Returns the quiet NaNs that represent null for floats/doubles in Realm in stored payload. - template - static T get_null_float() - { - typename std::conditional::value, uint32_t, uint64_t>::type i; - int64_t double_nan = 0x7ff80000000000aa; - i = std::is_same::value ? 0x7fc000aa : static_cast(double_nan); - T d = type_punning(i); - REALM_ASSERT_DEBUG(std::isnan(d)); - REALM_ASSERT_DEBUG(!is_signaling(d)); - return d; - } - - /// Takes a NaN as argument and returns whether or not it's signaling - template - static bool is_signaling(T v) - { - REALM_ASSERT(std::isnan(static_cast(v))); - typename std::conditional::value, uint32_t, uint64_t>::type i; - size_t signal_bit = std::is_same::value ? 22 : 51; // If this bit is set, it's quiet - i = type_punning(v); - return !(i & (1ull << signal_bit)); - } - - /// Converts any signaling or quiet NaN to their their respective bit patterns that are used on x64 gcc+clang, - /// ARM clang and x64 Java. - template - static T to_realm(T v) - { - if (std::isnan(static_cast(v))) { - typename std::conditional::value, uint32_t, uint64_t>::type i; - if (std::is_same::value) { - i = is_signaling(v) ? 0x7fa00000 : 0x7fc00000; - } - else { - i = static_cast(is_signaling(v) ? 0x7ff4000000000000 : 0x7ff8000000000000); - } - return type_punning(i); - } - else { - return v; - } - } -}; - -template -OS& operator<<(OS& os, const null&) -{ - os << "(null)"; - return os; -} - -} // namespace realm - -#endif // REALM_NULL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/olddatetime.hpp b/Lesson14/Pods/Realm/include/core/realm/olddatetime.hpp deleted file mode 100644 index b662899..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/olddatetime.hpp +++ /dev/null @@ -1,157 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_DATETIME_HPP -#define REALM_DATETIME_HPP - -#include -#include - -namespace realm { - - -class OldDateTime { -public: - OldDateTime() noexcept - : m_time(0) - { - } - - /// Construct from the number of seconds since Jan 1 00:00:00 UTC - /// 1970. - /// FIXME: See if we can make this private again. Required by query_expression.hpp - OldDateTime(int_fast64_t d) noexcept - : m_time(d) - { - } - - /// Return the time as seconds since Jan 1 00:00:00 UTC 1970. - int_fast64_t get_olddatetime() const noexcept - { - return m_time; - } - - friend bool operator==(const OldDateTime&, const OldDateTime&) noexcept; - friend bool operator!=(const OldDateTime&, const OldDateTime&) noexcept; - friend bool operator<(const OldDateTime&, const OldDateTime&) noexcept; - friend bool operator<=(const OldDateTime&, const OldDateTime&) noexcept; - friend bool operator>(const OldDateTime&, const OldDateTime&) noexcept; - friend bool operator>=(const OldDateTime&, const OldDateTime&) noexcept; - - /// Construct from broken down local time. - /// - /// \note This constructor uses std::mktime() to convert the - /// specified local time to seconds since the Epoch, that is, the - /// result depends on the current globally specified time zone - /// setting. - /// - /// \param year The year (the minimum valid value is 1970). - /// - /// \param month The month in the range [1, 12]. - /// - /// \param day The day of the month in the range [1, 31]. - /// - /// \param hours Hours since midnight in the range [0, 23]. - /// - /// \param minutes Minutes after the hour in the range [0, 59]. - /// - /// \param seconds Seconds after the minute in the range [0, - /// 60]. Note that the range allows for leap seconds. - OldDateTime(int year, int month, int day, int hours = 0, int minutes = 0, int seconds = 0); - - template - friend std::basic_ostream& operator<<(std::basic_ostream& out, const OldDateTime&); - - // This is used by query_expression.hpp to generalize its templates and simplify the code *alot*; it is needed - // because OldDateTime is internally stored in an int64_t column. - operator int_fast64_t() noexcept; - -private: - int_fast64_t m_time; // Seconds since Jan 1 00:00:00 UTC 1970. - static std::time_t assemble(int year, int month, int day, int hours, int minutes, int seconds); - template - friend class Value; -}; - - -// Implementation: - -inline bool operator==(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time == b.m_time; -} - -inline bool operator!=(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time != b.m_time; -} - -inline bool operator<(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time < b.m_time; -} - -inline bool operator<=(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time <= b.m_time; -} - -inline bool operator>(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time > b.m_time; -} - -inline bool operator>=(const OldDateTime& a, const OldDateTime& b) noexcept -{ - return a.m_time >= b.m_time; -} - -inline OldDateTime::operator int_fast64_t() noexcept -{ - return m_time; -} - -inline OldDateTime::OldDateTime(int year, int month, int day, int hours, int minutes, int seconds) - : m_time(assemble(year, month, day, hours, minutes, seconds)) -{ -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const OldDateTime& d) -{ - out << "OldDateTime(" << d.m_time << ")"; - return out; -} - -inline std::time_t OldDateTime::assemble(int year, int month, int day, int hours, int minutes, int seconds) -{ - std::tm local_time; - local_time.tm_year = year - 1900; - local_time.tm_mon = month - 1; - local_time.tm_mday = day; - local_time.tm_hour = hours; - local_time.tm_min = minutes; - local_time.tm_sec = seconds; - local_time.tm_isdst = -1; - return std::mktime(&local_time); -} - - -} // namespace realm - -#endif // REALM_DATETIME_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/owned_data.hpp b/Lesson14/Pods/Realm/include/core/realm/owned_data.hpp deleted file mode 100644 index c707f9d..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/owned_data.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_OWNED_DATA_HPP -#define REALM_OWNED_DATA_HPP - -#include - -#include -#include - -namespace realm { - -/// A chunk of owned data. -class OwnedData { -public: - /// Construct a null reference. - OwnedData() noexcept - { - } - - /// If \a data_to_copy is 'null', \a data_size must be zero. - OwnedData(const char* data_to_copy, size_t data_size) - : m_size(data_size) - { - REALM_ASSERT_DEBUG(data_to_copy || data_size == 0); - if (data_to_copy) { - m_data = std::unique_ptr(new char[data_size]); - memcpy(m_data.get(), data_to_copy, data_size); - } - } - - /// If \a unique_data is 'null', \a data_size must be zero. - OwnedData(std::unique_ptr unique_data, size_t data_size) noexcept - : m_data(std::move(unique_data)) - , m_size(data_size) - { - REALM_ASSERT_DEBUG(m_data || m_size == 0); - } - - OwnedData(const OwnedData& other) - : OwnedData(other.m_data.get(), other.m_size) - { - } - OwnedData& operator=(const OwnedData& other); - - OwnedData(OwnedData&&) = default; - OwnedData& operator=(OwnedData&&) = default; - - const char* data() const - { - return m_data.get(); - } - size_t size() const - { - return m_size; - } - -private: - std::unique_ptr m_data; - size_t m_size = 0; -}; - -inline OwnedData& OwnedData::operator=(const OwnedData& other) -{ - if (this != &other) { - if (other.m_data) { - m_data = std::unique_ptr(new char[other.m_size]); - memcpy(m_data.get(), other.m_data.get(), other.m_size); - } - else { - m_data = nullptr; - } - m_size = other.m_size; - } - return *this; -} - -} // namespace realm - -#endif // REALM_OWNED_DATA_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp deleted file mode 100644 index 4edd5c2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/collection_operator_expression.hpp +++ /dev/null @@ -1,226 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_COLLECTION_OPERATOR_EXPRESSION_HPP -#define REALM_COLLECTION_OPERATOR_EXPRESSION_HPP - -#include "property_expression.hpp" -#include "parser.hpp" -#include "parser_utils.hpp" - -#include - -namespace realm { -namespace parser { - -template -struct CollectionOperatorGetter; - -template -struct CollectionOperatorExpression -{ - static constexpr parser::Expression::KeyPathOp operation_type = OpType; - std::function table_getter; - PropertyExpression pe; - size_t post_link_col_ndx; - DataType post_link_col_type; - - CollectionOperatorExpression(PropertyExpression&& exp, std::string suffix_path, parser::KeyPathMapping& mapping) - : pe(std::move(exp)) - , post_link_col_ndx(realm::not_found) - { - table_getter = std::bind(&PropertyExpression::table_getter, pe); - - const bool requires_suffix_path = !(OpType == parser::Expression::KeyPathOp::SizeString - || OpType == parser::Expression::KeyPathOp::SizeBinary - || OpType == parser::Expression::KeyPathOp::Count - || OpType == parser::Expression::KeyPathOp::BacklinkCount); - - if (requires_suffix_path) { - Table* pre_link_table = pe.table_getter(); - REALM_ASSERT(pre_link_table); - StringData list_property_name; - if (pe.dest_type_is_backlink()) { - list_property_name = "linking object"; - } else { - list_property_name = pre_link_table->get_column_name(pe.get_dest_ndx()); - } - realm_precondition(pe.get_dest_type() == type_LinkList || pe.dest_type_is_backlink(), - util::format("The '%1' operation must be used on a list property, but '%2' is not a list", - util::collection_operator_to_str(OpType), list_property_name)); - - ConstTableRef post_link_table; - if (pe.dest_type_is_backlink()) { - post_link_table = pe.get_dest_table(); - } else { - post_link_table = pe.get_dest_table()->get_link_target(pe.get_dest_ndx()); - } - REALM_ASSERT(post_link_table); - StringData printable_post_link_table_name = get_printable_table_name(*post_link_table); - - KeyPath suffix_key_path = key_path_from_string(suffix_path); - - realm_precondition(suffix_path.size() > 0 && suffix_key_path.size() > 0, - util::format("A property from object '%1' must be provided to perform operation '%2'", - printable_post_link_table_name, util::collection_operator_to_str(OpType))); - size_t index = 0; - KeyPathElement element = mapping.process_next_path(post_link_table, suffix_key_path, index); - - realm_precondition(suffix_key_path.size() == 1, - util::format("Unable to use '%1' because collection aggreate operations are only supported " - "for direct properties at this time", suffix_path)); - - post_link_col_ndx = element.col_ndx; - post_link_col_type = element.col_type; - } - else { // !requires_suffix_path - if (!pe.link_chain.empty()) { - post_link_col_type = pe.get_dest_type(); - } - - realm_precondition(suffix_path.empty(), - util::format("An extraneous property '%1' was found for operation '%2'", - suffix_path, util::collection_operator_to_str(OpType))); - } - } - template - auto value_of_type_for_query() const - { - return CollectionOperatorGetter::convert(*this); - } -}; - - -// Certain operations are disabled for some types (eg. a sum of timestamps is invalid). -// The operations that are supported have a specialisation with std::enable_if for that type below -// any type/operation combination that is not specialised will get the runtime error from the following -// default implementation. The return type is just a dummy to make things compile. -template -struct CollectionOperatorGetter { - static Columns convert(const CollectionOperatorExpression& op) { - throw std::runtime_error(util::format("Predicate error: comparison of type '%1' with result of '%2' is not supported.", - type_to_str(), - collection_operator_to_str(op.operation_type))); - } -}; - -template -struct CollectionOperatorGetter::value> >{ - static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).min(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).min(); - } - } -}; - -template -struct CollectionOperatorGetter::value> >{ - static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).max(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).max(); - } - } -}; - -template -struct CollectionOperatorGetter::value> >{ - static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).sum(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).sum(); - } - } -}; - -template -struct CollectionOperatorGetter::value> >{ - static SubColumnAggregate > convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).average(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template column(expr.post_link_col_ndx).average(); - } - } -}; - -template -struct CollectionOperatorGetter::value> >{ - static LinkCount convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).count(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).count(); - } - } -}; - - -template -struct CollectionOperatorGetter::value> >{ - static BacklinkCount convert(const CollectionOperatorExpression& expr) - { - if (expr.pe.link_chain.empty() || expr.pe.get_dest_ndx() == realm::npos) { - // here we are operating on the current table from a "@links.@count" query with no link keypath prefix - return expr.table_getter()->template get_backlink_count(); - } else { - if (expr.pe.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.pe.get_dest_table(), expr.pe.get_dest_ndx()).template backlink_count(); - } else { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).template backlink_count(); - } - } - } -}; - - -template <> -struct CollectionOperatorGetter{ - static SizeOperator > convert(const CollectionOperatorExpression& expr) - { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).size(); - } -}; - -template <> -struct CollectionOperatorGetter{ - static SizeOperator > convert(const CollectionOperatorExpression& expr) - { - return expr.table_getter()->template column(expr.pe.get_dest_ndx()).size(); - } -}; - -} // namespace parser -} // namespace realm - -#endif // REALM_COLLECTION_OPERATOR_EXPRESSION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/expression_container.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/expression_container.hpp deleted file mode 100644 index 7e596b9..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/expression_container.hpp +++ /dev/null @@ -1,79 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_EXPRESSION_CONTAINER_HPP -#define REALM_EXPRESSION_CONTAINER_HPP - -#include - -#include "collection_operator_expression.hpp" -#include "parser.hpp" -#include "property_expression.hpp" -#include "query_builder.hpp" -#include "subquery_expression.hpp" -#include "value_expression.hpp" - -namespace realm { -namespace parser { - -class ExpressionContainer -{ -public: - ExpressionContainer(Query& query, const parser::Expression& e, query_builder::Arguments& args, parser::KeyPathMapping& mapping); - - bool is_null(); - - PropertyExpression& get_property(); - ValueExpression& get_value(); - CollectionOperatorExpression& get_min(); - CollectionOperatorExpression& get_max(); - CollectionOperatorExpression& get_sum(); - CollectionOperatorExpression& get_avg(); - CollectionOperatorExpression& get_count(); - CollectionOperatorExpression& get_backlink_count(); - CollectionOperatorExpression& get_size_string(); - CollectionOperatorExpression& get_size_binary(); - SubqueryExpression& get_subexpression(); - - DataType check_type_compatibility(DataType type); - DataType get_comparison_type(ExpressionContainer& rhs); - - enum class ExpressionInternal - { - exp_Value, - exp_Property, - exp_OpMin, - exp_OpMax, - exp_OpSum, - exp_OpAvg, - exp_OpCount, - exp_OpSizeString, - exp_OpSizeBinary, - exp_OpBacklinkCount, - exp_SubQuery - }; - - ExpressionInternal type; -private: - util::Any storage; -}; - -} // namespace parser -} // namespace realm - -#endif // REALM_EXPRESSION_CONTAINER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp deleted file mode 100644 index 01ea65f..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/keypath_mapping.hpp +++ /dev/null @@ -1,79 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_KEYPATH_MAPPING_HPP -#define REALM_KEYPATH_MAPPING_HPP - -#include - -#include "parser_utils.hpp" - -#include -#include - -namespace realm { -namespace parser { - -struct KeyPathElement -{ - ConstTableRef table; - size_t col_ndx; - DataType col_type; - bool is_backlink; -}; - -class BacklinksRestrictedError : public std::runtime_error { -public: - BacklinksRestrictedError(const std::string& msg) : std::runtime_error(msg) {} - /// runtime_error::what() returns the msg provided in the constructor. -}; - -struct TableAndColHash { - std::size_t operator () (const std::pair &p) const; -}; - - -// This class holds state which allows aliasing variable names in key paths used in queries. -// It is used to allow variable naming in subqueries such as 'SUBQUERY(list, $obj, $obj.intCol = 5).@count' -// It can also be used to allow querying named backlinks if bindings provide the mappings themselves. -class KeyPathMapping -{ -public: - KeyPathMapping(); - // returns true if added, false if duplicate key already exists - bool add_mapping(ConstTableRef table, std::string name, std::string alias); - void remove_mapping(ConstTableRef table, std::string name); - bool has_mapping(ConstTableRef table, std::string name); - KeyPathElement process_next_path(ConstTableRef table, KeyPath& path, size_t& index); - void set_allow_backlinks(bool allow); - bool backlinks_allowed() const - { - return m_allow_backlinks; - } - void set_backlink_class_prefix(std::string prefix); - static Table* table_getter(TableRef table, const std::vector& links); -protected: - bool m_allow_backlinks; - std::string m_backlink_class_prefix; - std::unordered_map, std::string, TableAndColHash> m_mapping; -}; - -} // namespace parser -} // namespace realm - -#endif // REALM_KEYPATH_MAPPING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/parser.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/parser.hpp deleted file mode 100644 index f04edc2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/parser.hpp +++ /dev/null @@ -1,147 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_PARSER_HPP -#define REALM_PARSER_HPP - -#include -#include -#include -#include - -namespace realm { - -namespace parser { - -struct Predicate; - -struct Expression -{ - enum class Type { None, Number, String, KeyPath, Argument, True, False, Null, Timestamp, Base64, SubQuery } type; - enum class KeyPathOp { None, Min, Max, Avg, Sum, Count, SizeString, SizeBinary, BacklinkCount } collection_op; - std::string s; - std::vector time_inputs; - std::string op_suffix; - std::string subquery_path, subquery_var; - std::shared_ptr subquery; - Expression(Type t = Type::None, std::string input = "") : type(t), collection_op(KeyPathOp::None), s(input) {} - Expression(std::vector&& timestamp) : type(Type::Timestamp), collection_op(KeyPathOp::None), time_inputs(timestamp) {} - Expression(std::string prefix, KeyPathOp op, std::string suffix) : type(Type::KeyPath), collection_op(op), s(prefix), op_suffix(suffix) {} -}; - -struct Predicate -{ - enum class Type - { - Comparison, - Or, - And, - True, - False - } type = Type::And; - - enum class Operator - { - None, - Equal, - NotEqual, - LessThan, - LessThanOrEqual, - GreaterThan, - GreaterThanOrEqual, - BeginsWith, - EndsWith, - Contains, - Like, - In - }; - - enum class OperatorOption - { - None, - CaseInsensitive, - }; - - enum class ComparisonType - { - Unspecified, - Any, - All, - None, - }; - - struct Comparison - { - Operator op = Operator::None; - OperatorOption option = OperatorOption::None; - Expression expr[2] = {{Expression::Type::None, ""}, {Expression::Type::None, ""}}; - ComparisonType compare_type = ComparisonType::Unspecified; - }; - - struct Compound - { - std::vector sub_predicates; - }; - - Comparison cmpr; - Compound cpnd; - - bool negate = false; - - Predicate(Type t, bool n = false) : type(t), negate(n) {} -}; - -struct DescriptorOrderingState -{ - struct PropertyState - { - std::string key_path; - std::string table_name; - bool ascending; - }; - struct SingleOrderingState - { - std::vector properties; - size_t limit; - enum class DescriptorType { Sort, Distinct, Limit, Include } type; - }; - std::vector orderings; -}; - -struct ParserResult -{ - ParserResult(Predicate p, DescriptorOrderingState o) - : predicate(p) - , ordering(o) {} - Predicate predicate; - DescriptorOrderingState ordering; -}; - -ParserResult parse(const char* query); // assumes c-style null termination -ParserResult parse(const std::string& query); -ParserResult parse(const realm::StringData& query); - -DescriptorOrderingState parse_include_path(const realm::StringData& path); - -// run the analysis tool to check for cycles in the grammar -// returns the number of problems found and prints some info to std::cout -size_t analyze_grammar(); -} -} - -#endif // REALM_PARSER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/parser_utils.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/parser_utils.hpp deleted file mode 100644 index 12b79c9..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/parser_utils.hpp +++ /dev/null @@ -1,87 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_PARSER_UTILS_HPP -#define REALM_PARSER_UTILS_HPP - -#include -#include -#include "parser.hpp" - -#include -#include - -namespace realm { - -class Table; -class Timestamp; -struct Link; - -namespace util { - -// check a precondition and throw an exception if it is not met -// this should be used iff the condition being false indicates a bug in the caller -// of the function checking its preconditions -#define realm_precondition(condition, message) if (!REALM_LIKELY(condition)) { throw std::logic_error(message); } - - -template -const char* type_to_str(); - -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); -template <> -const char* type_to_str(); - -const char* data_type_to_str(DataType type); -const char* collection_operator_to_str(parser::Expression::KeyPathOp op); -const char* comparison_type_to_str(parser::Predicate::ComparisonType type); - -using KeyPath = std::vector; -KeyPath key_path_from_string(const std::string &s); -std::string key_path_to_string(const KeyPath& keypath); -StringData get_printable_table_name(StringData name); -StringData get_printable_table_name(const Table& table); - -template -T stot(std::string const& s) { - std::istringstream iss(s); - T value; - iss >> value; - if (iss.fail()) { - throw std::invalid_argument(util::format("Cannot convert string '%1'", s)); - } - return value; -} - -} // namespace utils -} // namespace realm - -#endif // REALM_PARSER_UTILS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/property_expression.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/property_expression.hpp deleted file mode 100644 index 8f4a7ec..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/property_expression.hpp +++ /dev/null @@ -1,78 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_PROPERTY_EXPRESSION_HPP -#define REALM_PROPERTY_EXPRESSION_HPP - -#include -#include -#include - -namespace realm { -namespace parser { - -struct PropertyExpression -{ - Query &query; - std::vector link_chain; - DataType get_dest_type() const; - size_t get_dest_ndx() const; - ConstTableRef get_dest_table() const; - bool dest_type_is_backlink() const; - - PropertyExpression(Query &q, const std::string &key_path_string, parser::KeyPathMapping& mapping); - - Table* table_getter() const; - - template - auto value_of_type_for_query() const - { - return this->table_getter()->template column(get_dest_ndx()); - } -}; - -inline DataType PropertyExpression::get_dest_type() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().col_type; -} - -inline bool PropertyExpression::dest_type_is_backlink() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().is_backlink; -} - -inline size_t PropertyExpression::get_dest_ndx() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().col_ndx; -} - -inline ConstTableRef PropertyExpression::get_dest_table() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().table; -} - - -} // namespace parser -} // namespace realm - -#endif // REALM_PROPERTY_EXPRESSION_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/query_builder.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/query_builder.hpp deleted file mode 100644 index 34a72b6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/query_builder.hpp +++ /dev/null @@ -1,158 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_QUERY_BUILDER_HPP -#define REALM_QUERY_BUILDER_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { -class Query; -class Realm; -class Table; -template class BasicRowExpr; -using RowExpr = BasicRowExpr
; - -namespace parser { - struct Predicate; - struct DescriptorOrderingState; -} - -namespace query_builder { -class Arguments; - -void apply_predicate(Query& query, const parser::Predicate& predicate, Arguments& arguments, - parser::KeyPathMapping mapping = parser::KeyPathMapping()); - -void apply_ordering(DescriptorOrdering& ordering, ConstTableRef target, const parser::DescriptorOrderingState& state, - Arguments& arguments, parser::KeyPathMapping mapping = parser::KeyPathMapping()); -void apply_ordering(DescriptorOrdering& ordering, ConstTableRef target, const parser::DescriptorOrderingState& state, - parser::KeyPathMapping mapping = parser::KeyPathMapping()); - - -struct AnyContext -{ - template - T unbox(const util::Any& wrapper) { - return util::any_cast(wrapper); - } - bool is_null(const util::Any& wrapper) { - if (!wrapper.has_value()) { - return true; - } - if (wrapper.type() == typeid(realm::null)) { - return true; - } - return false; - } -}; - -class Arguments { -public: - virtual bool bool_for_argument(size_t argument_index) = 0; - virtual long long long_for_argument(size_t argument_index) = 0; - virtual float float_for_argument(size_t argument_index) = 0; - virtual double double_for_argument(size_t argument_index) = 0; - virtual StringData string_for_argument(size_t argument_index) = 0; - virtual BinaryData binary_for_argument(size_t argument_index) = 0; - virtual Timestamp timestamp_for_argument(size_t argument_index) = 0; - virtual size_t object_index_for_argument(size_t argument_index) = 0; - virtual bool is_argument_null(size_t argument_index) = 0; - // dynamic conversion space with lifetime tied to this - // it is used for storing literal binary/string data - std::vector buffer_space; -}; - -template -class ArgumentConverter : public Arguments { -public: - ArgumentConverter(ContextType& context, const ValueType* arguments, size_t count) - : m_ctx(context) - , m_arguments(arguments) - , m_count(count) - {} - - bool bool_for_argument(size_t i) override { return get(i); } - long long long_for_argument(size_t i) override { return get(i); } - float float_for_argument(size_t i) override { return get(i); } - double double_for_argument(size_t i) override { return get(i); } - StringData string_for_argument(size_t i) override { return get(i); } - BinaryData binary_for_argument(size_t i) override { return get(i); } - Timestamp timestamp_for_argument(size_t i) override { return get(i); } - size_t object_index_for_argument(size_t i) override { return get(i).get_index(); } - bool is_argument_null(size_t i) override { return m_ctx.is_null(at(i)); } - -private: - ContextType& m_ctx; - const ValueType* m_arguments; - size_t m_count; - - const ValueType& at(size_t index) const - { - if (index >= m_count) { - std::string error_message; - if (m_count) { - error_message = util::format("Request for argument at index %1 but only %2 argument%3 provided", index, m_count, m_count == 1 ? " is" : "s are"); - } else { - error_message = util::format("Request for argument at index %1 but no arguments are provided", index); - } - throw std::out_of_range(error_message); - } - return m_arguments[index]; - } - - template - T get(size_t index) const - { - return m_ctx.template unbox(at(index)); - } -}; - -class NoArgsError : public std::runtime_error { -public: - NoArgsError() : std::runtime_error("Attempt to retreive an argument when no arguments were given") {} -}; - -class NoArguments : public Arguments { -public: - bool bool_for_argument(size_t) { throw NoArgsError(); } - long long long_for_argument(size_t) { throw NoArgsError(); } - float float_for_argument(size_t) { throw NoArgsError(); } - double double_for_argument(size_t) { throw NoArgsError(); } - StringData string_for_argument(size_t) { throw NoArgsError(); } - BinaryData binary_for_argument(size_t) { throw NoArgsError(); } - Timestamp timestamp_for_argument(size_t) { throw NoArgsError(); } - size_t object_index_for_argument(size_t) { throw NoArgsError(); } - bool is_argument_null(size_t) { throw NoArgsError(); } -}; - -} // namespace query_builder -} // namespace realm - -#endif // REALM_QUERY_BUILDER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/subquery_expression.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/subquery_expression.hpp deleted file mode 100644 index 20c04d1..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/subquery_expression.hpp +++ /dev/null @@ -1,112 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_SUBQUERY_EXPRESSION_HPP -#define REALM_SUBQUERY_EXPRESSION_HPP - -#include -#include -#include -#include - -#include "parser_utils.hpp" - -namespace realm { -namespace parser { - -template -struct SubqueryGetter; - -struct SubqueryExpression -{ - std::string var_name; - Query &query; - Query subquery; - std::vector link_chain; - DataType get_dest_type() const; - size_t get_dest_ndx() const; - ConstTableRef get_dest_table() const; - bool dest_type_is_backlink() const; - - - SubqueryExpression(Query &q, const std::string &key_path_string, const std::string &variable_name, parser::KeyPathMapping &mapping); - Query& get_subquery(); - - Table* table_getter() const; - - template - auto value_of_type_for_query() const - { - return SubqueryGetter::convert(*this); - } -}; - -inline DataType SubqueryExpression::get_dest_type() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().col_type; -} - -inline bool SubqueryExpression::dest_type_is_backlink() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().is_backlink; -} - -inline size_t SubqueryExpression::get_dest_ndx() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().col_ndx; -} - -inline ConstTableRef SubqueryExpression::get_dest_table() const -{ - REALM_ASSERT_DEBUG(link_chain.size() > 0); - return link_chain.back().table; -} - -// Certain operations are disabled for some types (eg. a sum of timestamps is invalid). -// The operations that are supported have a specialisation with std::enable_if for that type below -// any type/operation combination that is not specialised will get the runtime error from the following -// default implementation. The return type is just a dummy to make things compile. -template -struct SubqueryGetter { - static Columns convert(const SubqueryExpression&) { - throw std::runtime_error(util::format("Predicate error: comparison of type '%1' with result of a subquery count is not supported.", - type_to_str())); - } -}; - -template -struct SubqueryGetter::value> >{ - static SubQueryCount convert(const SubqueryExpression& expr) - { - if (expr.dest_type_is_backlink()) { - return expr.table_getter()->template column(*expr.get_dest_table(), expr.get_dest_ndx(), expr.subquery).count(); - } else { - return expr.table_getter()->template column(expr.get_dest_ndx(), expr.subquery).count(); - } - } -}; - -} // namespace parser -} // namespace realm - -#endif // REALM_SUBQUERY_EXPRESSION_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/parser/value_expression.hpp b/Lesson14/Pods/Realm/include/core/realm/parser/value_expression.hpp deleted file mode 100644 index 09ac257..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/parser/value_expression.hpp +++ /dev/null @@ -1,43 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2015 Realm Inc. -// -// 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 REALM_VALUE_EXPRESSION_HPP -#define REALM_VALUE_EXPRESSION_HPP - -#include "parser.hpp" -#include "query_builder.hpp" - -namespace realm { -namespace parser { - -struct ValueExpression -{ - const parser::Expression* value; - query_builder::Arguments* arguments; - std::function
table_getter; - - ValueExpression(Query& query, query_builder::Arguments* args, const parser::Expression* v); - bool is_null(); - template - RetType value_of_type_for_query(); -}; - -} // namespace parser -} // namespace realm - -#endif // REALM_VALUE_EXPRESSION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/query.hpp b/Lesson14/Pods/Realm/include/core/realm/query.hpp deleted file mode 100644 index 6d9e5a3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/query.hpp +++ /dev/null @@ -1,483 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_QUERY_HPP -#define REALM_QUERY_HPP - -#include -#include -#include -#include -#include -#include - -#define REALM_MULTITHREAD_QUERY 0 - -#if REALM_MULTITHREAD_QUERY -// FIXME: Use our C++ thread abstraction API since it provides a much -// higher level of encapsulation and safety. -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - - -// Pre-declarations -class ParentNode; -class Table; -class TableView; -class TableViewBase; -class ConstTableView; -class Array; -class Expression; -class SequentialGetterBase; -class Group; - -namespace metrics { -class QueryInfo; -} - -struct QueryGroup { - enum class State { - Default, - OrCondition, - OrConditionChildren, - }; - - QueryGroup() = default; - - QueryGroup(const QueryGroup&); - QueryGroup& operator=(const QueryGroup&); - - QueryGroup(QueryGroup&&) = default; - QueryGroup& operator=(QueryGroup&&) = default; - - QueryGroup(const QueryGroup&, QueryNodeHandoverPatches&); - - std::unique_ptr m_root_node; - - bool m_pending_not = false; - size_t m_subtable_column = not_found; - State m_state = State::Default; -}; - -class Query final { -public: - Query(const Table& table, TableViewBase* tv = nullptr); - Query(const Table& table, std::unique_ptr); - Query(const Table& table, const LinkViewRef& lv); - Query(); - Query(std::unique_ptr); - ~Query() noexcept; - - Query(const Query& copy); - Query& operator=(const Query& source); - - Query(Query&&); - Query& operator=(Query&&); - - // Find links that point to a specific target row - Query& links_to(size_t column_ndx, const ConstRow& target_row); - // Find links that point to specific target rows - Query& links_to(size_t column_ndx, const std::vector& target_row); - - // Conditions: null - Query& equal(size_t column_ndx, null); - Query& not_equal(size_t column_ndx, null); - - // Conditions: int64_t - Query& equal(size_t column_ndx, int64_t value); - Query& not_equal(size_t column_ndx, int64_t value); - Query& greater(size_t column_ndx, int64_t value); - Query& greater_equal(size_t column_ndx, int64_t value); - Query& less(size_t column_ndx, int64_t value); - Query& less_equal(size_t column_ndx, int64_t value); - Query& between(size_t column_ndx, int64_t from, int64_t to); - - // Conditions: int (we need those because conversion from '1234' is ambiguous with float/double) - Query& equal(size_t column_ndx, int value); - Query& not_equal(size_t column_ndx, int value); - Query& greater(size_t column_ndx, int value); - Query& greater_equal(size_t column_ndx, int value); - Query& less(size_t column_ndx, int value); - Query& less_equal(size_t column_ndx, int value); - Query& between(size_t column_ndx, int from, int to); - - // Conditions: 2 int columns - Query& equal_int(size_t column_ndx1, size_t column_ndx2); - Query& not_equal_int(size_t column_ndx1, size_t column_ndx2); - Query& greater_int(size_t column_ndx1, size_t column_ndx2); - Query& less_int(size_t column_ndx1, size_t column_ndx2); - Query& greater_equal_int(size_t column_ndx1, size_t column_ndx2); - Query& less_equal_int(size_t column_ndx1, size_t column_ndx2); - - // Conditions: float - Query& equal(size_t column_ndx, float value); - Query& not_equal(size_t column_ndx, float value); - Query& greater(size_t column_ndx, float value); - Query& greater_equal(size_t column_ndx, float value); - Query& less(size_t column_ndx, float value); - Query& less_equal(size_t column_ndx, float value); - Query& between(size_t column_ndx, float from, float to); - - // Conditions: 2 float columns - Query& equal_float(size_t column_ndx1, size_t column_ndx2); - Query& not_equal_float(size_t column_ndx1, size_t column_ndx2); - Query& greater_float(size_t column_ndx1, size_t column_ndx2); - Query& greater_equal_float(size_t column_ndx1, size_t column_ndx2); - Query& less_float(size_t column_ndx1, size_t column_ndx2); - Query& less_equal_float(size_t column_ndx1, size_t column_ndx2); - - // Conditions: double - Query& equal(size_t column_ndx, double value); - Query& not_equal(size_t column_ndx, double value); - Query& greater(size_t column_ndx, double value); - Query& greater_equal(size_t column_ndx, double value); - Query& less(size_t column_ndx, double value); - Query& less_equal(size_t column_ndx, double value); - Query& between(size_t column_ndx, double from, double to); - - // Conditions: 2 double columns - Query& equal_double(size_t column_ndx1, size_t column_ndx2); - Query& not_equal_double(size_t column_ndx1, size_t column_ndx2); - Query& greater_double(size_t column_ndx1, size_t column_ndx2); - Query& greater_equal_double(size_t column_ndx1, size_t column_ndx2); - Query& less_double(size_t column_ndx1, size_t column_ndx2); - Query& less_equal_double(size_t column_ndx1, size_t column_ndx2); - - // Conditions: timestamp - Query& equal(size_t column_ndx, Timestamp value); - Query& not_equal(size_t column_ndx, Timestamp value); - Query& greater(size_t column_ndx, Timestamp value); - Query& greater_equal(size_t column_ndx, Timestamp value); - Query& less_equal(size_t column_ndx, Timestamp value); - Query& less(size_t column_ndx, Timestamp value); - - // Conditions: size - Query& size_equal(size_t column_ndx, int64_t value); - Query& size_not_equal(size_t column_ndx, int64_t value); - Query& size_greater(size_t column_ndx, int64_t value); - Query& size_greater_equal(size_t column_ndx, int64_t value); - Query& size_less_equal(size_t column_ndx, int64_t value); - Query& size_less(size_t column_ndx, int64_t value); - Query& size_between(size_t column_ndx, int64_t from, int64_t to); - - // Conditions: bool - Query& equal(size_t column_ndx, bool value); - - // Conditions: date - Query& equal_olddatetime(size_t column_ndx, OldDateTime value) - { - return equal(column_ndx, int64_t(value.get_olddatetime())); - } - Query& not_equal_olddatetime(size_t column_ndx, OldDateTime value) - { - return not_equal(column_ndx, int64_t(value.get_olddatetime())); - } - Query& greater_olddatetime(size_t column_ndx, OldDateTime value) - { - return greater(column_ndx, int64_t(value.get_olddatetime())); - } - Query& greater_equal_olddatetime(size_t column_ndx, OldDateTime value) - { - return greater_equal(column_ndx, int64_t(value.get_olddatetime())); - } - Query& less_olddatetime(size_t column_ndx, OldDateTime value) - { - return less(column_ndx, int64_t(value.get_olddatetime())); - } - Query& less_equal_olddatetime(size_t column_ndx, OldDateTime value) - { - return less_equal(column_ndx, int64_t(value.get_olddatetime())); - } - Query& between_olddatetime(size_t column_ndx, OldDateTime from, OldDateTime to) - { - return between(column_ndx, int64_t(from.get_olddatetime()), int64_t(to.get_olddatetime())); - } - - // Conditions: strings - Query& equal(size_t column_ndx, StringData value, bool case_sensitive = true); - Query& not_equal(size_t column_ndx, StringData value, bool case_sensitive = true); - Query& begins_with(size_t column_ndx, StringData value, bool case_sensitive = true); - Query& ends_with(size_t column_ndx, StringData value, bool case_sensitive = true); - Query& contains(size_t column_ndx, StringData value, bool case_sensitive = true); - Query& like(size_t column_ndx, StringData value, bool case_sensitive = true); - - // These are shortcuts for equal(StringData(c_str)) and - // not_equal(StringData(c_str)), and are needed to avoid unwanted - // implicit conversion of char* to bool. - Query& equal(size_t column_ndx, const char* c_str, bool case_sensitive = true); - Query& not_equal(size_t column_ndx, const char* c_str, bool case_sensitive = true); - - // Conditions: binary data - Query& equal(size_t column_ndx, BinaryData value, bool case_sensitive = true); - Query& not_equal(size_t column_ndx, BinaryData value, bool case_sensitive = true); - Query& begins_with(size_t column_ndx, BinaryData value, bool case_sensitive = true); - Query& ends_with(size_t column_ndx, BinaryData value, bool case_sensitive = true); - Query& contains(size_t column_ndx, BinaryData value, bool case_sensitive = true); - Query& like(size_t column_ndx, BinaryData b, bool case_sensitive = true); - - // Negation - Query& Not(); - - // Grouping - Query& group(); - Query& end_group(); - Query& subtable(size_t column); - Query& end_subtable(); - Query& Or(); - - Query& and_query(const Query& q); - Query& and_query(Query&& q); - Query operator||(const Query& q); - Query operator&&(const Query& q); - Query operator!(); - - - // Searching - size_t find(size_t begin_at_table_row = size_t(0)); - TableView find_all(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)); - - // Aggregates - size_t count(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; - - TableView find_all(const DescriptorOrdering& descriptor); - size_t count(const DescriptorOrdering& descriptor); - - int64_t sum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - double average_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - int64_t maximum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - int64_t minimum_int(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - double sum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - double average_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - float maximum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - float minimum_float(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - double sum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - double average_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - double maximum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - double minimum_double(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1), size_t* return_ndx = nullptr) const; - - OldDateTime maximum_olddatetime(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, - size_t end = size_t(-1), size_t limit = size_t(-1), - size_t* return_ndx = nullptr) const; - - OldDateTime minimum_olddatetime(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, - size_t end = size_t(-1), size_t limit = size_t(-1), - size_t* return_ndx = nullptr) const; - - Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)); - - Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)); - - // Deletion - size_t remove(); - -#if REALM_MULTITHREAD_QUERY - // Multi-threading - TableView find_all_multi(size_t start = 0, size_t end = size_t(-1)); - ConstTableView find_all_multi(size_t start = 0, size_t end = size_t(-1)) const; - int set_threads(unsigned int threadcount); -#endif - - const TableRef& get_table() - { - return m_table; - } - - // True if matching rows are guaranteed to be returned in table order. - bool produces_results_in_table_order() const - { - return !m_view; - } - - // Calls sync_if_needed on the restricting view, if present. - // Returns the current version of the table(s) this query depends on, - // or util::none if the query is not associated with a table. - util::Optional sync_view_if_needed() const; - - std::string validate(); - - std::string get_description() const; - std::string get_description(util::serializer::SerialisationState& state) const; - -private: - Query(Table& table, TableViewBase* tv = nullptr); - void create(); - - void init() const; - size_t find_internal(size_t start = 0, size_t end = size_t(-1)) const; - size_t peek_tablerow(size_t row) const; - void handle_pending_not(); - void set_table(TableRef tr); - -public: - using HandoverPatch = QueryHandoverPatch; - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, ConstSourcePayload mode) const - { - patch.reset(new HandoverPatch); - return std::make_unique(*this, *patch, mode); - } - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, MutableSourcePayload mode) - { - patch.reset(new HandoverPatch); - return std::make_unique(*this, *patch, mode); - } - - void apply_and_consume_patch(std::unique_ptr& patch, Group& dest_group) - { - apply_patch(*patch, dest_group); - patch.reset(); - } - - void apply_patch(HandoverPatch& patch, Group& dest_group); - Query(const Query& source, HandoverPatch& patch, ConstSourcePayload mode); - Query(Query& source, HandoverPatch& patch, MutableSourcePayload mode); - -private: - void fetch_descriptor(); - - void add_expression_node(std::unique_ptr); - - template - Query& equal(size_t column_ndx1, size_t column_ndx2); - - template - Query& less(size_t column_ndx1, size_t column_ndx2); - - template - Query& less_equal(size_t column_ndx1, size_t column_ndx2); - - template - Query& greater(size_t column_ndx1, size_t column_ndx2); - - template - Query& greater_equal(size_t column_ndx1, size_t column_ndx2); - - template - Query& not_equal(size_t column_ndx1, size_t column_ndx2); - - template - Query& add_condition(size_t column_ndx, T value); - - template - Query& add_size_condition(size_t column_ndx, int64_t value); - - template - double average(size_t column_ndx, size_t* resultcount = nullptr, size_t start = 0, size_t end = size_t(-1), - size_t limit = size_t(-1)) const; - - template - R aggregate(R (ColClass::*method)(size_t, size_t, size_t, size_t*) const, size_t column_ndx, size_t* resultcount, - size_t start, size_t end, size_t limit, size_t* return_ndx = nullptr) const; - - void aggregate_internal(Action TAction, DataType TSourceColumn, bool nullable, ParentNode* pn, QueryStateBase* st, - size_t start, size_t end, SequentialGetterBase* source_column) const; - - void find_all(TableViewBase& tv, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; - size_t do_count(size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; - void delete_nodes() noexcept; - - bool has_conditions() const - { - return m_groups.size() > 0 && m_groups[0].m_root_node; - } - ParentNode* root_node() const - { - REALM_ASSERT(m_groups.size()); - return m_groups[0].m_root_node.get(); - } - - void add_node(std::unique_ptr); - - friend class Table; - friend class TableViewBase; - friend class metrics::QueryInfo; - - std::string error_code; - - std::vector m_groups; - - // Used to access schema while building query: - std::vector m_subtable_path; - - ConstDescriptorRef m_current_descriptor; - TableRef m_table; - - // points to the base class of the restricting view. If the restricting - // view is a link view, m_source_link_view is non-zero. If it is a table view, - // m_source_table_view is non-zero. - RowIndexes* m_view = nullptr; - - // At most one of these can be non-zero, and if so the non-zero one indicates the restricting view. - LinkViewRef m_source_link_view; // link views are refcounted and shared. - TableViewBase* m_source_table_view = nullptr; // table views are not refcounted, and not owned by the query. - std::unique_ptr m_owned_source_table_view; // <--- except when indicated here -}; - -// Implementation: - -inline Query& Query::equal(size_t column_ndx, const char* c_str, bool case_sensitive) -{ - return equal(column_ndx, StringData(c_str), case_sensitive); -} - -inline Query& Query::not_equal(size_t column_ndx, const char* c_str, bool case_sensitive) -{ - return not_equal(column_ndx, StringData(c_str), case_sensitive); -} - -} // namespace realm - -#endif // REALM_QUERY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/query_conditions.hpp b/Lesson14/Pods/Realm/include/core/realm/query_conditions.hpp deleted file mode 100644 index bc13bbe..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/query_conditions.hpp +++ /dev/null @@ -1,856 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_QUERY_CONDITIONS_HPP -#define REALM_QUERY_CONDITIONS_HPP - -#include -#include - -#include -#include -#include - -namespace realm { - -// Array::VTable only uses the first 4 conditions (enums) in an array of function pointers -enum { cond_Equal, cond_NotEqual, cond_Greater, cond_Less, cond_VTABLE_FINDER_COUNT, cond_None, cond_LeftNotNull }; - -// Quick hack to make "Queries with Integer null columns" able to compile in Visual Studio 2015 which doesn't full -// support sfinae -// (real cause hasn't been investigated yet, cannot exclude that we don't obey c++11 standard) -struct HackClass { - template - bool can_match(A, B, C) - { - REALM_ASSERT(false); - return false; - } - template - bool will_match(A, B, C) - { - REALM_ASSERT(false); - return false; - } -}; - -// Does v2 contain v1? -struct Contains : public HackClass { - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v2.contains(v1); - } - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - return v2.contains(v1); - } - bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const - { - return v2.contains(v1); - } - bool operator()(StringData v1, const std::array &charmap, StringData v2) const - { - return v2.contains(v1, charmap); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "CONTAINS"; - } - - static const int condition = -1; -}; - -// Does v2 contain something like v1 (wildcard matching)? -struct Like : public HackClass { - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v2.like(v1); - } - bool operator()(BinaryData b1, const char*, const char*, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return s2.like(s1); - } - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - return v2.like(v1); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return s2.like(s1); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "LIKE"; - } - - static const int condition = -1; -}; - -// Does v2 begin with v1? -struct BeginsWith : public HackClass { - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v2.begins_with(v1); - } - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - return v2.begins_with(v1); - } - bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const - { - return v2.begins_with(v1); - } - - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "BEGINSWITH"; - } - - static const int condition = -1; -}; - -// Does v2 end with v1? -struct EndsWith : public HackClass { - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v2.ends_with(v1); - } - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - return v2.ends_with(v1); - } - bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const - { - return v2.ends_with(v1); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "ENDSWITH"; - } - - static const int condition = -1; -}; - -struct Equal { - static const int avx = 0x00; // _CMP_EQ_OQ - // bool operator()(const bool v1, const bool v2, bool v1null = false, bool v2null = false) const { return v1 == - // v2; } - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v1 == v2; - } - bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const - { - return v1 == v2; - } - - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - return (v1null && v2null) || (!v1null && !v2null && v1 == v2); - } - static const int condition = cond_Equal; - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - return (v >= lbound && v <= ubound); - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - return (v == 0 && ubound == 0 && lbound == 0); - } - - static std::string description() - { - return "=="; - } -}; - -struct NotEqual { - static const int avx = 0x0B; // _CMP_FALSE_OQ - bool operator()(StringData v1, const char*, const char*, StringData v2, bool = false, bool = false) const - { - return v1 != v2; - } - // bool operator()(BinaryData v1, BinaryData v2, bool = false, bool = false) const { return v1 != v2; } - - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - if (!v1null && !v2null) - return v1 != v2; - - if (v1null && v2null) - return false; - - return true; - } - - static const int condition = cond_NotEqual; - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - return !(v == 0 && ubound == 0 && lbound == 0); - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - return (v > ubound || v < lbound); - } - - template - bool operator()(A, B, C, D) const = delete; - - static std::string description() - { - return "!="; - } -}; - -// Does v2 contain v1? -struct ContainsIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - if (v1.size() == 0 && !v2.is_null()) - return true; - - return search_case_fold(v2, v1_upper, v1_lower, v1.size()) != v2.size(); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - if (v1.size() == 0 && !v2.is_null()) - return true; - - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return search_case_fold(v2, v1_upper.c_str(), v1_lower.c_str(), v1.size()) != v2.size(); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return this->operator()(s1, s2, false, false); - } - - // Case insensitive Boyer-Moore version - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, const std::array &charmap, StringData v2) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - if (v1.size() == 0 && !v2.is_null()) - return true; - - return contains_ins(v2, v1_upper, v1_lower, v1.size(), charmap); - } - - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "CONTAINS[c]"; - } - - static const int condition = -1; -}; - -// Does v2 contain something like v1 (wildcard matching)? -struct LikeIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v2.is_null() || v1.is_null()) { - return (v2.is_null() && v1.is_null()); - } - - return string_like_ins(v2, v1_lower, v1_upper); - } - bool operator()(BinaryData b1, const char* b1_upper, const char* b1_lower, BinaryData b2, bool = false, - bool = false) const - { - if (b2.is_null() || b1.is_null()) { - return (b2.is_null() && b1.is_null()); - } - StringData s2(b2.data(), b2.size()); - - return string_like_ins(s2, b1_lower, b1_upper); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v2.is_null() || v1.is_null()) { - return (v2.is_null() && v1.is_null()); - } - - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return string_like_ins(v2, v1_lower, v1_upper); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - if (b2.is_null() || b1.is_null()) { - return (b2.is_null() && b1.is_null()); - } - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - - std::string s1_upper = case_map(s1, true, IgnoreErrors); - std::string s1_lower = case_map(s1, false, IgnoreErrors); - return string_like_ins(s2, s1_lower, s1_upper); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "LIKE[c]"; - } - - static const int condition = -1; -}; - -// Does v2 begin with v1? -struct BeginsWithIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - return v1.size() <= v2.size() && equal_case_fold(v2.prefix(v1.size()), v1_upper, v1_lower); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - if (v1.size() > v2.size()) - return false; - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return equal_case_fold(v2.prefix(v1.size()), v1_upper.c_str(), v1_lower.c_str()); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return this->operator()(s1, s2, false, false); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "BEGINSWITH[c]"; - } - - static const int condition = -1; -}; - -// Does v2 end with v1? -struct EndsWithIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - return v1.size() <= v2.size() && equal_case_fold(v2.suffix(v1.size()), v1_upper, v1_lower); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v2.is_null() && !v1.is_null()) - return false; - - if (v1.size() > v2.size()) - return false; - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return equal_case_fold(v2.suffix(v1.size()), v1_upper.c_str(), v1_lower.c_str()); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return this->operator()(s1, s2, false, false); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "ENDSWITH[c]"; - } - - static const int condition = -1; -}; - -struct EqualIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v1.is_null() != v2.is_null()) - return false; - - return v1.size() == v2.size() && equal_case_fold(v2, v1_upper, v1_lower); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v1.is_null() != v2.is_null()) - return false; - - if (v1.size() != v2.size()) - return false; - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return equal_case_fold(v2, v1_upper.c_str(), v1_lower.c_str()); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return this->operator()(s1, s2, false, false); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool operator()(int64_t, int64_t, bool, bool) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "==[c]"; - } - - static const int condition = -1; -}; - -struct NotEqualIns : public HackClass { - bool operator()(StringData v1, const char* v1_upper, const char* v1_lower, StringData v2, bool = false, - bool = false) const - { - if (v1.is_null() != v2.is_null()) - return true; - return v1.size() != v2.size() || !equal_case_fold(v2, v1_upper, v1_lower); - } - - // Slow version, used if caller hasn't stored an upper and lower case version - bool operator()(StringData v1, StringData v2, bool = false, bool = false) const - { - if (v1.is_null() != v2.is_null()) - return true; - - if (v1.size() != v2.size()) - return true; - std::string v1_upper = case_map(v1, true, IgnoreErrors); - std::string v1_lower = case_map(v1, false, IgnoreErrors); - return !equal_case_fold(v2, v1_upper.c_str(), v1_lower.c_str()); - } - bool operator()(BinaryData b1, BinaryData b2, bool = false, bool = false) const - { - StringData s1(b1.data(), b1.size()); - StringData s2(b2.data(), b2.size()); - return this->operator()(s1, s2, false, false); - } - - template - bool operator()(A, B) const - { - REALM_ASSERT(false); - return false; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - - static std::string description() - { - return "!=[c]"; - } - - static const int condition = -1; -}; - -struct Greater { - static const int avx = 0x1E; // _CMP_GT_OQ - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - if (v1null || v2null) - return false; - - return v1 > v2; - } - static const int condition = cond_Greater; - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - return ubound > v; - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(ubound); - return lbound > v; - } - - static std::string description() - { - return ">"; - } -}; - -struct None { - template - bool operator()(const T&, const T&, bool = false, bool = false) const - { - return true; - } - static const int condition = cond_None; - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - static_cast(ubound); - static_cast(v); - return true; - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - static_cast(ubound); - static_cast(v); - return true; - } - - static std::string description() - { - return "none"; - } -}; - -struct NotNull { - template - bool operator()(const T&, const T&, bool v = false, bool = false) const - { - return !v; - } - static const int condition = cond_LeftNotNull; - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - static_cast(ubound); - static_cast(v); - return true; - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - static_cast(ubound); - static_cast(v); - return true; - } - static std::string description() - { - return "!= NULL"; - } -}; - - -struct Less { - static const int avx = 0x11; // _CMP_LT_OQ - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - if (v1null || v2null) - return false; - - return v1 < v2; - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - static const int condition = cond_Less; - bool can_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(ubound); - return lbound < v; - } - bool will_match(int64_t v, int64_t lbound, int64_t ubound) - { - static_cast(lbound); - return ubound < v; - } - static std::string description() - { - return "<"; - } -}; - -struct LessEqual : public HackClass { - static const int avx = 0x12; // _CMP_LE_OQ - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - if (v1null && v2null) - return true; - - return (!v1null && !v2null && v1 <= v2); - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - static std::string description() - { - return "<="; - } - static const int condition = -1; -}; - -struct GreaterEqual : public HackClass { - static const int avx = 0x1D; // _CMP_GE_OQ - template - bool operator()(const T& v1, const T& v2, bool v1null = false, bool v2null = false) const - { - if (v1null && v2null) - return true; - - return (!v1null && !v2null && v1 >= v2); - } - template - bool operator()(A, B, C, D) const - { - REALM_ASSERT(false); - return false; - } - static std::string description() - { - return ">="; - } - static const int condition = -1; -}; - - -// CompareLess is a temporary hack to have a generalized way to compare any realm types. Todo, enable correct < -// operator of StringData (currently gives circular header dependency with utf8.hpp) -template -struct CompareLess { - static bool compare(T v1, T v2, bool = false, bool = false) - { - return v1 < v2; - } -}; -template <> -struct CompareLess { - static bool compare(StringData v1, StringData v2, bool = false, bool = false) - { - bool ret = utf8_compare(v1.data(), v2.data()); - return ret; - } -}; - -} // namespace realm - -#endif // REALM_QUERY_CONDITIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/query_engine.hpp b/Lesson14/Pods/Realm/include/core/realm/query_engine.hpp deleted file mode 100644 index 806bc2a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/query_engine.hpp +++ /dev/null @@ -1,2521 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -/* -A query consists of node objects, one for each query condition. Each node contains pointers to all other nodes: - -node1 node2 node3 ------- ----- ----- -node2* node1* node1* -node3* node3* node2* - -The construction of all this takes part in query.cpp. Each node has two important functions: - - aggregate(start, end) - aggregate_local(start, end) - -The aggregate() function executes the aggregate of a query. You can call the method on any of the nodes -(except children nodes of OrNode and SubtableNode) - it has the same behaviour. The function contains -scheduling that calls aggregate_local(start, end) on different nodes with different start/end ranges, -depending on what it finds is most optimal. - -The aggregate_local() function contains a tight loop that tests the condition of its own node, and upon match -it tests all other conditions at that index to report a full match or not. It will remain in the tight loop -after a full match. - -So a call stack with 2 and 9 being local matches of a node could look like this: - -aggregate(0, 10) - node1->aggregate_local(0, 3) - node2->find_first_local(2, 3) - node3->find_first_local(2, 3) - node3->aggregate_local(3, 10) - node1->find_first_local(4, 5) - node2->find_first_local(4, 5) - node1->find_first_local(7, 8) - node2->find_first_local(7, 8) - -find_first_local(n, n + 1) is a function that can be used to test a single row of another condition. Note that -this is very simplified. There are other statistical arguments to the methods, and also, find_first_local() can be -called from a callback function called by an integer Array. - - -Template arguments in methods: ----------------------------------------------------------------------------------------------------- - -TConditionFunction: Each node has a condition from query_conditions.c such as Equal, GreaterEqual, etc - -TConditionValue: Type of values in condition column. That is, int64_t, float, int, bool, etc - -TAction: What to do with each search result, from the enums act_ReturnFirst, act_Count, act_Sum, etc - -TResult: Type of result of actions - float, double, int64_t, etc. Special notes: For act_Count it's - int64_t, for RLM_FIND_ALL it's int64_t which points at destination array. - -TSourceColumn: Type of source column used in actions, or *ignored* if no source column is used (like for - act_Count, act_ReturnFirst) - - -There are two important classes used in queries: ----------------------------------------------------------------------------------------------------- -SequentialGetter Column iterator used to get successive values with leaf caching. Used both for condition columns - and aggregate source column - -AggregateState State of the aggregate - contains a state variable that stores intermediate sum, max, min, - etc, etc. - -*/ - -#ifndef REALM_QUERY_ENGINE_HPP -#define REALM_QUERY_ENGINE_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#if REALM_X86_OR_X64_TRUE && defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219 -#include -#endif - -namespace realm { - -// Number of matches to find in best condition loop before breaking out to probe other conditions. Too low value gives -// too many constant time overheads everywhere in the query engine. Too high value makes it adapt less rapidly to -// changes in match frequencies. -const size_t findlocals = 64; - -// Average match distance in linear searches where further increase in distance no longer increases query speed -// (because time spent on handling each match becomes insignificant compared to time spent on the search). -const size_t bestdist = 512; - -// Minimum number of matches required in a certain condition before it can be used to compute statistics. Too high -// value can spent too much time in a bad node (with high match frequency). Too low value gives inaccurate statistics. -const size_t probe_matches = 4; - -const size_t bitwidth_time_unit = 64; - -typedef bool (*CallbackDummy)(int64_t); - -class ParentNode { - typedef ParentNode ThisType; - -public: - ParentNode() = default; - virtual ~ParentNode() = default; - - void gather_children(std::vector& v) - { - m_children.clear(); - size_t i = v.size(); - v.push_back(this); - - if (m_child) - m_child->gather_children(v); - - m_children = v; - m_children.erase(m_children.begin() + i); - m_children.insert(m_children.begin(), this); - } - - double cost() const - { - return 8 * bitwidth_time_unit / m_dD + - m_dT; // dt = 1/64 to 1. Match dist is 8 times more important than bitwidth - } - - size_t find_first(size_t start, size_t end); - - virtual void init() - { - // Verify that the cached column accessor is still valid - verify_column(); // throws - - if (m_child) - m_child->init(); - - m_column_action_specializer = nullptr; - } - - void set_table(const Table& table) - { - if (&table == m_table) - return; - - m_table.reset(&table); - if (m_child) - m_child->set_table(table); - table_changed(); - } - - virtual size_t find_first_local(size_t start, size_t end) = 0; - - virtual void aggregate_local_prepare(Action TAction, DataType col_id, bool nullable); - - template - bool column_action_specialization(QueryStateBase* st, SequentialGetterBase* source_column, size_t r) - { - // TResult: type of query result - // TSourceValue: type of aggregate source - using TSourceValue = typename TSourceColumn::value_type; - using TResult = typename ColumnTypeTraitsSum::sum_type; - - // Sum of float column must accumulate in double - static_assert(!(TAction == act_Sum && - (std::is_same::value && !std::is_same::value)), - ""); - - TSourceValue av{}; - // uses_val test because compiler cannot see that IntegerColumn::get has no side effect and result is - // discarded - if (static_cast*>(st)->template uses_val() && source_column != nullptr) { - REALM_ASSERT_DEBUG(dynamic_cast*>(source_column) != nullptr); - av = static_cast*>(source_column)->get_next(r); - } - REALM_ASSERT_DEBUG(dynamic_cast*>(st) != nullptr); - bool cont = static_cast*>(st)->template match(r, 0, av); - return cont; - } - - virtual size_t aggregate_local(QueryStateBase* st, size_t start, size_t end, size_t local_limit, - SequentialGetterBase* source_column); - - - virtual std::string validate() - { - if (error_code != "") - return error_code; - if (m_child == nullptr) - return ""; - else - return m_child->validate(); - } - - ParentNode(const ParentNode& from) - : ParentNode(from, nullptr) - { - } - - ParentNode(const ParentNode& from, QueryNodeHandoverPatches* patches) - : m_child(from.m_child ? from.m_child->clone(patches) : nullptr) - , m_condition_column_idx(from.m_condition_column_idx) - , m_dD(from.m_dD) - , m_dT(from.m_dT) - , m_probes(from.m_probes) - , m_matches(from.m_matches) - , m_table(patches ? ConstTableRef{} : from.m_table) - { - } - - void add_child(std::unique_ptr child) - { - if (m_child) - m_child->add_child(std::move(child)); - else - m_child = std::move(child); - } - - virtual std::unique_ptr clone(QueryNodeHandoverPatches* = nullptr) const = 0; - - virtual void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) - { - if (m_child) - m_child->apply_handover_patch(patches, group); - } - - virtual void verify_column() const = 0; - - virtual std::string describe(util::serializer::SerialisationState&) const - { - return ""; - } - - virtual std::string describe_condition() const - { - return "matches"; - } - - virtual std::string describe_expression(util::serializer::SerialisationState& state) const - { - std::string s; - s = describe(state); - if (m_child) { - s = s + " and " + m_child->describe_expression(state); - } - return s; - } - - std::unique_ptr m_child; - std::vector m_children; - size_t m_condition_column_idx = npos; // Column of search criteria - - double m_dD; // Average row distance between each local match at current position - double m_dT = 0.0; // Time overhead of testing index i + 1 if we have just tested index i. > 1 for linear scans, 0 - // for index/tableview - - size_t m_probes = 0; - size_t m_matches = 0; - -protected: - typedef bool (ParentNode::*Column_action_specialized)(QueryStateBase*, SequentialGetterBase*, size_t); - Column_action_specialized m_column_action_specializer; - ConstTableRef m_table; - std::string error_code; - - const ColumnBase& get_column_base(size_t ndx) - { - return m_table->get_column_base(ndx); - } - - template - const ColType& get_column(size_t ndx) - { - auto& col = m_table->get_column_base(ndx); - REALM_ASSERT_DEBUG(dynamic_cast(&col)); - return static_cast(col); - } - - ColumnType get_real_column_type(size_t ndx) - { - return m_table->get_real_column_type(ndx); - } - - template - void copy_getter(SequentialGetter& dst, size_t& dst_idx, const SequentialGetter& src, - const QueryNodeHandoverPatches* patches) - { - if (src.m_column) { - if (patches) - dst_idx = src.m_column->get_column_index(); - else - dst.init(src.m_column); - } - } - - void do_verify_column(const ColumnBase* col, size_t col_ndx = npos) const - { - if (col_ndx == npos) - col_ndx = m_condition_column_idx; - if (m_table && col_ndx != npos) { - m_table->verify_column(col_ndx, col); - } - } - -private: - virtual void table_changed() = 0; -}; - -// For conditions on a subtable (encapsulated in subtable()...end_subtable()). These return the parent row as match if -// and only if one or more subtable rows match the condition. -class SubtableNode : public ParentNode { -public: - SubtableNode(size_t column, std::unique_ptr condition) - : m_condition(std::move(condition)) - { - m_dT = 100.0; - m_condition_column_idx = column; - } - - void init() override - { - ParentNode::init(); - - m_dD = 10.0; - - // m_condition is first node in condition of subtable query. - if (m_condition) { - // Can't call init() here as usual since the subtable can be degenerate - // m_condition->init(table); - std::vector v; - m_condition->gather_children(v); - } - } - - void table_changed() override - { - m_col_type = m_table->get_real_column_type(m_condition_column_idx); - REALM_ASSERT(m_col_type == col_type_Table || m_col_type == col_type_Mixed); - if (m_col_type == col_type_Table) - m_column = &m_table->get_column_table(m_condition_column_idx); - else // Mixed - m_column = &m_table->get_column_mixed(m_condition_column_idx); - } - - void verify_column() const override - { - if (m_table) - m_table->verify_column(m_condition_column_idx, m_column); - } - - std::string validate() override - { - if (error_code != "") - return error_code; - if (m_condition == nullptr) - return "Unbalanced subtable/end_subtable block"; - else - return m_condition->validate(); - } - - std::string describe(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialising a query which contains a subtable expression is currently unsupported."); - } - - - size_t find_first_local(size_t start, size_t end) override - { - REALM_ASSERT(m_table); - REALM_ASSERT(m_condition); - - for (size_t s = start; s < end; ++s) { - ConstTableRef subtable; // TBD: optimize this back to Table* - if (m_col_type == col_type_Table) - subtable = static_cast(m_column)->get_subtable_tableref(s); - else { - subtable = static_cast(m_column)->get_subtable_tableref(s); - if (!subtable) - continue; - } - - if (subtable->is_degenerate()) - return not_found; - - m_condition->set_table(*subtable); - m_condition->init(); - const size_t subsize = subtable->size(); - const size_t sub = m_condition->find_first(0, subsize); - - if (sub != not_found) - return s; - } - return not_found; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new SubtableNode(*this, patches)); - } - - SubtableNode(const SubtableNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_condition(from.m_condition ? from.m_condition->clone(patches) : nullptr) - , m_column(from.m_column) - , m_col_type(from.m_col_type) - { - if (m_column && patches) - m_condition_column_idx = m_column->get_column_index(); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_condition->apply_handover_patch(patches, group); - ParentNode::apply_handover_patch(patches, group); - } - - std::unique_ptr m_condition; - const ColumnBase* m_column = nullptr; - ColumnType m_col_type; -}; - -namespace _impl { - -template -struct CostHeuristic; - -template <> -struct CostHeuristic { - static constexpr double dD() - { - return 100.0; - } - static constexpr double dT() - { - return 1.0 / 4.0; - } -}; - -template <> -struct CostHeuristic { - static constexpr double dD() - { - return 100.0; - } - static constexpr double dT() - { - return 1.0 / 4.0; - } -}; - -// FIXME: Add AdaptiveStringColumn, BasicColumn, etc. -} - -class ColumnNodeBase : public ParentNode { -protected: - ColumnNodeBase(size_t column_idx) - { - m_condition_column_idx = column_idx; - } - - ColumnNodeBase(const ColumnNodeBase& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_last_local_match(from.m_last_local_match) - , m_local_matches(from.m_local_matches) - , m_local_limit(from.m_local_limit) - , m_fastmode_disabled(from.m_fastmode_disabled) - , m_action(from.m_action) - , m_state(from.m_state) - , m_source_column(from.m_source_column) - { - } - - template - bool match_callback(int64_t v) - { - using TSourceValue = typename ColType::value_type; - using QueryStateType = typename ColumnTypeTraitsSum::sum_type; - - size_t i = to_size_t(v); - m_last_local_match = i; - m_local_matches++; - - auto state = static_cast*>(m_state); - auto source_column = static_cast*>(m_source_column); - - // Test remaining sub conditions of this node. m_children[0] is the node that called match_callback(), so skip - // it - for (size_t c = 1; c < m_children.size(); c++) { - m_children[c]->m_probes++; - size_t m = m_children[c]->find_first_local(i, i + 1); - if (m != i) - return true; - } - - bool b; - if (state->template uses_val()) { // Compiler cannot see that IntegerColumn::Get has no side effect - // and result is discarded - TSourceValue av = source_column->get_next(i); - b = state->template match(i, 0, av); - } - else { - b = state->template match(i, 0, TSourceValue{}); - } - - return b; - } - - // Aggregate bookkeeping - size_t m_last_local_match = npos; - size_t m_local_matches = 0; - size_t m_local_limit = 0; - bool m_fastmode_disabled = false; - Action m_action; - QueryStateBase* m_state = nullptr; - SequentialGetterBase* m_source_column = - nullptr; // Column of values used in aggregate (act_FindAll, actReturnFirst, act_Sum, etc) -}; - -template -class IntegerNodeBase : public ColumnNodeBase { - using ThisType = IntegerNodeBase; - -public: - using TConditionValue = typename ColType::value_type; - static const bool nullable = ColType::nullable; - - template - bool find_callback_specialization(size_t s, size_t end_in_leaf) - { - using AggregateColumnType = typename GetColumnType::type; - bool cont; - size_t start_in_leaf = s - this->m_leaf_start; - cont = this->m_leaf_ptr->template find( - m_value, start_in_leaf, end_in_leaf, this->m_leaf_start, nullptr, - std::bind(std::mem_fn(&ThisType::template match_callback), this, - std::placeholders::_1)); - return cont; - } - -protected: - using LeafType = typename ColType::LeafType; - using LeafInfo = typename ColType::LeafInfo; - - size_t aggregate_local_impl(QueryStateBase* st, size_t start, size_t end, size_t local_limit, - SequentialGetterBase* source_column, int c) - { - REALM_ASSERT(m_children.size() > 0); - m_local_matches = 0; - m_local_limit = local_limit; - m_last_local_match = start - 1; - m_state = st; - - // If there are no other nodes than us (m_children.size() == 1) AND the column used for our condition is - // the same as the column used for the aggregate action, then the entire query can run within scope of that - // column only, with no references to other columns: - bool fastmode = should_run_in_fastmode(source_column); - for (size_t s = start; s < end;) { - cache_leaf(s); - - size_t end_in_leaf; - if (end > m_leaf_end) - end_in_leaf = m_leaf_end - m_leaf_start; - else - end_in_leaf = end - m_leaf_start; - - if (fastmode) { - bool cont; - size_t start_in_leaf = s - m_leaf_start; - cont = m_leaf_ptr->find(c, m_action, m_value, start_in_leaf, end_in_leaf, m_leaf_start, - static_cast*>(st)); - if (!cont) - return not_found; - } - // Else, for each match in this node, call our IntegerNodeBase::match_callback to test remaining nodes - // and/or extract - // aggregate payload from aggregate column: - else { - m_source_column = source_column; - bool cont = (this->*m_find_callback_specialized)(s, end_in_leaf); - if (!cont) - return not_found; - } - - if (m_local_matches == m_local_limit) - break; - - s = end_in_leaf + m_leaf_start; - } - - if (m_local_matches == m_local_limit) { - m_dD = (m_last_local_match + 1 - start) / (m_local_matches + 1.0); - return m_last_local_match + 1; - } - else { - m_dD = (end - start) / (m_local_matches + 1.0); - return end; - } - } - - IntegerNodeBase(TConditionValue value, size_t column_idx) - : ColumnNodeBase(column_idx) - , m_value(std::move(value)) - { - } - - IntegerNodeBase(const ThisType& from, QueryNodeHandoverPatches* patches) - : ColumnNodeBase(from, patches) - , m_value(from.m_value) - , m_condition_column(from.m_condition_column) - , m_find_callback_specialized(from.m_find_callback_specialized) - { - if (m_condition_column && patches) - m_condition_column_idx = m_condition_column->get_column_index(); - } - - void table_changed() override - { - m_condition_column = &get_column(m_condition_column_idx); - } - - void verify_column() const override - { - do_verify_column(m_condition_column); - } - - void init() override - { - ColumnNodeBase::init(); - - m_dT = _impl::CostHeuristic::dT(); - m_dD = _impl::CostHeuristic::dD(); - - // Clear leaf cache - m_leaf_end = 0; - m_array_ptr.reset(); // Explicitly destroy the old one first, because we're reusing the memory. - m_array_ptr.reset(new (&m_leaf_cache_storage) LeafType(m_table->get_alloc())); - } - - void get_leaf(const ColType& col, size_t ndx) - { - size_t ndx_in_leaf; - LeafInfo leaf_info{&m_leaf_ptr, m_array_ptr.get()}; - col.get_leaf(ndx, ndx_in_leaf, leaf_info); - m_leaf_start = ndx - ndx_in_leaf; - m_leaf_end = m_leaf_start + m_leaf_ptr->size(); - } - - void cache_leaf(size_t s) - { - if (s >= m_leaf_end || s < m_leaf_start) { - get_leaf(*m_condition_column, s); - size_t w = m_leaf_ptr->get_width(); - m_dT = (w == 0 ? 1.0 / REALM_MAX_BPNODE_SIZE : w / float(bitwidth_time_unit)); - } - } - - bool should_run_in_fastmode(SequentialGetterBase* source_column) const - { - return (m_children.size() == 1 && - (source_column == nullptr || - (!m_fastmode_disabled && - static_cast*>(source_column)->m_column == m_condition_column))); - } - - // Search value: - TConditionValue m_value; - - // Column on which search criteria are applied - const ColType* m_condition_column = nullptr; - - // Leaf cache - using LeafCacheStorage = typename std::aligned_storage::type; - LeafCacheStorage m_leaf_cache_storage; - std::unique_ptr m_array_ptr; - const LeafType* m_leaf_ptr = nullptr; - size_t m_leaf_start = npos; - size_t m_leaf_end = 0; - size_t m_local_end; - - // Aggregate optimization - using TFind_callback_specialized = bool (ThisType::*)(size_t, size_t); - TFind_callback_specialized m_find_callback_specialized = nullptr; -}; - - -template -class IntegerNode : public IntegerNodeBase { - using BaseType = IntegerNodeBase; - using ThisType = IntegerNode; - -public: - static const bool special_null_node = false; - using TConditionValue = typename BaseType::TConditionValue; - - IntegerNode(TConditionValue value, size_t column_ndx) - : BaseType(value, column_ndx) - { - } - IntegerNode(const IntegerNode& from, QueryNodeHandoverPatches* patches) - : BaseType(from, patches) - { - } - - void aggregate_local_prepare(Action action, DataType col_id, bool is_nullable) override - { - this->m_fastmode_disabled = (col_id == type_Float || col_id == type_Double); - this->m_action = action; - this->m_find_callback_specialized = get_specialized_callback(action, col_id, is_nullable); - } - - size_t aggregate_local(QueryStateBase* st, size_t start, size_t end, size_t local_limit, - SequentialGetterBase* source_column) override - { - constexpr int cond = TConditionFunction::condition; - return this->aggregate_local_impl(st, start, end, local_limit, source_column, cond); - } - - size_t find_first_local(size_t start, size_t end) override - { - REALM_ASSERT(this->m_table); - - while (start < end) { - - // Cache internal leaves - if (start >= this->m_leaf_end || start < this->m_leaf_start) { - this->get_leaf(*this->m_condition_column, start); - } - - // FIXME: Create a fast bypass when you just need to check 1 row, which is used alot from within core. - // It should just call array::get and save the initial overhead of find_first() which has become quite - // big. Do this when we have cleaned up core a bit more. - - size_t end2; - if (end > this->m_leaf_end) - end2 = this->m_leaf_end - this->m_leaf_start; - else - end2 = end - this->m_leaf_start; - - size_t s; - s = this->m_leaf_ptr->template find_first(this->m_value, start - this->m_leaf_start, - end2); - - if (s == not_found) { - start = this->m_leaf_end; - continue; - } - else - return s + this->m_leaf_start; - } - - return not_found; - } - - std::string describe(util::serializer::SerialisationState& state) const override - { - return state.describe_column(ParentNode::m_table, IntegerNodeBase::m_condition_column->get_column_index()) - + " " + describe_condition() + " " + util::serializer::print_value(IntegerNodeBase::m_value); - } - - std::string describe_condition() const override - { - return TConditionFunction::description(); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new IntegerNode(*this, patches)); - } - -protected: - using TFind_callback_specialized = typename BaseType::TFind_callback_specialized; - - static TFind_callback_specialized get_specialized_callback(Action action, DataType col_id, bool is_nullable) - { - switch (action) { - case act_Count: - return get_specialized_callback_2_int(col_id, is_nullable); - case act_Sum: - return get_specialized_callback_2(col_id, is_nullable); - case act_Max: - return get_specialized_callback_2(col_id, is_nullable); - case act_Min: - return get_specialized_callback_2(col_id, is_nullable); - case act_FindAll: - return get_specialized_callback_2_int(col_id, is_nullable); - case act_CallbackIdx: - return get_specialized_callback_2_int(col_id, is_nullable); - default: - break; - } - REALM_ASSERT(false); // Invalid aggregate function - return nullptr; - } - - template - static TFind_callback_specialized get_specialized_callback_2(DataType col_id, bool is_nullable) - { - switch (col_id) { - case type_Int: - return get_specialized_callback_3(is_nullable); - case type_Float: - return get_specialized_callback_3(is_nullable); - case type_Double: - return get_specialized_callback_3(is_nullable); - default: - break; - } - REALM_ASSERT(false); // Invalid aggregate source column - return nullptr; - } - - template - static TFind_callback_specialized get_specialized_callback_2_int(DataType col_id, bool is_nullable) - { - if (col_id == type_Int) { - return get_specialized_callback_3(is_nullable); - } - REALM_ASSERT(false); // Invalid aggregate source column - return nullptr; - } - - template - static TFind_callback_specialized get_specialized_callback_3(bool is_nullable) - { - if (is_nullable) { - return &BaseType::template find_callback_specialization; - } - else { - return &BaseType::template find_callback_specialization; - } - } -}; - -template -class IntegerNode : public IntegerNodeBase { -public: - using BaseType = IntegerNodeBase; - using TConditionValue = typename BaseType::TConditionValue; - - IntegerNode(TConditionValue value, size_t column_ndx) - : BaseType(value, column_ndx) - { - } - ~IntegerNode() - { - if (m_result) { - m_result->destroy(); - } - } - - void init() override - { - BaseType::init(); - m_nb_needles = m_needles.size(); - - if (has_search_index()) { - if (m_result) { - m_result->clear(); - } - else { - ref_type ref = IntegerColumn::create(Allocator::get_default()); - m_result = std::make_unique(); - m_result->init_from_ref(Allocator::get_default(), ref); - } - - IntegerNodeBase::m_condition_column->find_all(*m_result, this->m_value, 0, realm::npos); - m_index_get = 0; - m_index_end = m_result->size(); - IntegerNodeBase::m_dT = 0; - } - } - - void consume_condition(IntegerNode* other) - { - REALM_ASSERT(this->m_condition_column == other->m_condition_column); - REALM_ASSERT(other->m_needles.empty()); - if (m_needles.empty()) { - m_needles.insert(this->m_value); - } - m_needles.insert(other->m_value); - } - - bool has_search_index() const - { - return IntegerNodeBase::m_condition_column->has_search_index(); - } - - size_t find_first_local(size_t start, size_t end) override - { - REALM_ASSERT(this->m_table); - - if (has_search_index()) { - if (m_index_end == 0) - return not_found; - - if (start <= m_index_last_start) - m_index_get = 0; - else - m_index_last_start = start; - - REALM_ASSERT(m_result); - while (m_index_get < m_index_end) { - // m_results are stored in sorted ascending order, guaranteed by the string index - size_t ndx = size_t(m_result->get(m_index_get)); - if (ndx >= end) { - break; - } - m_index_get++; - if (ndx >= start) { - return ndx; - } - } - return not_found; - } - - - while (start < end) { - // Cache internal leaves - this->cache_leaf(start); - - size_t end2; - if (end > this->m_leaf_end) - end2 = this->m_leaf_end - this->m_leaf_start; - else - end2 = end - this->m_leaf_start; - - auto start2 = start - this->m_leaf_start; - size_t s = realm::npos; - if (m_nb_needles) { - s = find_first_haystack(start2, end2); - } - else if (end2 - start2 == 1) { - if (this->m_leaf_ptr->get(start2) == this->m_value) { - s = start2; - } - } - else { - s = this->m_leaf_ptr->template find_first(this->m_value, start2, end2); - } - - if (s == not_found) { - start = this->m_leaf_end; - continue; - } - else - return s + this->m_leaf_start; - } - - return not_found; - } - - std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(this->m_condition_column != nullptr); - std::string col_descr = state.describe_column(this->m_table, this->m_condition_column->get_column_index()); - - if (m_needles.empty()) { - return col_descr + " " + Equal::description() + " " + - util::serializer::print_value(IntegerNodeBase::m_value); - } - - // FIXME: once the parser supports it, print something like "column IN {n1, n2, n3}" - std::string desc = "("; - bool is_first = true; - for (auto it : m_needles) { - if (!is_first) - desc += " or "; - desc += - col_descr + " " + Equal::description() + " " + util::serializer::print_value(it); // "it" may be null - is_first = false; - } - desc += ")"; - return desc; - } - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new IntegerNode(*this, patches)); - } - -private: - std::unordered_set m_needles; - std::unique_ptr m_result; - size_t m_nb_needles = 0; - size_t m_index_get = 0; - size_t m_index_last_start = 0; - size_t m_index_end = 0; - - IntegerNode(const IntegerNode& from, QueryNodeHandoverPatches* patches) - : BaseType(from, patches) - , m_needles(from.m_needles) - { - } - size_t find_first_haystack(size_t start, size_t end) - { - const auto not_in_set = m_needles.end(); - // for a small number of conditions, it is faster to do a linear search than to compute the hash - // the decision threshold was determined experimentally to be 22 conditions - bool search = m_nb_needles < 22; - auto cmp_fn = [this, search, not_in_set](const auto& v) { - if (search) { - for (auto it = m_needles.begin(); it != not_in_set; ++it) { - if (*it == v) - return true; - } - return false; - } - else { - return (m_needles.find(v) != not_in_set); - } - }; - for (size_t i = start; i < end; ++i) { - auto val = this->m_leaf_ptr->get(i); - if (cmp_fn(val)) { - return i; - } - } - return realm::npos; - } -}; - - -// This node is currently used for floats and doubles only -template -class FloatDoubleNode : public ParentNode { -public: - using TConditionValue = typename ColType::value_type; - static const bool special_null_node = false; - - FloatDoubleNode(TConditionValue v, size_t column_ndx) - : m_value(v) - { - m_condition_column_idx = column_ndx; - m_dT = 1.0; - } - FloatDoubleNode(null, size_t column_ndx) - : m_value(null::get_null_float()) - { - m_condition_column_idx = column_ndx; - m_dT = 1.0; - } - - void table_changed() override - { - m_condition_column.init(&get_column(m_condition_column_idx)); - } - - void verify_column() const override - { - do_verify_column(m_condition_column.m_column); - } - - void init() override - { - ParentNode::init(); - m_dD = 100.0; - } - - size_t find_first_local(size_t start, size_t end) override - { - TConditionFunction cond; - - auto find = [&](bool nullability) { - bool m_value_nan = nullability ? null::is_null_float(m_value) : false; - for (size_t s = start; s < end; ++s) { - TConditionValue v = m_condition_column.get_next(s); - REALM_ASSERT(!(null::is_null_float(v) && !nullability)); - if (cond(v, m_value, nullability ? null::is_null_float(v) : false, m_value_nan)) - return s; - } - return not_found; - }; - - // This will inline the second case but no the first. Todo, use templated lambda when switching to c++14 - if (m_table->is_nullable(m_condition_column_idx)) - return find(true); - else - return find(false); - } - - std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_condition_column.m_column != nullptr); - return state.describe_column(ParentNode::m_table, m_condition_column.m_column->get_column_index()) - + " " + describe_condition() + " " + util::serializer::print_value(FloatDoubleNode::m_value); - } - std::string describe_condition() const override - { - return TConditionFunction::description(); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new FloatDoubleNode(*this, patches)); - } - - FloatDoubleNode(const FloatDoubleNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - { - copy_getter(m_condition_column, m_condition_column_idx, from.m_condition_column, patches); - } - -protected: - TConditionValue m_value; - SequentialGetter m_condition_column; -}; - -template -class SizeNode : public ParentNode { -public: - SizeNode(int64_t v, size_t column) - : m_value(v) - { - m_condition_column_idx = column; - } - - void table_changed() override - { - m_condition_column = &get_column(m_condition_column_idx); - } - - void verify_column() const override - { - do_verify_column(m_condition_column); - } - - void init() override - { - ParentNode::init(); - m_dD = 10.0; - } - - size_t find_first_local(size_t start, size_t end) override - { - for (size_t s = start; s < end; ++s) { - TConditionValue v = m_condition_column->get(s); - if (v) { - int64_t sz = m_size_operator(v); - if (TConditionFunction()(sz, m_value)) - return s; - } - } - return not_found; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new SizeNode(*this, patches)); - } - - SizeNode(const SizeNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - , m_condition_column(from.m_condition_column) - { - if (m_condition_column && patches) - m_condition_column_idx = m_condition_column->get_column_index(); - } - -private: - using TConditionValue = typename ColType::value_type; - - int64_t m_value; - const ColType* m_condition_column = nullptr; - Size m_size_operator; -}; - - -template -class BinaryNode : public ParentNode { -public: - using TConditionValue = BinaryData; - static const bool special_null_node = false; - - BinaryNode(BinaryData v, size_t column) - : m_value(v) - { - m_dT = 100.0; - m_condition_column_idx = column; - } - - BinaryNode(null, size_t column) - : BinaryNode(BinaryData{}, column) - { - } - - void table_changed() override - { - m_condition_column = &get_column(m_condition_column_idx); - } - - void verify_column() const override - { - do_verify_column(m_condition_column); - } - - void init() override - { - ParentNode::init(); - - m_dD = 100.0; - } - - size_t find_first_local(size_t start, size_t end) override - { - TConditionFunction condition; - for (size_t s = start; s < end; ++s) { - BinaryData value = m_condition_column->get(s); - if (condition(m_value.get(), value)) - return s; - } - return not_found; - } - - virtual std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_condition_column != nullptr); - return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) - + " " + TConditionFunction::description() + " " - + util::serializer::print_value(BinaryNode::m_value.get()); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new BinaryNode(*this, patches)); - } - - BinaryNode(const BinaryNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - , m_condition_column(from.m_condition_column) - { - if (m_condition_column && patches) - m_condition_column_idx = m_condition_column->get_column_index(); - } - -private: - OwnedBinaryData m_value; - const BinaryColumn* m_condition_column; -}; - - -class TimestampNodeBase : public ParentNode { -public: - using TConditionValue = Timestamp; - static const bool special_null_node = false; - using LeafTypeSeconds = typename IntNullColumn::LeafType; - using LeafInfoSeconds = typename IntNullColumn::LeafInfo; - using LeafTypeNanos = typename IntegerColumn::LeafType; - using LeafInfoNanos = typename IntegerColumn::LeafInfo; - - - TimestampNodeBase(Timestamp v, size_t column) - : m_value(v) - , m_needle_seconds(m_value.is_null() ? util::none : util::make_optional(m_value.get_seconds())) - { - m_condition_column_idx = column; - } - - TimestampNodeBase(null, size_t column) - : TimestampNodeBase(Timestamp{}, column) - { - } - - void table_changed() override - { - m_condition_column = &get_column(m_condition_column_idx); - } - - void verify_column() const override - { - do_verify_column(m_condition_column); - } - - void init() override - { - ParentNode::init(); - - m_dD = 100.0; - - // Clear leaf cache - m_leaf_end_seconds = 0; - m_array_ptr_seconds.reset(); // Explicitly destroy the old one first, because we're reusing the memory. - m_array_ptr_seconds.reset(new (&m_leaf_cache_storage_seconds) LeafTypeSeconds(m_table->get_alloc())); - m_leaf_end_nanos = 0; - m_array_ptr_nanos.reset(); // Explicitly destroy the old one first, because we're reusing the memory. - m_array_ptr_nanos.reset(new (&m_leaf_cache_storage_nanos) LeafTypeNanos(m_table->get_alloc())); - m_condition_column_is_nullable = m_condition_column->is_nullable(); - } - -protected: - void get_leaf_seconds(const TimestampColumn& col, size_t ndx) - { - size_t ndx_in_leaf; - LeafInfoSeconds leaf_info_seconds{&m_leaf_ptr_seconds, m_array_ptr_seconds.get()}; - col.get_seconds_leaf(ndx, ndx_in_leaf, leaf_info_seconds); - m_leaf_start_seconds = ndx - ndx_in_leaf; - m_leaf_end_seconds = m_leaf_start_seconds + m_leaf_ptr_seconds->size(); - } - - void get_leaf_nanos(const TimestampColumn& col, size_t ndx) - { - size_t ndx_in_leaf; - LeafInfoNanos leaf_info_nanos{&m_leaf_ptr_nanos, m_array_ptr_nanos.get()}; - col.get_nanoseconds_leaf(ndx, ndx_in_leaf, leaf_info_nanos); - m_leaf_start_nanos = ndx - ndx_in_leaf; - m_leaf_end_nanos = m_leaf_start_nanos + m_leaf_ptr_nanos->size(); - } - - util::Optional get_seconds_and_cache(size_t ndx) - { - // Cache internal leaves - if (ndx >= this->m_leaf_end_seconds || ndx < this->m_leaf_start_seconds) { - this->get_leaf_seconds(*this->m_condition_column, ndx); - } - const size_t ndx_in_leaf = ndx - m_leaf_start_seconds; - return this->m_leaf_ptr_seconds->get(ndx_in_leaf); - } - - int32_t get_nanoseconds_and_cache(size_t ndx) - { - // Cache internal leaves - if (ndx >= this->m_leaf_end_nanos || ndx < this->m_leaf_start_nanos) { - this->get_leaf_nanos(*this->m_condition_column, ndx); - } - return int32_t(this->m_leaf_ptr_nanos->get(ndx - this->m_leaf_start_nanos)); - } - - TimestampNodeBase(const TimestampNodeBase& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - , m_needle_seconds(from.m_needle_seconds) - , m_condition_column(from.m_condition_column) - , m_condition_column_is_nullable(from.m_condition_column_is_nullable) - { - if (m_condition_column && patches) - m_condition_column_idx = m_condition_column->get_column_index(); - } - - Timestamp m_value; - util::Optional m_needle_seconds; - const TimestampColumn* m_condition_column; - bool m_condition_column_is_nullable = false; - - // Leaf cache seconds - using LeafCacheStorageSeconds = - typename std::aligned_storage::type; - LeafCacheStorageSeconds m_leaf_cache_storage_seconds; - std::unique_ptr m_array_ptr_seconds; - const LeafTypeSeconds* m_leaf_ptr_seconds = nullptr; - size_t m_leaf_start_seconds = npos; - size_t m_leaf_end_seconds = 0; - - // Leaf cache nanoseconds - using LeafCacheStorageNanos = typename std::aligned_storage::type; - LeafCacheStorageNanos m_leaf_cache_storage_nanos; - std::unique_ptr m_array_ptr_nanos; - const LeafTypeNanos* m_leaf_ptr_nanos = nullptr; - size_t m_leaf_start_nanos = npos; - size_t m_leaf_end_nanos = 0; -}; - -template -class TimestampNode : public TimestampNodeBase { -public: - using TimestampNodeBase::TimestampNodeBase; - - template - size_t find_first_local_seconds(size_t start, size_t end) - { - while (start < end) { - // Cache internal leaves - if (start >= this->m_leaf_end_seconds || start < this->m_leaf_start_seconds) { - this->get_leaf_seconds(*this->m_condition_column, start); - } - - size_t end2; - if (end > this->m_leaf_end_seconds) - end2 = this->m_leaf_end_seconds - this->m_leaf_start_seconds; - else - end2 = end - this->m_leaf_start_seconds; - - size_t s = this->m_leaf_ptr_seconds->template find_first( - m_needle_seconds, start - this->m_leaf_start_seconds, end2); - - if (s == not_found) { - start = this->m_leaf_end_seconds; - continue; - } - return s + this->m_leaf_start_seconds; - } - return not_found; - } - - // see query_engine.cpp for operator specialisations - size_t find_first_local(size_t start, size_t end) override - { - REALM_ASSERT(this->m_table); - - size_t ret = m_condition_column->find(m_value, start, end); - return ret; - } - - virtual std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_condition_column != nullptr); - return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) + " " + - TConditionFunction::description() + " " + util::serializer::print_value(TimestampNode::m_value); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new TimestampNode(*this, patches)); - } -}; - -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); -template <> -size_t TimestampNode::find_first_local(size_t start, size_t end); - -class StringNodeBase : public ParentNode { -public: - using TConditionValue = StringData; - static const bool special_null_node = true; - - StringNodeBase(StringData v, size_t column) - : m_value(v.is_null() ? util::none : util::make_optional(std::string(v))) - { - m_condition_column_idx = column; - } - - void table_changed() override - { - m_condition_column = &get_column_base(m_condition_column_idx); - m_column_type = get_real_column_type(m_condition_column_idx); - } - - void verify_column() const override - { - do_verify_column(m_condition_column); - } - - bool has_search_index() const - { - return m_condition_column->has_search_index(); - } - - void init() override - { - ParentNode::init(); - - m_dT = 10.0; - m_probes = 0; - m_matches = 0; - m_end_s = 0; - m_leaf_start = 0; - m_leaf_end = 0; - } - - void clear_leaf_state() - { - m_leaf.reset(nullptr); - } - - StringNodeBase(const StringNodeBase& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - , m_condition_column(from.m_condition_column) - , m_column_type(from.m_column_type) - , m_leaf_type(from.m_leaf_type) - { - if (m_condition_column && patches) - m_condition_column_idx = m_condition_column->get_column_index(); - } - - virtual std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_condition_column != nullptr); - StringData sd; - if (bool(StringNodeBase::m_value)) { - sd = StringData(StringNodeBase::m_value.value()); - } - return state.describe_column(ParentNode::m_table, m_condition_column->get_column_index()) - + " " + describe_condition() + " " + util::serializer::print_value(sd); - } - -protected: - util::Optional m_value; - - const ColumnBase* m_condition_column = nullptr; - ColumnType m_column_type; - - // Used for linear scan through short/long-string - std::unique_ptr m_leaf; - StringColumn::LeafType m_leaf_type; - size_t m_end_s = 0; - size_t m_leaf_start = 0; - size_t m_leaf_end = 0; - - inline StringData get_string(size_t s) - { - StringData t; - - if (m_column_type == col_type_StringEnum) { - // enum - t = static_cast(m_condition_column)->get(s); - } - else { - // short or long - const StringColumn* asc = static_cast(m_condition_column); - REALM_ASSERT_3(s, <, asc->size()); - if (s >= m_end_s || s < m_leaf_start) { - // we exceeded current leaf's range - clear_leaf_state(); - size_t ndx_in_leaf; - m_leaf = asc->get_leaf(s, ndx_in_leaf, m_leaf_type); - m_leaf_start = s - ndx_in_leaf; - - if (m_leaf_type == StringColumn::leaf_type_Small) - m_end_s = m_leaf_start + static_cast(*m_leaf).size(); - else if (m_leaf_type == StringColumn::leaf_type_Medium) - m_end_s = m_leaf_start + static_cast(*m_leaf).size(); - else - m_end_s = m_leaf_start + static_cast(*m_leaf).size(); - } - - if (m_leaf_type == StringColumn::leaf_type_Small) - t = static_cast(*m_leaf).get(s - m_leaf_start); - else if (m_leaf_type == StringColumn::leaf_type_Medium) - t = static_cast(*m_leaf).get(s - m_leaf_start); - else - t = static_cast(*m_leaf).get_string(s - m_leaf_start); - } - return t; - } -}; - -// Conditions for strings. Note that Equal is specialized later in this file! -template -class StringNode : public StringNodeBase { -public: - StringNode(StringData v, size_t column) - : StringNodeBase(v, column) - { - auto upper = case_map(v, true); - auto lower = case_map(v, false); - if (!upper || !lower) { - error_code = "Malformed UTF-8: " + std::string(v); - } - else { - m_ucase = std::move(*upper); - m_lcase = std::move(*lower); - } - } - - void init() override - { - clear_leaf_state(); - - m_dD = 100.0; - - StringNodeBase::init(); - } - - size_t find_first_local(size_t start, size_t end) override - { - TConditionFunction cond; - - for (size_t s = start; s < end; ++s) { - StringData t = get_string(s); - - if (cond(StringData(m_value), m_ucase.c_str(), m_lcase.c_str(), t)) - return s; - } - return not_found; - } - - virtual std::string describe_condition() const override - { - return TConditionFunction::description(); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new StringNode(*this, patches)); - } - - StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) - : StringNodeBase(from, patches) - , m_ucase(from.m_ucase) - , m_lcase(from.m_lcase) - { - } - -protected: - std::string m_ucase; - std::string m_lcase; -}; - -// Specialization for Contains condition on Strings - we specialize because we can utilize Boyer-Moore -template <> -class StringNode : public StringNodeBase { -public: - StringNode(StringData v, size_t column) - : StringNodeBase(v, column), m_charmap() - { - if (v.size() == 0) - return; - - // Build a dictionary of char-to-last distances in the search string - // (zero indicates that the char is not in needle) - size_t last_char_pos = v.size()-1; - for (size_t i = 0; i < last_char_pos; ++i) { - // we never jump longer increments than 255 chars, even if needle is longer (to fit in one byte) - uint8_t jump = last_char_pos-i < 255 ? static_cast(last_char_pos-i) : 255; - - unsigned char c = v[i]; - m_charmap[c] = jump; - } - } - - void init() override - { - clear_leaf_state(); - - m_dD = 100.0; - - StringNodeBase::init(); - } - - - size_t find_first_local(size_t start, size_t end) override - { - Contains cond; - - for (size_t s = start; s < end; ++s) { - StringData t = get_string(s); - - if (cond(StringData(m_value), m_charmap, t)) - return s; - } - return not_found; - } - - virtual std::string describe_condition() const override - { - return Contains::description(); - } - - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new StringNode(*this, patches)); - } - - StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) - : StringNodeBase(from, patches) - , m_charmap(from.m_charmap) - { - } - -protected: - std::array m_charmap; -}; - -// Specialization for ContainsIns condition on Strings - we specialize because we can utilize Boyer-Moore -template <> -class StringNode : public StringNodeBase { -public: - StringNode(StringData v, size_t column) - : StringNodeBase(v, column), m_charmap() - { - auto upper = case_map(v, true); - auto lower = case_map(v, false); - if (!upper || !lower) { - error_code = "Malformed UTF-8: " + std::string(v); - } - else { - m_ucase = std::move(*upper); - m_lcase = std::move(*lower); - } - - if (v.size() == 0) - return; - - // Build a dictionary of char-to-last distances in the search string - // (zero indicates that the char is not in needle) - size_t last_char_pos = m_ucase.size()-1; - for (size_t i = 0; i < last_char_pos; ++i) { - // we never jump longer increments than 255 chars, even if needle is longer (to fit in one byte) - uint8_t jump = last_char_pos-i < 255 ? static_cast(last_char_pos-i) : 255; - - unsigned char uc = m_ucase[i]; - unsigned char lc = m_lcase[i]; - m_charmap[uc] = jump; - m_charmap[lc] = jump; - } - - } - - void init() override - { - clear_leaf_state(); - - m_dD = 100.0; - - StringNodeBase::init(); - } - - - size_t find_first_local(size_t start, size_t end) override - { - ContainsIns cond; - - for (size_t s = start; s < end; ++s) { - StringData t = get_string(s); - // The current behaviour is to return all results when querying for a null string. - // See comment above Query_NextGen_StringConditions on why every string including "" contains null. - if (!bool(m_value)) { - return s; - } - if (cond(StringData(m_value), m_ucase.c_str(), m_lcase.c_str(), m_charmap, t)) - return s; - } - return not_found; - } - - virtual std::string describe_condition() const override - { - return ContainsIns::description(); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new StringNode(*this, patches)); - } - - StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) - : StringNodeBase(from, patches) - , m_charmap(from.m_charmap) - , m_ucase(from.m_ucase) - , m_lcase(from.m_lcase) - { - } - -protected: - std::array m_charmap; - std::string m_ucase; - std::string m_lcase; -}; - -class StringNodeEqualBase : public StringNodeBase { -public: - StringNodeEqualBase(StringData v, size_t column) - : StringNodeBase(v, column) - { - } - StringNodeEqualBase(const StringNodeEqualBase& from, QueryNodeHandoverPatches* patches) - : StringNodeBase(from, patches) - { - } - ~StringNodeEqualBase() noexcept override - { - deallocate(); - } - - void deallocate() noexcept; - void init() override; - size_t find_first_local(size_t start, size_t end) override; - - virtual std::string describe_condition() const override - { - return Equal::description(); - } - -protected: - inline BinaryData str_to_bin(const StringData& s) noexcept - { - return BinaryData(s.data(), s.size()); - } - - virtual void _search_index_init() = 0; - virtual size_t _find_first_local(size_t start, size_t end) = 0; - - size_t m_key_ndx = not_found; - size_t m_last_indexed; - - // Used for linear scan through enum-string - SequentialGetter m_cse; - - // Used for index lookup - std::unique_ptr m_index_matches; - bool m_index_matches_destroy = false; - std::unique_ptr> m_index_getter; - size_t m_results_start; - size_t m_results_end; - size_t m_last_start; -}; - -// Specialization for Equal condition on Strings - we specialize because we can utilize indexes (if they exist) for -// Equal. This specialisation also supports combining other StringNode conditions into itself in order to -// optimise the non-indexed linear search that can be happen when many conditions are OR'd together in an "IN" query. -// Future optimization: make specialization for greater, notequal, etc -template <> -class StringNode : public StringNodeEqualBase { -public: - using StringNodeEqualBase::StringNodeEqualBase; - - void _search_index_init() override; - - void consume_condition(StringNode* other); - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new StringNode(*this, patches)); - } - - std::string describe(util::serializer::SerialisationState& state) const override; - - StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) - : StringNodeEqualBase(from, patches) - { - for (auto it = from.m_needles.begin(); it != from.m_needles.end(); ++it) { - if (it->data() == nullptr && it->size() == 0) { - m_needles.insert(StringData()); // nulls - } - else { - m_needle_storage.emplace_back(StringBuffer()); - m_needle_storage.back().append(it->data(), it->size()); - m_needles.insert(StringData(m_needle_storage.back().data(), m_needle_storage.back().size())); - } - } - } - -private: - template - size_t find_first_in(ArrayType& array, size_t begin, size_t end); - - size_t _find_first_local(size_t start, size_t end) override; - std::unordered_set m_needles; - std::vector m_needle_storage; -}; - - -// Specialization for EqualIns condition on Strings - we specialize because we can utilize indexes (if they exist) for -// EqualIns. -template <> -class StringNode : public StringNodeEqualBase { -public: - StringNode(StringData v, size_t column) - : StringNodeEqualBase(v, column) - { - auto upper = case_map(v, true); - auto lower = case_map(v, false); - if (!upper || !lower) { - error_code = "Malformed UTF-8: " + std::string(v); - } - else { - m_ucase = std::move(*upper); - m_lcase = std::move(*lower); - } - } - - void _search_index_init() override; - - virtual std::string describe_condition() const override - { - return EqualIns::description(); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new StringNode(*this, patches)); - } - - StringNode(const StringNode& from, QueryNodeHandoverPatches* patches) - : StringNodeEqualBase(from, patches) - , m_ucase(from.m_ucase) - , m_lcase(from.m_lcase) - { - } - -private: - std::string m_ucase; - std::string m_lcase; - - size_t _find_first_local(size_t start, size_t end) override; -}; - -// OR node contains at least two node pointers: Two or more conditions to OR -// together in m_conditions, and the next AND condition (if any) in m_child. -// -// For 'second.equal(23).begin_group().first.equal(111).Or().first.equal(222).end_group().third().equal(555)', this -// will first set m_conditions[0] = left-hand-side through constructor, and then later, when .first.equal(222) is -// invoked, invocation will set m_conditions[1] = right-hand-side through Query& Query::Or() (see query.cpp). -// In there, m_child is also set to next AND condition (if any exists) following the OR. -class OrNode : public ParentNode { -public: - OrNode(std::unique_ptr condition) - { - m_dT = 50.0; - if (condition) - m_conditions.emplace_back(std::move(condition)); - } - - OrNode(const OrNode& other, QueryNodeHandoverPatches* patches) - : ParentNode(other, patches) - { - for (const auto& condition : other.m_conditions) { - m_conditions.emplace_back(condition->clone(patches)); - } - } - - void table_changed() override - { - for (auto& condition : m_conditions) { - condition->set_table(*m_table); - } - } - - void verify_column() const override - { - for (auto& condition : m_conditions) { - condition->verify_column(); - } - } - - std::string describe(util::serializer::SerialisationState& state) const override - { - std::string s; - for (size_t i = 0; i < m_conditions.size(); ++i) { - if (m_conditions[i]) { - s += m_conditions[i]->describe_expression(state); - if (i != m_conditions.size() - 1) { - s += " or "; - } - } - } - if (m_conditions.size() > 1) { - s = "(" + s + ")"; - } - return s; - } - - void init() override - { - ParentNode::init(); - - m_dD = 10.0; - - std::sort(m_conditions.begin(), m_conditions.end(), - [](auto& a, auto& b) { return a->m_condition_column_idx < b->m_condition_column_idx; }); - - combine_conditions>(); - combine_conditions>(); - combine_conditions>(); - - m_start.clear(); - m_start.resize(m_conditions.size(), 0); - - m_last.clear(); - m_last.resize(m_conditions.size(), 0); - - m_was_match.clear(); - m_was_match.resize(m_conditions.size(), false); - - std::vector v; - for (auto& condition : m_conditions) { - condition->init(); - v.clear(); - condition->gather_children(v); - } - } - - size_t find_first_local(size_t start, size_t end) override - { - if (start >= end) - return not_found; - - size_t index = not_found; - - for (size_t c = 0; c < m_conditions.size(); ++c) { - // out of order search; have to discard cached results - if (start < m_start[c]) { - m_last[c] = 0; - m_was_match[c] = false; - } - // already searched this range and didn't match - else if (m_last[c] >= end) - continue; - // already search this range and *did* match - else if (m_was_match[c] && m_last[c] >= start) { - if (index > m_last[c]) - index = m_last[c]; - continue; - } - - m_start[c] = start; - size_t fmax = std::max(m_last[c], start); - size_t f = m_conditions[c]->find_first(fmax, end); - m_was_match[c] = f != not_found; - m_last[c] = f == not_found ? end : f; - if (f != not_found && index > m_last[c]) - index = m_last[c]; - } - - return index; - } - - std::string validate() override - { - if (error_code != "") - return error_code; - if (m_conditions.size() == 0) - return "Missing left-hand side of OR"; - if (m_conditions.size() == 1) - return "Missing right-hand side of OR"; - std::string s; - if (m_child != 0) - s = m_child->validate(); - if (s != "") - return s; - for (size_t i = 0; i < m_conditions.size(); ++i) { - s = m_conditions[i]->validate(); - if (s != "") - return s; - } - return ""; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new OrNode(*this, patches)); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - for (auto it = m_conditions.rbegin(); it != m_conditions.rend(); ++it) - (*it)->apply_handover_patch(patches, group); - - ParentNode::apply_handover_patch(patches, group); - } - - std::vector> m_conditions; - -private: - template - void combine_conditions() { - QueryNodeType* first_match = nullptr; - QueryNodeType* advance = nullptr; - auto it = m_conditions.begin(); - while (it != m_conditions.end()) { - // Only try to optimize on QueryNodeType conditions without search index - auto node = it->get(); - if ((first_match = dynamic_cast(node)) && first_match->m_child == nullptr && - !first_match->has_search_index()) { - auto col_ndx = first_match->m_condition_column_idx; - auto next = it + 1; - while (next != m_conditions.end() && (*next)->m_condition_column_idx == col_ndx) { - auto next_node = next->get(); - if ((advance = dynamic_cast(next_node)) && next_node->m_child == nullptr) { - first_match->consume_condition(advance); - next = m_conditions.erase(next); - } - else { - ++next; - } - } - it = next; - } - else { - ++it; - } - } - } - - // start index of the last find for each cond - std::vector m_start; - // last looked at index of the lasft find for each cond - // is a matching index if m_was_match is true - std::vector m_last; - std::vector m_was_match; -}; - - -class NotNode : public ParentNode { -public: - NotNode(std::unique_ptr condition) - : m_condition(std::move(condition)) - { - m_dT = 50.0; - } - - void table_changed() override - { - m_condition->set_table(*m_table); - } - - void verify_column() const override - { - m_condition->verify_column(); - } - - void init() override - { - ParentNode::init(); - - m_dD = 10.0; - - std::vector v; - - m_condition->init(); - v.clear(); - m_condition->gather_children(v); - - // Heuristics bookkeeping: - m_known_range_start = 0; - m_known_range_end = 0; - m_first_in_known_range = not_found; - } - - size_t find_first_local(size_t start, size_t end) override; - - std::string validate() override - { - if (error_code != "") - return error_code; - if (m_condition == 0) - return "Missing argument to Not"; - std::string s; - if (m_child != 0) - s = m_child->validate(); - if (s != "") - return s; - s = m_condition->validate(); - if (s != "") - return s; - return ""; - } - - virtual std::string describe(util::serializer::SerialisationState& state) const override - { - if (m_condition) { - return "!(" + m_condition->describe_expression(state) + ")"; - } - return "!()"; - } - - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new NotNode(*this, patches)); - } - - NotNode(const NotNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_condition(from.m_condition ? from.m_condition->clone(patches) : nullptr) - , m_known_range_start(from.m_known_range_start) - , m_known_range_end(from.m_known_range_end) - , m_first_in_known_range(from.m_first_in_known_range) - { - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_condition->apply_handover_patch(patches, group); - ParentNode::apply_handover_patch(patches, group); - } - - std::unique_ptr m_condition; - -private: - // FIXME This heuristic might as well be reused for all condition nodes. - size_t m_known_range_start; - size_t m_known_range_end; - size_t m_first_in_known_range; - - bool evaluate_at(size_t rowndx); - void update_known(size_t start, size_t end, size_t first); - size_t find_first_loop(size_t start, size_t end); - size_t find_first_covers_known(size_t start, size_t end); - size_t find_first_covered_by_known(size_t start, size_t end); - size_t find_first_overlap_lower(size_t start, size_t end); - size_t find_first_overlap_upper(size_t start, size_t end); - size_t find_first_no_overlap(size_t start, size_t end); -}; - - -// Compare two columns with eachother row-by-row -template -class TwoColumnsNode : public ParentNode { -public: - using TConditionValue = typename ColType::value_type; - - TwoColumnsNode(size_t column1, size_t column2) - { - m_dT = 100.0; - m_condition_column_idx1 = column1; - m_condition_column_idx2 = column2; - } - - ~TwoColumnsNode() noexcept override - { - delete[] m_value.data(); - } - - void table_changed() override - { - m_getter1.init(&get_column(m_condition_column_idx1)); - m_getter2.init(&get_column(m_condition_column_idx2)); - } - - void verify_column() const override - { - do_verify_column(m_getter1.m_column, m_condition_column_idx1); - do_verify_column(m_getter2.m_column, m_condition_column_idx2); - } - - virtual std::string describe(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_getter1.m_column != nullptr && m_getter2.m_column != nullptr); - return state.describe_column(ParentNode::m_table, m_getter1.m_column->get_column_index()) - + " " + describe_condition() + " " - + state.describe_column(ParentNode::m_table,m_getter2.m_column->get_column_index()); - } - - virtual std::string describe_condition() const override - { - return TConditionFunction::description(); - } - - void init() override - { - ParentNode::init(); - m_dD = 100.0; - } - - size_t find_first_local(size_t start, size_t end) override - { - size_t s = start; - - while (s < end) { - if (std::is_same::value) { - // For int64_t we've created an array intrinsics named compare_leafs which template expands bitwidths - // of boths arrays to make Get faster. - m_getter1.cache_next(s); - m_getter2.cache_next(s); - - QueryState qs; - bool resume = m_getter1.m_leaf_ptr->template compare_leafs( - m_getter2.m_leaf_ptr, s - m_getter1.m_leaf_start, m_getter1.local_end(end), 0, &qs, - CallbackDummy()); - - if (resume) - s = m_getter1.m_leaf_end; - else - return to_size_t(qs.m_state) + m_getter1.m_leaf_start; - } - else { -// This is for float and double. - -#if 0 && defined(REALM_COMPILER_AVX) -// AVX has been disabled because of array alignment (see https://app.asana.com/0/search/8836174089724/5763107052506) -// -// For AVX you can call things like if (sseavx<1>()) to test for AVX, and then utilize _mm256_movemask_ps (VC) -// or movemask_cmp_ps (gcc/clang) -// -// See https://github.com/rrrlasse/realm/tree/AVX for an example of utilizing AVX for a two-column search which has -// been benchmarked to: floats: 288 ms vs 552 by using AVX compared to 2-level-unrolled FPU loop. doubles: 415 ms vs -// 475 (more bandwidth bound). Tests against SSE have not been performed; AVX may not pay off. Please benchmark -#endif - - TConditionValue v1 = m_getter1.get_next(s); - TConditionValue v2 = m_getter2.get_next(s); - TConditionFunction C; - - if (C(v1, v2)) - return s; - else - s++; - } - } - return not_found; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new TwoColumnsNode(*this, patches)); - } - - TwoColumnsNode(const TwoColumnsNode& from, QueryNodeHandoverPatches* patches) - : ParentNode(from, patches) - , m_value(from.m_value) - , m_condition_column(from.m_condition_column) - , m_column_type(from.m_column_type) - , m_condition_column_idx1(from.m_condition_column_idx1) - , m_condition_column_idx2(from.m_condition_column_idx2) - { - if (m_condition_column) - m_condition_column_idx = m_condition_column->get_column_index(); - copy_getter(m_getter1, m_condition_column_idx1, from.m_getter1, patches); - copy_getter(m_getter2, m_condition_column_idx2, from.m_getter2, patches); - } - -private: - BinaryData m_value; - const BinaryColumn* m_condition_column = nullptr; - ColumnType m_column_type; - - size_t m_condition_column_idx1 = not_found; - size_t m_condition_column_idx2 = not_found; - - SequentialGetter m_getter1; - SequentialGetter m_getter2; -}; - - -// For Next-Generation expressions like col1 / col2 + 123 > col4 * 100. -class ExpressionNode : public ParentNode { -public: - ExpressionNode(std::unique_ptr); - - void init() override; - size_t find_first_local(size_t start, size_t end) override; - - void table_changed() override; - void verify_column() const override; - - virtual std::string describe(util::serializer::SerialisationState& state) const override; - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override; - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override; - -private: - ExpressionNode(const ExpressionNode& from, QueryNodeHandoverPatches* patches); - - std::unique_ptr m_expression; -}; - - -struct LinksToNodeHandoverPatch : public QueryNodeHandoverPatch { - std::vector> m_target_rows; - size_t m_origin_column; -}; - -class LinksToNode : public ParentNode { -public: - LinksToNode(size_t origin_column_index, const ConstRow& target_row) - : m_origin_column(origin_column_index) - , m_target_rows(1, target_row) - { - m_dD = 10.0; - m_dT = 50.0; - } - - LinksToNode(size_t origin_column_index, const std::vector& target_rows) - : m_origin_column(origin_column_index) - , m_target_rows(target_rows) - { - m_dD = 10.0; - m_dT = 50.0; - } - - void table_changed() override - { - m_column_type = m_table->get_column_type(m_origin_column); - m_column = &const_cast(m_table.get())->get_column_link_base(m_origin_column); - REALM_ASSERT(m_column_type == type_Link || m_column_type == type_LinkList); - } - - void verify_column() const override - { - do_verify_column(m_column, m_origin_column); - } - - virtual std::string describe(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialising a query which links to an object is currently unsupported."); - // We can do something like the following when core gets stable keys - //return describe_column() + " " + describe_condition() + " " + util::serializer::print_value(m_target_row.get_index()); - } - virtual std::string describe_condition() const override - { - return "links to"; - } - - - size_t find_first_local(size_t start, size_t end) override - { - REALM_ASSERT(m_column); - if (m_column_type == type_Link) { - LinkColumn& cl = static_cast(*m_column); - for (auto& row : m_target_rows) { - if (row.is_attached()) { - // LinkColumn stores link to row N as the integer N + 1 - auto pos = cl.find_first(row.get_index() + 1, start, end); - if (pos != realm::npos) { - return pos; - } - } - } - } - else if (m_column_type == type_LinkList) { - LinkListColumn& cll = static_cast(*m_column); - - for (size_t i = start; i < end; i++) { - LinkViewRef lv = cll.get(i); - for (auto& row : m_target_rows) { - if (row.is_attached()) { - if (lv->find(row.get_index()) != not_found) - return i; - } - } - } - } - - return not_found; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(patches ? new LinksToNode(*this, patches) : new LinksToNode(*this)); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - REALM_ASSERT(patches.size()); - std::unique_ptr abstract_patch = std::move(patches.back()); - patches.pop_back(); - - auto patch = dynamic_cast(abstract_patch.get()); - REALM_ASSERT(patch); - - m_origin_column = patch->m_origin_column; - auto sz = patch->m_target_rows.size(); - m_target_rows.resize(sz); - for (size_t i = 0; i < sz; i++) { - m_target_rows[i].apply_and_consume_patch(patch->m_target_rows[i], group); - } - - ParentNode::apply_handover_patch(patches, group); - } - -private: - size_t m_origin_column = npos; - std::vector m_target_rows; - LinkColumnBase* m_column = nullptr; - DataType m_column_type; - - LinksToNode(const LinksToNode& source, QueryNodeHandoverPatches* patches) - : ParentNode(source, patches) - { - auto patch = std::make_unique(); - patch->m_origin_column = source.m_column->get_column_index(); - auto sz = source.m_target_rows.size(); - patch->m_target_rows.resize(sz); - for (size_t i = 0; i < sz; i++) { - ConstRow::generate_patch(source.m_target_rows[i], patch->m_target_rows[i]); - } - patches->push_back(std::move(patch)); - } -}; - -} // namespace realm - -#endif // REALM_QUERY_ENGINE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/query_expression.hpp b/Lesson14/Pods/Realm/include/core/realm/query_expression.hpp deleted file mode 100644 index bd6e1a8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/query_expression.hpp +++ /dev/null @@ -1,4145 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -/* -This file lets you write queries in C++ syntax like: Expression* e = (first + 1 / second >= third + 12.3); - -Type conversion/promotion semantics is the same as in the C++ expressions, e.g float + int > double == float + -(float)int > double. - - -Grammar: ------------------------------------------------------------------------------------------------------------------------ - Expression: Subexpr2 Compare Subexpr2 - operator! Expression - - Subexpr2: Value - Columns - Subexpr2 Operator Subexpr2 - power(Subexpr2) // power(x) = x * x, as example of unary operator - - Value: T - - Operator>: +, -, *, / - - Compare: ==, !=, >=, <=, >, < - - T: bool, int, int64_t, float, double, StringData - - -Class diagram ------------------------------------------------------------------------------------------------------------------------ -Subexpr2 - void evaluate(size_t i, ValueBase* destination) - -Compare: public Subexpr2 - size_t find_first(size_t start, size_t end) // main method that executes query - - unique_ptr m_left; // left expression subtree - unique_ptr m_right; // right expression subtree - -Operator: public Subexpr2 - void evaluate(size_t i, ValueBase* destination) - unique_ptr m_left; // left expression subtree - unique_ptr m_right; // right expression subtree - -Value: public Subexpr2 - void evaluate(size_t i, ValueBase* destination) - T m_v[8]; - -Columns: public Subexpr2 - void evaluate(size_t i, ValueBase* destination) - SequentialGetter sg; // class bound to a column, lets you read values in a fast way - Table* m_table; - -class ColumnAccessor<>: public Columns - - -Call diagram: ------------------------------------------------------------------------------------------------------------------------ -Example of 'table.first > 34.6 + table.second': - -size_t Compare::find_first()-------------+ - | | - | | - | | - +--> Columns::evaluate() +--------> Operator::evaluate() - | | - Value::evaluate() Columns::evaluate() - -Operator, Value and Columns have an evaluate(size_t i, ValueBase* destination) method which returns a Value -containing 8 values representing table rows i...i + 7. - -So Value contains 8 concecutive values and all operations are based on these chunks. This is -to save overhead by virtual calls needed for evaluating a query that has been dynamically constructed at runtime. - - -Memory allocation: ------------------------------------------------------------------------------------------------------------------------ -Subexpressions created by the end-user are stack allocated. They are cloned to the heap when passed to UnaryOperator, -Operator, and Compare. Those types own the clones and deallocate them when destroyed. - - -Caveats, notes and todos ------------------------------------------------------------------------------------------------------------------------ - * Perhaps disallow columns from two different tables in same expression - * The name Columns (with s) an be confusing because we also have Column (without s) - * We have Columns::m_table, Query::m_table and ColumnAccessorBase::m_table that point at the same thing, even with - ColumnAccessor<> extending Columns. So m_table is redundant, but this is in order to keep class dependencies and - entanglement low so that the design is flexible (if you perhaps later want a Columns class that is not dependent - on ColumnAccessor) - -Nulls ------------------------------------------------------------------------------------------------------------------------ -First note that at array level, nulls are distinguished between non-null in different ways: -String: - m_data == 0 && m_size == 0 - -Integer, Bool, OldDateTime stored in ArrayIntNull: - value == get(0) (entry 0 determins a magic value that represents nulls) - -Float/double: - null::is_null(value) which tests if value bit-matches one specific bit pattern reserved for null - -The Columns class encapsulates all this into a simple class that, for any type T has - evaluate(size_t index) that reads values from a column, taking nulls in count - get(index) - set(index) - is_null(index) - set_null(index) -*/ - -#ifndef REALM_QUERY_EXPRESSION_HPP -#define REALM_QUERY_EXPRESSION_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -// Normally, if a next-generation-syntax condition is supported by the old query_engine.hpp, a query_engine node is -// created because it's faster (by a factor of 5 - 10). Because many of our existing next-generation-syntax unit -// unit tests are indeed simple enough to fallback to old query_engine, query_expression gets low test coverage. Undef -// flag to get higher query_expression test coverage. This is a good idea to try out each time you develop on/modify -// query_expression. - -#define REALM_OLDQUERY_FALLBACK - -namespace realm { - -template -T minimum(T a, T b) -{ - return a < b ? a : b; -} - -#ifdef REALM_OLDQUERY_FALLBACK -// Hack to avoid template instantiation errors. See create(). Todo, see if we can simplify only_numeric somehow -namespace _impl { - -template -inline T only_numeric(U in) -{ - return static_cast(util::unwrap(in)); -} - -template -inline int only_numeric(const StringData&) -{ - REALM_ASSERT(false); - return 0; -} - -template -inline int only_numeric(const BinaryData&) -{ - REALM_ASSERT(false); - return 0; -} - -template -inline StringData only_string_op_types(T in) -{ - REALM_ASSERT(false); - static_cast(in); - return StringData(); -} - -inline BinaryData only_string_op_types(BinaryData in) -{ - return in; -} - -template <> -inline StringData only_string_op_types(StringData in) -{ - return in; -} - -template -inline T no_timestamp(U in) -{ - return static_cast(util::unwrap(in)); -} - -template -inline int no_timestamp(const Timestamp&) -{ - REALM_ASSERT(false); - return 0; -} - -} // namespace _impl - -#endif // REALM_OLDQUERY_FALLBACK - -template -struct Plus { - T operator()(T v1, T v2) const - { - return v1 + v2; - } - static std::string description() - { - return "+"; - } - typedef T type; -}; - -template -struct Minus { - T operator()(T v1, T v2) const - { - return v1 - v2; - } - static std::string description() - { - return "-"; - } - typedef T type; -}; - -template -struct Div { - T operator()(T v1, T v2) const - { - return v1 / v2; - } - static std::string description() - { - return "/"; - } - typedef T type; -}; - -template -struct Mul { - T operator()(T v1, T v2) const - { - return v1 * v2; - } - static std::string description() - { - return "*"; - } - typedef T type; -}; - -// Unary operator -template -struct Pow { - T operator()(T v) const - { - return v * v; - } - static std::string description() - { - return "^"; - } - typedef T type; -}; - -// Finds a common type for T1 and T2 according to C++ conversion/promotion in arithmetic (float + int => float, etc) -template ::is_integer || std::is_same::value, - bool T2_is_int = std::numeric_limits::is_integer || std::is_same::value, - bool T1_is_widest = (sizeof(T1) > sizeof(T2) || std::is_same::value)> -struct Common; -template -struct Common { - typedef T1 type; -}; -template -struct Common { - typedef T2 type; -}; -template -struct Common { - typedef T1 type; -}; -template -struct Common { - typedef T2 type; -}; - - -struct RowIndex { - enum DetachedTag { - Detached, - }; - - explicit RowIndex() - : m_row_index(npos) - { - } - explicit RowIndex(size_t row_index) - : m_row_index(row_index) - { - } - RowIndex(DetachedTag) - : m_row_index() - { - } - - bool is_attached() const - { - return bool(m_row_index); - } - bool is_null() const - { - return is_attached() && *m_row_index == npos; - } - - bool operator==(const RowIndex& other) const - { - // Row indexes that are detached are never equal to any other row index. - if (!is_attached() || !other.is_attached()) - return false; - return m_row_index == other.m_row_index; - } - bool operator!=(const RowIndex& other) const - { - return !(*this == other); - } -private: - util::Optional m_row_index; -}; - -struct ValueBase { - static const size_t chunk_size = 8; - virtual void export_bool(ValueBase& destination) const = 0; - virtual void export_Timestamp(ValueBase& destination) const = 0; - virtual void export_int(ValueBase& destination) const = 0; - virtual void export_float(ValueBase& destination) const = 0; - virtual void export_int64_t(ValueBase& destination) const = 0; - virtual void export_double(ValueBase& destination) const = 0; - virtual void export_StringData(ValueBase& destination) const = 0; - virtual void export_BinaryData(ValueBase& destination) const = 0; - virtual void export_RowIndex(ValueBase& destination) const = 0; - virtual void export_null(ValueBase& destination) const = 0; - virtual void import(const ValueBase& destination) = 0; - - // If true, all values in the class come from a link list of a single field in the parent table (m_table). If - // false, then values come from successive rows of m_table (query operations are operated on in bulks for speed) - bool m_from_link_list; - - // Number of values stored in the class. - size_t m_values; -}; - -class Expression { -public: - Expression() - { - } - virtual ~Expression() - { - } - - virtual double init() - { - return 50.0; // Default dT - } - - virtual size_t find_first(size_t start, size_t end) const = 0; - virtual void set_base_table(const Table* table) = 0; - virtual void verify_column() const = 0; - virtual const Table* get_base_table() const = 0; - virtual std::string description(util::serializer::SerialisationState& state) const = 0; - - virtual std::unique_ptr clone(QueryNodeHandoverPatches*) const = 0; - virtual void apply_handover_patch(QueryNodeHandoverPatches&, Group&) - { - } -}; - -template -std::unique_ptr make_expression(Args&&... args) -{ - return std::unique_ptr(new T(std::forward(args)...)); -} - -class Subexpr { -public: - virtual ~Subexpr() - { - } - - virtual std::unique_ptr clone(QueryNodeHandoverPatches* = nullptr) const = 0; - virtual void apply_handover_patch(QueryNodeHandoverPatches&, Group&) - { - } - - // When the user constructs a query, it always "belongs" to one single base/parent table (regardless of - // any links or not and regardless of any queries assembled with || or &&). When you do a Query::find(), - // then Query::m_table is set to this table, and set_base_table() is called on all Columns and LinkMaps in - // the query expression tree so that they can set/update their internals as required. - // - // During thread-handover of a Query, set_base_table() is also called to make objects point at the new table - // instead of the old one from the old thread. - virtual void set_base_table(const Table*) - { - } - - virtual void verify_column() const = 0; - virtual std::string description(util::serializer::SerialisationState& state) const = 0; - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and - // binds it to a Query at a later time - virtual const Table* get_base_table() const - { - return nullptr; - } - - virtual bool has_constant_evaluation() const - { - return false; - } - - virtual bool has_search_index() const - { - return false; - } - - virtual std::vector find_all(util::Optional) const - { - return {}; - } - - virtual void evaluate(size_t index, ValueBase& destination) = 0; -}; - -template -std::unique_ptr make_subexpr(Args&&... args) -{ - return std::unique_ptr(new T(std::forward(args)...)); -} - -template -class Columns; -template -class Value; -class ConstantStringValue; -template -class Subexpr2; -template -class Operator; -template -class UnaryOperator; -template -class SizeOperator; -template -class Compare; -template -class UnaryLinkCompare; -class ColumnAccessorBase; - - -// Handle cases where left side is a constant (int, float, int64_t, double, StringData) -template -Query create(L left, const Subexpr2& right) -{ -// Purpose of below code is to intercept the creation of a condition and test if it's supported by the old -// query_engine.hpp which is faster. If it's supported, create a query_engine.hpp node, otherwise create a -// query_expression.hpp node. -// -// This method intercepts only Value Subexpr2. Interception of Subexpr2 Subexpr is elsewhere. - -#ifdef REALM_OLDQUERY_FALLBACK // if not defined, then never fallback to query_engine.hpp; always use query_expression - const Columns* column = dynamic_cast*>(&right); - // TODO: recognize size operator expressions - // auto size_operator = dynamic_cast, Subexpr>*>(&right); - - if (column && ((std::numeric_limits::is_integer && std::numeric_limits::is_integer) || - (std::is_same::value && std::is_same::value) || - (std::is_same::value && std::is_same::value) || - (std::is_same::value && std::is_same::value) || - (std::is_same::value && std::is_same::value) || - (std::is_same::value && std::is_same::value)) && - !column->links_exist()) { - const Table* t = column->get_base_table(); - Query q = Query(*t); - - if (std::is_same::value) - q.greater(column->column_ndx(), _impl::only_numeric(left)); - else if (std::is_same::value) - q.less(column->column_ndx(), _impl::only_numeric(left)); - else if (std::is_same::value) - q.equal(column->column_ndx(), left); - else if (std::is_same::value) - q.not_equal(column->column_ndx(), left); - else if (std::is_same::value) - q.greater_equal(column->column_ndx(), _impl::only_numeric(left)); - else if (std::is_same::value) - q.less_equal(column->column_ndx(), _impl::only_numeric(left)); - else if (std::is_same::value) - q.equal(column->column_ndx(), _impl::only_string_op_types(left), false); - else if (std::is_same::value) - q.not_equal(column->column_ndx(), _impl::only_string_op_types(left), false); - else if (std::is_same::value) - q.begins_with(column->column_ndx(), _impl::only_string_op_types(left)); - else if (std::is_same::value) - q.begins_with(column->column_ndx(), _impl::only_string_op_types(left), false); - else if (std::is_same::value) - q.ends_with(column->column_ndx(), _impl::only_string_op_types(left)); - else if (std::is_same::value) - q.ends_with(column->column_ndx(), _impl::only_string_op_types(left), false); - else if (std::is_same::value) - q.contains(column->column_ndx(), _impl::only_string_op_types(left)); - else if (std::is_same::value) - q.contains(column->column_ndx(), _impl::only_string_op_types(left), false); - else if (std::is_same::value) - q.like(column->column_ndx(), _impl::only_string_op_types(left)); - else if (std::is_same::value) - q.like(column->column_ndx(), _impl::only_string_op_types(left), false); - else { - // query_engine.hpp does not support this Cond. Please either add support for it in query_engine.hpp or - // fallback to using use 'return new Compare<>' instead. - REALM_ASSERT(false); - } - // Return query_engine.hpp node - return q; - } - else -#endif - { - // Return query_expression.hpp node - using CommonType = typename Common::type; - using ValueType = - typename std::conditional::value, ConstantStringValue, Value>::type; - return make_expression>(make_subexpr(left), right.clone()); - } -} - - -// All overloads where left-hand-side is Subexpr2: -// -// left-hand-side operator right-hand-side -// Subexpr2 +, -, *, /, <, >, ==, !=, <=, >= R, Subexpr2 -// -// For L = R = {int, int64_t, float, double, StringData, Timestamp}: -template -class Overloads { - typedef typename Common::type CommonType; - - std::unique_ptr clone_subexpr() const - { - return static_cast&>(*this).clone(); - } - -public: - // Arithmetic, right side constant - Operator> operator+(R right) const - { - return {clone_subexpr(), make_subexpr>(right)}; - } - Operator> operator-(R right) const - { - return {clone_subexpr(), make_subexpr>(right)}; - } - Operator> operator*(R right) const - { - return {clone_subexpr(), make_subexpr>(right)}; - } - Operator> operator/(R right) const - { - return {clone_subexpr(), make_subexpr>(right)}; - } - - // Arithmetic, right side subexpression - Operator> operator+(const Subexpr2& right) const - { - return {clone_subexpr(), right.clone()}; - } - Operator> operator-(const Subexpr2& right) const - { - return {clone_subexpr(), right.clone()}; - } - Operator> operator*(const Subexpr2& right) const - { - return {clone_subexpr(), right.clone()}; - } - Operator> operator/(const Subexpr2& right) const - { - return {clone_subexpr(), right.clone()}; - } - - // Compare, right side constant - Query operator>(R right) - { - return create(right, static_cast&>(*this)); - } - Query operator<(R right) - { - return create(right, static_cast&>(*this)); - } - Query operator>=(R right) - { - return create(right, static_cast&>(*this)); - } - Query operator<=(R right) - { - return create(right, static_cast&>(*this)); - } - Query operator==(R right) - { - return create(right, static_cast&>(*this)); - } - Query operator!=(R right) - { - return create(right, static_cast&>(*this)); - } - - // Purpose of this method is to intercept the creation of a condition and test if it's supported by the old - // query_engine.hpp which is faster. If it's supported, create a query_engine.hpp node, otherwise create a - // query_expression.hpp node. - // - // This method intercepts Subexpr2 Subexpr2 only. Value Subexpr2 is intercepted elsewhere. - template - Query create2(const Subexpr2& right) - { -#ifdef REALM_OLDQUERY_FALLBACK // if not defined, never fallback query_engine; always use query_expression - // Test if expressions are of type Columns. Other possibilities are Value and Operator. - const Columns* left_col = dynamic_cast*>(static_cast*>(this)); - const Columns* right_col = dynamic_cast*>(&right); - - // query_engine supports 'T-column ' for T = {int64_t, float, double}, op = {<, >, ==, !=, <=, - // >=}, - // but only if both columns are non-nullable, and aren't in linked tables. - if (left_col && right_col && std::is_same::value && !left_col->is_nullable() && - !right_col->is_nullable() && !left_col->links_exist() && !right_col->links_exist() && - !std::is_same::value) { - const Table* t = left_col->get_base_table(); - Query q = Query(*t); - - if (std::numeric_limits::is_integer || std::is_same::value) { - if (std::is_same::value) - q.less_int(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_int(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.equal_int(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.not_equal_int(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.less_equal_int(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_equal_int(left_col->column_ndx(), right_col->column_ndx()); - else { - REALM_ASSERT(false); - } - } - else if (std::is_same::value) { - if (std::is_same::value) - q.less_float(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_float(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.equal_float(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.not_equal_float(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.less_equal_float(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_equal_float(left_col->column_ndx(), right_col->column_ndx()); - else { - REALM_ASSERT(false); - } - } - else if (std::is_same::value) { - if (std::is_same::value) - q.less_double(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_double(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.equal_double(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.not_equal_double(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.less_equal_double(left_col->column_ndx(), right_col->column_ndx()); - else if (std::is_same::value) - q.greater_equal_double(left_col->column_ndx(), right_col->column_ndx()); - else { - REALM_ASSERT(false); - } - } - else { - REALM_ASSERT(false); - } - // Return query_engine.hpp node - return q; - } - else -#endif - { - // Return query_expression.hpp node - return make_expression::type>>(clone_subexpr(), right.clone()); - } - } - - // Compare, right side subexpression - Query operator==(const Subexpr2& right) - { - return create2(right); - } - Query operator!=(const Subexpr2& right) - { - return create2(right); - } - Query operator>(const Subexpr2& right) - { - return create2(right); - } - Query operator<(const Subexpr2& right) - { - return create2(right); - } - Query operator>=(const Subexpr2& right) - { - return create2(right); - } - Query operator<=(const Subexpr2& right) - { - return create2(right); - } -}; - -// With this wrapper class we can define just 20 overloads inside Overloads instead of 5 * 20 = 100. Todo: We -// can -// consider if it's simpler/better to remove this class completely and just list all 100 overloads manually anyway. -template -class Subexpr2 : public Subexpr, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads, - public Overloads { -public: - virtual ~Subexpr2() - { - } - -#define RLM_U2(t, o) using Overloads::operator o; -#define RLM_U(o) \ - RLM_U2(int, o) \ - RLM_U2(float, o) \ - RLM_U2(double, o) \ - RLM_U2(int64_t, o) \ - RLM_U2(StringData, o) RLM_U2(bool, o) RLM_U2(OldDateTime, o) RLM_U2(Timestamp, o) RLM_U2(null, o) - RLM_U(+) RLM_U(-) RLM_U(*) RLM_U(/) RLM_U(>) RLM_U(<) RLM_U(==) RLM_U(!=) RLM_U(>=) RLM_U(<=) -}; - -// Subexpr2 only provides equality comparisons. Their implementations can be found later in this file. -template <> -class Subexpr2 : public Subexpr { -}; - -template <> -class Subexpr2 : public Subexpr, public Overloads { -public: - Query equal(StringData sd, bool case_sensitive = true); - Query equal(const Subexpr2& col, bool case_sensitive = true); - Query not_equal(StringData sd, bool case_sensitive = true); - Query not_equal(const Subexpr2& col, bool case_sensitive = true); - Query begins_with(StringData sd, bool case_sensitive = true); - Query begins_with(const Subexpr2& col, bool case_sensitive = true); - Query ends_with(StringData sd, bool case_sensitive = true); - Query ends_with(const Subexpr2& col, bool case_sensitive = true); - Query contains(StringData sd, bool case_sensitive = true); - Query contains(const Subexpr2& col, bool case_sensitive = true); - Query like(StringData sd, bool case_sensitive = true); - Query like(const Subexpr2& col, bool case_sensitive = true); -}; - -template <> -class Subexpr2 : public Subexpr, public Overloads { -public: - Query equal(BinaryData sd, bool case_sensitive = true); - Query equal(const Subexpr2& col, bool case_sensitive = true); - Query not_equal(BinaryData sd, bool case_sensitive = true); - Query not_equal(const Subexpr2& col, bool case_sensitive = true); - Query begins_with(BinaryData sd, bool case_sensitive = true); - Query begins_with(const Subexpr2& col, bool case_sensitive = true); - Query ends_with(BinaryData sd, bool case_sensitive = true); - Query ends_with(const Subexpr2& col, bool case_sensitive = true); - Query contains(BinaryData sd, bool case_sensitive = true); - Query contains(const Subexpr2& col, bool case_sensitive = true); - Query like(BinaryData sd, bool case_sensitive = true); - Query like(const Subexpr2& col, bool case_sensitive = true); -}; - - -/* -This class is used to store N values of type T = {int64_t, bool, OldDateTime or StringData}, and allows an entry -to be null too. It's used by the Value class for internal storage. - -To indicate nulls, we could have chosen a separate bool vector or some other bitmask construction. But for -performance, we customize indication of nulls to match the same indication that is used in the persisted database -file - -Queries in query_expression.hpp execute by processing chunks of 8 rows at a time. Assume you have a column: - - price (int) = {1, 2, 3, null, 1, 6, 6, 9, 5, 2, null} - -And perform a query: - - Query q = (price + 2 == 5); - -query_expression.hpp will then create a NullableVector = {5, 5, 5, 5, 5, 5, 5, 5} and then read values -NullableVector = {1, 2, 3, null, 1, 6, 6, 9} from the column, and then perform `+` and `==` on these chunks. - -See the top of this file for more information on all this. - -Assume the user specifies the null constant in a query: - -Query q = (price == null) - -The query system will then construct a NullableVector of type `null` (NullableVector). This allows compile -time optimizations for these cases. -*/ - -template -struct NullableVector { - using Underlying = typename util::RemoveOptional::type; - using t_storage = - typename std::conditional::value || std::is_same::value, - int64_t, Underlying>::type; - - NullableVector() - { - } - - NullableVector& operator=(const NullableVector& other) - { - if (this != &other) { - init(other.m_size); - realm::safe_copy_n(other.m_first, other.m_size, m_first); - m_null = other.m_null; - } - return *this; - } - - NullableVector(const NullableVector& other) - { - init(other.m_size); - realm::safe_copy_n(other.m_first, other.m_size, m_first); - m_null = other.m_null; - } - - ~NullableVector() - { - dealloc(); - } - - T operator[](size_t index) const - { - REALM_ASSERT_3(index, <, m_size); - return static_cast(m_first[index]); - } - - inline bool is_null(size_t index) const - { - REALM_ASSERT((std::is_same::value)); - return m_first[index] == m_null; - } - - inline void set_null(size_t index) - { - REALM_ASSERT((std::is_same::value)); - m_first[index] = m_null; - } - - template - typename std::enable_if::value, void>::type set(size_t index, t_storage value) - { - REALM_ASSERT((std::is_same::value)); - - // If value collides with magic null value, then switch to a new unique representation for null - if (REALM_UNLIKELY(value == m_null)) { - // adding a prime will generate 2^64 unique values. Todo: Only works on 2's complement architecture - uint64_t candidate = static_cast(m_null) + 0xfffffffbULL; - while (std::find(m_first, m_first + m_size, static_cast(candidate)) != m_first + m_size) - candidate += 0xfffffffbULL; - std::replace(m_first, m_first + m_size, m_null, static_cast(candidate)); - } - m_first[index] = value; - } - - template - typename std::enable_if::value, - void>::type - set(size_t index, t_storage value) - { - m_first[index] = value; - } - - inline util::Optional get(size_t index) const - { - if (is_null(index)) - return util::none; - - return util::make_optional((*this)[index]); - } - - inline void set(size_t index, util::Optional value) - { - if (value) { - Underlying v = *value; - set(index, v); - } - else { - set_null(index); - } - } - - void fill(T value) - { - for (size_t t = 0; t < m_size; t++) { - if (std::is_same::value) - set_null(t); - else - set(t, value); - } - } - - void init(size_t size) - { - if (size == m_size) - return; - - dealloc(); - m_size = size; - if (m_size > 0) { - if (m_size > prealloc) - m_first = reinterpret_cast(new t_storage[m_size]); - else - m_first = m_cache; - } - } - - void init(size_t size, T values) - { - init(size); - fill(values); - } - - void dealloc() - { - if (m_first) { - if (m_size > prealloc) - delete[] m_first; - m_first = nullptr; - } - } - - t_storage m_cache[prealloc]; - t_storage* m_first = &m_cache[0]; - size_t m_size = 0; - - int64_t m_null = reinterpret_cast(&m_null); // choose magic value to represent nulls -}; - -// Double -// NOTE: fails in gcc 4.8 without `inline`. Do not remove. Same applies for all methods below. -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return null::is_null_float(m_first[index]); -} - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = null::get_null_float(); -} - -// Float -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return null::is_null_float(m_first[index]); -} - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = null::get_null_float(); -} - - -// Null -template <> -inline void NullableVector::set_null(size_t) -{ - return; -} -template <> -inline bool NullableVector::is_null(size_t) const -{ - return true; -} - - -// OldDateTime -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return m_first[index].get_olddatetime() == m_null; -} - - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = m_null; -} - -// StringData - -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return m_first[index].is_null(); -} - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = StringData(); -} - -// BinaryData - -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return m_first[index].is_null(); -} - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = BinaryData(); -} - -// RowIndex -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return m_first[index].is_null(); -} -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = RowIndex(); -} - - -// Timestamp - -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return m_first[index].is_null(); -} - -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index] = Timestamp{}; -} - -// ConstTableRef -template <> -inline bool NullableVector::is_null(size_t index) const -{ - return !bool(m_first[index]); -} -template <> -inline void NullableVector::set_null(size_t index) -{ - m_first[index].reset(); -} - -template -struct OperatorOptionalAdapter { - template - util::Optional operator()(const util::Optional& left, const util::Optional& right) - { - if (!left || !right) - return util::none; - return Operator()(*left, *right); - } - - template - util::Optional operator()(const util::Optional& arg) - { - if (!arg) - return util::none; - return Operator()(*arg); - } -}; - - -struct TrueExpression : Expression { - size_t find_first(size_t start, size_t end) const override - { - REALM_ASSERT(start <= end); - if (start != end) - return start; - - return realm::not_found; - } - void set_base_table(const Table*) override - { - } - const Table* get_base_table() const override - { - return nullptr; - } - void verify_column() const override - { - } - std::string description(util::serializer::SerialisationState&) const override - { - return "TRUEPREDICATE"; - } - std::unique_ptr clone(QueryNodeHandoverPatches*) const override - { - return std::unique_ptr(new TrueExpression(*this)); - } -}; - - -struct FalseExpression : Expression { - size_t find_first(size_t, size_t) const override - { - return realm::not_found; - } - void set_base_table(const Table*) override - { - } - void verify_column() const override - { - } - std::string description(util::serializer::SerialisationState&) const override - { - return "FALSEPREDICATE"; - } - const Table* get_base_table() const override - { - return nullptr; - } - std::unique_ptr clone(QueryNodeHandoverPatches*) const override - { - return std::unique_ptr(new FalseExpression(*this)); - } -}; - - -// Stores N values of type T. Can also exchange data with other ValueBase of different types -template -class Value : public ValueBase, public Subexpr2 { -public: - Value() - { - init(false, 1, T()); - } - Value(T v) - { - init(false, 1, v); - } - - Value(bool from_link_list, size_t values) - { - init(from_link_list, values, T()); - } - - Value(bool from_link_list, size_t values, T v) - { - init(from_link_list, values, v); - } - - Value(const Value&) = default; - Value& operator=(const Value&) = default; - - void init(bool from_link_list, size_t values, T v) - { - m_storage.init(values, v); - ValueBase::m_from_link_list = from_link_list; - ValueBase::m_values = values; - } - - void init(bool from_link_list, size_t values) - { - m_storage.init(values); - ValueBase::m_from_link_list = from_link_list; - ValueBase::m_values = values; - } - - void verify_column() const override - { - } - - std::string description(util::serializer::SerialisationState&) const override - { - if (ValueBase::m_from_link_list) { - return util::serializer::print_value(util::to_string(ValueBase::m_values) - + (ValueBase::m_values == 1 ? " value" : " values")); - } - if (m_storage.m_size > 0) { - return util::serializer::print_value(m_storage[0]); - } - return ""; - } - - bool has_constant_evaluation() const override - { - return true; - } - - void evaluate(size_t, ValueBase& destination) override - { - destination.import(*this); - } - - - template - REALM_FORCEINLINE void fun(const Value* left, const Value* right) - { - OperatorOptionalAdapter o; - - if (!left->m_from_link_list && !right->m_from_link_list) { - // Operate on values one-by-one (one value is one row; no links) - size_t min = std::min(left->m_values, right->m_values); - init(false, min); - - for (size_t i = 0; i < min; i++) { - m_storage.set(i, o(left->m_storage.get(i), right->m_storage.get(i))); - } - } - else if (left->m_from_link_list && right->m_from_link_list) { - // FIXME: Many-to-many links not supported yet. Need to specify behaviour - REALM_ASSERT_DEBUG(false); - } - else if (!left->m_from_link_list && right->m_from_link_list) { - // Right values come from link. Left must come from single row. - REALM_ASSERT_DEBUG(left->m_values > 0); - init(true, right->m_values); - - auto left_value = left->m_storage.get(0); - for (size_t i = 0; i < right->m_values; i++) { - m_storage.set(i, o(left_value, right->m_storage.get(i))); - } - } - else if (left->m_from_link_list && !right->m_from_link_list) { - // Same as above, but with left values coming from links - REALM_ASSERT_DEBUG(right->m_values > 0); - init(true, left->m_values); - - auto right_value = right->m_storage.get(0); - for (size_t i = 0; i < left->m_values; i++) { - m_storage.set(i, o(left->m_storage.get(i), right_value)); - } - } - } - - template - REALM_FORCEINLINE void fun(const Value* value) - { - init(value->m_from_link_list, value->m_values); - - OperatorOptionalAdapter o; - for (size_t i = 0; i < value->m_values; i++) { - m_storage.set(i, o(value->m_storage.get(i))); - } - } - - - // Below import and export methods are for type conversion between float, double, int64_t, etc. - template - typename std::enable_if::value>::type REALM_FORCEINLINE - export2(ValueBase& destination) const - { - Value& d = static_cast&>(destination); - d.init(ValueBase::m_from_link_list, ValueBase::m_values, D()); - for (size_t t = 0; t < ValueBase::m_values; t++) { - if (m_storage.is_null(t)) - d.m_storage.set_null(t); - else { - d.m_storage.set(t, static_cast(m_storage[t])); - } - } - } - - template - typename std::enable_if::value>::type REALM_FORCEINLINE export2(ValueBase&) const - { - // export2 is instantiated for impossible conversions like T=StringData, D=int64_t. These are never - // performed at runtime but would result in a compiler error if we did not provide this implementation. - REALM_ASSERT_DEBUG(false); - } - - REALM_FORCEINLINE void export_Timestamp(ValueBase& destination) const override - { - export2(destination); - } - - REALM_FORCEINLINE void export_bool(ValueBase& destination) const override - { - export2(destination); - } - - REALM_FORCEINLINE void export_int64_t(ValueBase& destination) const override - { - export2(destination); - } - - REALM_FORCEINLINE void export_float(ValueBase& destination) const override - { - export2(destination); - } - - REALM_FORCEINLINE void export_int(ValueBase& destination) const override - { - export2(destination); - } - - REALM_FORCEINLINE void export_double(ValueBase& destination) const override - { - export2(destination); - } - REALM_FORCEINLINE void export_StringData(ValueBase& destination) const override - { - export2(destination); - } - REALM_FORCEINLINE void export_BinaryData(ValueBase& destination) const override - { - export2(destination); - } - REALM_FORCEINLINE void export_RowIndex(ValueBase& destination) const override - { - export2(destination); - } - REALM_FORCEINLINE void export_null(ValueBase& destination) const override - { - Value& d = static_cast&>(destination); - d.init(m_from_link_list, m_values); - } - - REALM_FORCEINLINE void import(const ValueBase& source) override - { - if (std::is_same::value) - source.export_int(*this); - else if (std::is_same::value) - source.export_Timestamp(*this); - else if (std::is_same::value) - source.export_bool(*this); - else if (std::is_same::value) - source.export_float(*this); - else if (std::is_same::value) - source.export_double(*this); - else if (std::is_same::value || std::is_same::value || - std::is_same::value) - source.export_int64_t(*this); - else if (std::is_same::value) - source.export_StringData(*this); - else if (std::is_same::value) - source.export_BinaryData(*this); - else if (std::is_same::value) - source.export_RowIndex(*this); - else if (std::is_same::value) - source.export_null(*this); - else - REALM_ASSERT_DEBUG(false); - } - - // Given a TCond (==, !=, >, <, >=, <=) and two Value, return index of first match - template - REALM_FORCEINLINE static size_t compare_const(const Value* left, Value* right) - { - TCond c; - - size_t sz = right->ValueBase::m_values; - bool left_is_null = left->m_storage.is_null(0); - for (size_t m = 0; m < sz; m++) { - if (c(left->m_storage[0], right->m_storage[m], left_is_null, right->m_storage.is_null(m))) - return right->m_from_link_list ? 0 : m; - } - - return not_found; // no match - } - - template - REALM_FORCEINLINE static size_t compare(Value* left, Value* right) - { - TCond c; - - if (!left->m_from_link_list && !right->m_from_link_list) { - // Compare values one-by-one (one value is one row; no link lists) - size_t min = minimum(left->ValueBase::m_values, right->ValueBase::m_values); - for (size_t m = 0; m < min; m++) { - - if (c(left->m_storage[m], right->m_storage[m], left->m_storage.is_null(m), - right->m_storage.is_null(m))) - return m; - } - } - else if (left->m_from_link_list && right->m_from_link_list) { - // FIXME: Many-to-many links not supported yet. Need to specify behaviour - REALM_ASSERT_DEBUG(false); - } - else if (!left->m_from_link_list && right->m_from_link_list) { - // Right values come from link list. Left must come from single row. Semantics: Match if at least 1 - // linked-to-value fulfills the condition - REALM_ASSERT_DEBUG(left->m_values > 0); - for (size_t r = 0; r < right->m_values; r++) { - if (c(left->m_storage[0], right->m_storage[r], left->m_storage.is_null(0), - right->m_storage.is_null(r))) - return 0; - } - } - else if (left->m_from_link_list && !right->m_from_link_list) { - // Same as above, but with left values coming from link list. - REALM_ASSERT_DEBUG(right->m_values > 0); - for (size_t l = 0; l < left->m_values; l++) { - if (c(left->m_storage[l], right->m_storage[0], left->m_storage.is_null(l), - right->m_storage.is_null(0))) - return 0; - } - } - - return not_found; // no match - } - - std::unique_ptr clone(QueryNodeHandoverPatches*) const override - { - return make_subexpr>(*this); - } - - NullableVector m_storage; -}; - -class ConstantStringValue : public Value { -public: - ConstantStringValue(const StringData& string) - : Value() - , m_string(string.is_null() ? util::none : util::make_optional(std::string(string))) - { - init(false, 1, m_string); - } - - std::unique_ptr clone(QueryNodeHandoverPatches*) const override - { - return std::unique_ptr(new ConstantStringValue(*this)); - } - -private: - ConstantStringValue(const ConstantStringValue& other) - : Value() - , m_string(other.m_string) - { - init(other.m_from_link_list, other.m_values, m_string); - } - - util::Optional m_string; -}; - -// All overloads where left-hand-side is L: -// -// left-hand-side operator right-hand-side -// L +, -, *, /, <, >, ==, !=, <=, >= Subexpr2 -// -// For L = R = {int, int64_t, float, double, Timestamp}: -// Compare numeric values -template -Query operator>(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} - -template -Query operator<(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator==(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator==(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator==(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator==(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator==(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>=(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>=(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>=(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>=(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator>=(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<=(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<=(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<=(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<=(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator<=(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator!=(double left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator!=(float left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator!=(int left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator!=(int64_t left, const Subexpr2& right) -{ - return create(left, right); -} -template -Query operator!=(Timestamp left, const Subexpr2& right) -{ - return create(left, right); -} - -// Arithmetic -template -Operator::type>> operator+(double left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator+(float left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator+(int left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator+(int64_t left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator-(double left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator-(float left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator-(int left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator-(int64_t left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator*(double left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator*(float left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator*(int left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator*(int64_t left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator/(double left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator/(float left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator/(int left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} -template -Operator::type>> operator/(int64_t left, const Subexpr2& right) -{ - return {make_subexpr>(left), right.clone()}; -} - -// Unary operators -template -UnaryOperator> power(const Subexpr2& left) -{ - return {left.clone()}; -} - -// Classes used for LinkMap (see below). -struct LinkMapFunction { - // Your consume() method is given row index of the linked-to table as argument, and you must return whether or - // not you want the LinkMapFunction to exit (return false) or continue (return true) harvesting the link tree - // for the current main table row index (it will be a link tree if you have multiple type_LinkList columns - // in a link()->link() query. - virtual bool consume(size_t row_index) = 0; -}; - -struct FindNullLinks : public LinkMapFunction { - bool consume(size_t row_index) override - { - static_cast(row_index); - m_has_link = true; - return false; // we've found a row index, so this can't be a null-link, so exit link harvesting - } - - bool m_has_link = false; -}; - -struct MakeLinkVector : public LinkMapFunction { - MakeLinkVector(std::vector& result) - : m_links(result) - { - } - - bool consume(size_t row_index) override - { - m_links.push_back(row_index); - return true; // continue evaluation - } - std::vector& m_links; -}; - -struct UnaryLinkResult : public LinkMapFunction { - UnaryLinkResult() - : m_result(realm::not_found) - { - } - bool consume(size_t row_index) override - { - m_result = row_index; - return false; // exit search, only one result ever expected - } - size_t m_result; -}; - -struct CountLinks : public LinkMapFunction { - bool consume(size_t) override - { - m_link_count++; - return true; - } - - size_t result() const - { - return m_link_count; - } - - size_t m_link_count = 0; -}; - -struct CountBacklinks : public LinkMapFunction { - CountBacklinks(const Table* t) - : m_table(t) - { - } - - bool consume(size_t row_index) override - { - m_link_count += m_table->get_backlink_count(row_index); - return true; - } - - size_t result() const - { - return m_link_count; - } - - const Table* m_table; - size_t m_link_count = 0; -}; - - -/* -The LinkMap and LinkMapFunction classes are used for query conditions on links themselves (contrary to conditions on -the value payload they point at). - -MapLink::map_links() takes a row index of the link column as argument and follows any link chain stated in the query -(through the link()->link() methods) until the final payload table is reached, and then applies LinkMapFunction on -the linked-to row index(es). - -If all link columns are type_Link, then LinkMapFunction is only invoked for a single row index. If one or more -columns are type_LinkList, then it may result in multiple row indexes. - -The reason we use this map pattern is that we can exit the link-tree-traversal as early as possible, e.g. when we've -found the first link that points to row '5'. Other solutions could be a std::vector harvest_all_links(), or an -iterator pattern. First solution can't exit, second solution requires internal state. -*/ -class LinkMap { -public: - LinkMap() = default; - LinkMap(const Table* table, std::vector columns) - : m_link_column_indexes(std::move(columns)) - { - set_base_table(table); - } - - LinkMap(LinkMap const& other, QueryNodeHandoverPatches* patches) - : LinkMap(other) - { - if (!patches) - return; - - m_link_column_indexes.clear(); - const Table* table = base_table(); - m_tables.clear(); - for (auto column : m_link_columns) { - m_link_column_indexes.push_back(column->get_column_index()); - if (table->get_real_column_type(m_link_column_indexes.back()) == col_type_BackLink) - table = &static_cast(column)->get_origin_table(); - else - table = &static_cast(column)->get_target_table(); - } - } - - void set_base_table(const Table* table) - { - if (table == base_table()) - return; - - m_tables.clear(); - m_tables.push_back(table); - m_link_columns.clear(); - m_link_types.clear(); - m_only_unary_links = true; - - for (size_t link_column_index : m_link_column_indexes) { - // Link column can be either LinkList or single Link - const Table* t = m_tables.back(); - ColumnType type = t->get_real_column_type(link_column_index); - REALM_ASSERT(Table::is_link_type(type) || type == col_type_BackLink); - m_link_types.push_back(type); - - if (type == col_type_LinkList) { - const LinkListColumn& cll = t->get_column_link_list(link_column_index); - m_link_columns.push_back(&cll); - m_only_unary_links = false; - m_tables.push_back(&cll.get_target_table()); - } - else if (type == col_type_Link) { - const LinkColumn& cl = t->get_column_link(link_column_index); - m_link_columns.push_back(&cl); - m_tables.push_back(&cl.get_target_table()); - } - else if (type == col_type_BackLink) { - const BacklinkColumn& bl = t->get_column_backlink(link_column_index); - m_link_columns.push_back(&bl); - m_only_unary_links = false; - m_tables.push_back(&bl.get_origin_table()); - } - } - } - - void verify_columns() const - { - for (size_t i = 0; i < m_link_column_indexes.size(); i++) { - m_tables[i]->verify_column(m_link_column_indexes[i], m_link_columns[i]); - } - } - - virtual std::string description(util::serializer::SerialisationState& state) const - { - std::string s; - for (size_t i = 0; i < m_link_column_indexes.size(); ++i) { - if (i < m_tables.size() && m_tables[i]) { - s += state.get_column_name(m_tables[i]->get_table_ref(), m_link_column_indexes[i]); - if (i != m_link_column_indexes.size() - 1) { - s += util::serializer::value_separator; - } - } - } - return s; - } - - size_t get_unary_link_or_not_found(size_t index) const - { - REALM_ASSERT(m_only_unary_links); - UnaryLinkResult res; - map_links(index, res); - return res.m_result; - } - - std::vector get_links(size_t index) const - { - std::vector res; - get_links(index, res); - return res; - } - - std::vector get_origin_ndxs(size_t index, size_t column = 0) const; - - size_t count_links(size_t row) - { - CountLinks counter; - map_links(row, counter); - return counter.result(); - } - - size_t count_all_backlinks(size_t row) - { - CountBacklinks counter(target_table()); - map_links(row, counter); - return counter.result(); - } - - void map_links(size_t row, LinkMapFunction& lm) const - { - map_links(0, row, lm); - } - - bool only_unary_links() const - { - return m_only_unary_links; - } - - const Table* base_table() const - { - return m_tables.empty() ? nullptr : m_tables[0]; - } - - const Table* target_table() const - { - REALM_ASSERT(!m_tables.empty()); - return m_tables.back(); - } - - bool links_exist() const - { - return !m_link_columns.empty(); - } - - std::vector m_link_columns; - -private: - void map_links(size_t column, size_t row, LinkMapFunction& lm) const - { - bool last = (column + 1 == m_link_columns.size()); - ColumnType type = m_link_types[column]; - if (type == col_type_Link) { - const LinkColumn& cl = *static_cast(m_link_columns[column]); - size_t r = to_size_t(cl.get(row)); - if (r == 0) - return; - r--; // LinkColumn stores link to row N as N + 1 - if (last) { - bool continue2 = lm.consume(r); - if (!continue2) - return; - } - else - map_links(column + 1, r, lm); - } - else if (type == col_type_LinkList) { - const LinkListColumn& cll = *static_cast(m_link_columns[column]); - ConstLinkViewRef lvr = cll.get(row); - for (size_t t = 0; t < lvr->size(); t++) { - size_t r = lvr->get(t).get_index(); - if (last) { - bool continue2 = lm.consume(r); - if (!continue2) - return; - } - else - map_links(column + 1, r, lm); - } - } - else if (type == col_type_BackLink) { - const BacklinkColumn& bl = *static_cast(m_link_columns[column]); - size_t count = bl.get_backlink_count(row); - for (size_t i = 0; i < count; ++i) { - size_t r = bl.get_backlink(row, i); - if (last) { - bool continue2 = lm.consume(r); - if (!continue2) - return; - } - else - map_links(column + 1, r, lm); - } - } - } - - void get_links(size_t row, std::vector& result) const - { - MakeLinkVector mlv = MakeLinkVector(result); - map_links(row, mlv); - } - - std::vector m_link_column_indexes; - std::vector m_link_types; - std::vector m_tables; - bool m_only_unary_links = true; - - template - friend Query compare(const Subexpr2&, const ConstRow&); -}; - -template -Query string_compare(const Subexpr2& left, T right, bool case_insensitive); -template -Query string_compare(const Subexpr2& left, const Subexpr2& right, bool case_insensitive); - -template -Value make_value_for_link(bool only_unary_links, size_t size) -{ - Value value; - if (only_unary_links) { - REALM_ASSERT(size <= 1); - value.init(false, 1); - value.m_storage.set_null(0); - } - else { - value.init(true, size); - } - return value; -} - - -// If we add a new Realm type T and quickly want Query support for it, then simply inherit from it like -// `template <> class Columns : public SimpleQuerySupport` and you're done. Any operators of the set -// { ==, >=, <=, !=, >, < } that are supported by T will be supported by the "query expression syntax" -// automatically. NOTE: This method of Query support will be slow because it goes through Table::get. -// To get faster Query support, either add SequentialGetter support (faster) or create a query_engine.hpp -// node for it (super fast). - -template -class SimpleQuerySupport : public Subexpr2 { -public: - SimpleQuerySupport(size_t column, const Table* table, std::vector links = {}) - : m_column_ndx(column) - , m_link_map(table, std::move(links)) - { - m_column = &m_link_map.target_table()->get_column_base(m_column_ndx); - } - - bool is_nullable() const noexcept - { - return m_link_map.base_table()->is_nullable(m_column->get_column_index()); - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - if (table != get_base_table()) { - m_link_map.set_base_table(table); - m_column = &m_link_map.target_table()->get_column_base(m_column_ndx); - } - } - - bool has_search_index() const override - { - return m_link_map.target_table()->has_search_index(m_column_ndx); - } - - std::vector find_all(util::Optional value) const override - { - std::vector ret; - ref_type ref = IntegerColumn::create(Allocator::get_default()); - IntegerColumn result; - result.init_from_ref(Allocator::get_default(), ref); - - T val{}; - if (value) { - val = value->get(); - } - - auto col = dynamic_cast::column_type*>(m_column); - col->find_all(result, val, 0, realm::npos); - - auto sz = result.size(); - for (size_t i = 0; i < sz; i++) { - auto ndxs = m_link_map.get_origin_ndxs(size_t(result.get(i))); - ret.insert(ret.end(), ndxs.begin(), ndxs.end()); - } - result.destroy(); - - return ret; - } - - void verify_column() const override - { - // verify links - m_link_map.verify_columns(); - // verify target table - const Table* target_table = m_link_map.target_table(); - if (target_table && m_column_ndx != npos) { - target_table->verify_column(m_column_ndx, m_column); - } - } - - void evaluate(size_t index, ValueBase& destination) override - { - Value& d = static_cast&>(destination); - size_t col = column_ndx(); - - if (links_exist()) { - if (m_link_map.only_unary_links()) { - const Table* target_table = m_link_map.target_table(); - d.init(false, 1); - d.m_storage.set_null(0); - size_t link_translation_index = this->m_link_map.get_unary_link_or_not_found(index); - if (link_translation_index != realm::not_found) { - d.m_storage.set(0, target_table->get(col, link_translation_index)); - } - } - else { - std::vector links = m_link_map.get_links(index); - constexpr bool has_only_unary_links = false; - Value v = make_value_for_link(has_only_unary_links, links.size()); - for (size_t t = 0; t < links.size(); t++) { - size_t link_to = links[t]; - v.m_storage.set(t, m_link_map.target_table()->template get(col, link_to)); - } - destination.import(v); - } - } - else { - // Not a link column - const Table* target_table = m_link_map.target_table(); - for (size_t t = 0; t < destination.m_values && index + t < target_table->size(); t++) { - d.m_storage.set(t, target_table->get(col, index + t)); - } - } - } - - bool links_exist() const - { - return m_link_map.m_link_columns.size() > 0; - } - - bool only_unary_links() const - { - return m_link_map.only_unary_links(); - } - - LinkMap get_link_map() const - { - return m_link_map; - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - return state.describe_columns(m_link_map, m_column_ndx); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches = nullptr) const override - { - return make_subexpr>(static_cast&>(*this), patches); - } - - SimpleQuerySupport(SimpleQuerySupport const& other, QueryNodeHandoverPatches* patches) - : Subexpr2(other) - , m_column_ndx(other.m_column_ndx) - , m_column(other.m_column) - , m_link_map(other.m_link_map, patches) - { - if (patches && m_column) { - m_column_ndx = column_ndx(); - m_column = nullptr; - } - } - - size_t column_ndx() const - { - return m_column->get_column_index(); - } - - SizeOperator> size() - { - return SizeOperator>(this->clone(nullptr)); - } - -private: - // Column index of payload column of m_table - mutable size_t m_column_ndx; - const ColumnBase* m_column; - LinkMap m_link_map; -}; - - -template <> -class Columns : public SimpleQuerySupport { - using SimpleQuerySupport::SimpleQuerySupport; -}; - -template <> -class Columns : public SimpleQuerySupport { - using SimpleQuerySupport::SimpleQuerySupport; -}; - -template <> -class Columns : public SimpleQuerySupport { -public: - Columns(size_t column, const Table* table, std::vector links = {}) - : SimpleQuerySupport(column, table, links) - { - } - - Columns(Columns const& other, QueryNodeHandoverPatches* patches = nullptr) - : SimpleQuerySupport(other, patches) - { - } - - Columns(Columns&& other) - : SimpleQuerySupport(other) - { - } -}; - -template -Query string_compare(const Subexpr2& left, T right, bool case_sensitive) -{ - StringData sd(right); - if (case_sensitive) - return create(sd, left); - else - return create(sd, left); -} - -template -Query string_compare(const Subexpr2& left, const Subexpr2& right, bool case_sensitive) -{ - if (case_sensitive) - return make_expression>(right.clone(), left.clone()); - else - return make_expression>(right.clone(), left.clone()); -} - -template -Query binary_compare(const Subexpr2& left, T right, bool case_sensitive) -{ - BinaryData data(right); - if (case_sensitive) - return create(data, left); - else - return create(data, left); -} - -template -Query binary_compare(const Subexpr2& left, const Subexpr2& right, bool case_sensitive) -{ - if (case_sensitive) - return make_expression>(right.clone(), left.clone()); - else - return make_expression>(right.clone(), left.clone()); -} - - -// Columns == Columns -inline Query operator==(const Columns& left, const Columns& right) -{ - return string_compare(left, right, true); -} - -// Columns != Columns -inline Query operator!=(const Columns& left, const Columns& right) -{ - return string_compare(left, right, true); -} - -// String == Columns -template -Query operator==(T left, const Columns& right) -{ - return operator==(right, left); -} - -// String != Columns -template -Query operator!=(T left, const Columns& right) -{ - return operator!=(right, left); -} - -// Columns == String -template -Query operator==(const Columns& left, T right) -{ - return string_compare(left, right, true); -} - -// Columns != String -template -Query operator!=(const Columns& left, T right) -{ - return string_compare(left, right, true); -} - - -inline Query operator==(const Columns& left, BinaryData right) -{ - return create(right, left); -} - -inline Query operator==(BinaryData left, const Columns& right) -{ - return create(left, right); -} - -inline Query operator!=(const Columns& left, BinaryData right) -{ - return create(right, left); -} - -inline Query operator!=(BinaryData left, const Columns& right) -{ - return create(left, right); -} - - -// This class is intended to perform queries on the *pointers* of links, contrary to performing queries on *payload* -// in linked-to tables. Queries can be "find first link that points at row X" or "find first null-link". Currently -// only "find first null link" and "find first non-null link" is supported. More will be added later. When we add -// more, I propose to remove the template argument from this class and instead template it by -// a criteria-class (like the FindNullLinks class below in find_first()) in some generalized fashion. -template -class UnaryLinkCompare : public Expression { -public: - UnaryLinkCompare(LinkMap lm) - : m_link_map(std::move(lm)) - { - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - } - - // Return main table of query (table on which table->where()... is invoked). Note that this is not the same as - // any linked-to payload tables - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - size_t find_first(size_t start, size_t end) const override - { - for (; start < end;) { - FindNullLinks fnl; - m_link_map.map_links(start, fnl); - if (fnl.m_has_link == has_links) - return start; - - start++; - } - - return not_found; - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - return state.describe_columns(m_link_map, realm::npos) + (has_links ? " != NULL" : " == NULL"); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new UnaryLinkCompare(*this, patches)); - } - -private: - UnaryLinkCompare(const UnaryLinkCompare& other, QueryNodeHandoverPatches* patches = nullptr) - : Expression(other) - , m_link_map(other.m_link_map, patches) - { - } - - mutable LinkMap m_link_map; -}; - -class LinkCount : public Subexpr2 { -public: - LinkCount(LinkMap link_map) - : m_link_map(std::move(link_map)) - { - } - LinkCount(LinkCount const& other, QueryNodeHandoverPatches* patches) - : Subexpr2(other) - , m_link_map(other.m_link_map, patches) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr(*this, patches); - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - size_t count = m_link_map.count_links(index); - destination.import(Value(false, 1, count)); - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - return state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator + "@count"; - } - -private: - LinkMap m_link_map; -}; - -// Gives a count of all backlinks across all columns for the specified row. -// The unused template parameter is a hack to avoid a circular dependency between table.hpp and query_expression.hpp. -template -class BacklinkCount : public Subexpr2 { -public: - BacklinkCount(LinkMap link_map) - : m_link_map(std::move(link_map)) - { - } - BacklinkCount(const Table* table, std::vector links = {}) - : m_link_map(table, std::move(links)) - { - } - BacklinkCount(BacklinkCount const& other, QueryNodeHandoverPatches* patches) - : Subexpr2(other) - , m_link_map(other.m_link_map, patches) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr >(*this, patches); - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - size_t count; - if (m_link_map.links_exist()) { - count = m_link_map.count_all_backlinks(index); - } - else { - count = m_link_map.target_table()->get_backlink_count(index); - } - destination.import(Value(false, 1, count)); - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - std::string s; - if (m_link_map.links_exist()) { - s += state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator; - } - s += "@links.@count"; - return s; - } -private: - LinkMap m_link_map; -}; - - -template -class SizeOperator : public Subexpr2 { -public: - SizeOperator(std::unique_ptr left) - : m_expr(std::move(left)) - { - } - - // See comment in base class - void set_base_table(const Table* table) override - { - m_expr->set_base_table(table); - } - - void verify_column() const override - { - m_expr->verify_column(); - } - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and binds it to a Query at a later time - const Table* get_base_table() const override - { - return m_expr->get_base_table(); - } - - // destination = operator(left) - void evaluate(size_t index, ValueBase& destination) override - { - REALM_ASSERT_DEBUG(dynamic_cast*>(&destination) != nullptr); - Value* d = static_cast*>(&destination); - REALM_ASSERT(d); - - Value v; - m_expr->evaluate(index, v); - - size_t sz = v.m_values; - d->init(v.m_from_link_list, sz); - - for (size_t i = 0; i < sz; i++) { - auto elem = v.m_storage.get(i); - if (!elem) { - d->m_storage.set_null(i); - } - else { - d->m_storage.set(i, oper()(*elem)); - } - } - } - - std::string description(util::serializer::SerialisationState& state) const override - { - if (m_expr) { - return m_expr->description(state) + util::serializer::value_separator + "@size"; - } - return "@size"; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new SizeOperator(*this, patches)); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_expr->apply_handover_patch(patches, group); - } - -private: - SizeOperator(const SizeOperator& other, QueryNodeHandoverPatches* patches) - : m_expr(other.m_expr->clone(patches)) - { - } - - typedef typename oper::type T; - std::unique_ptr m_expr; -}; - -struct ConstantRowValueHandoverPatch : public QueryNodeHandoverPatch { - std::unique_ptr row_patch; -}; - -class ConstantRowValue : public Subexpr2 { -public: - ConstantRowValue(const ConstRow& row) - : m_row(row) - { - } - - void set_base_table(const Table*) override - { - } - - void verify_column() const override - { - } - - const Table* get_base_table() const override - { - return nullptr; - } - - void evaluate(size_t, ValueBase& destination) override - { - if (m_row.is_attached()) { - Value v(RowIndex(m_row.get_index())); - destination.import(v); - } - else { - Value v(RowIndex::Detached); - destination.import(v); - } - } - - virtual std::string description(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialising a query which links to an object is currently unsupported."); - // TODO: we can do something like the following when core gets stable keys: - //if (!m_row.is_attached()) { - // return util::serializer::print_value("detached object"); - //} - //return util::serializer::print_value(m_row.get_index()); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new ConstantRowValue(*this, patches)); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - REALM_ASSERT(patches.size()); - std::unique_ptr abstract_patch = std::move(patches.back()); - patches.pop_back(); - - auto patch = dynamic_cast(abstract_patch.get()); - REALM_ASSERT(patch); - - m_row.apply_and_consume_patch(patch->row_patch, group); - } - -private: - ConstantRowValue(const ConstantRowValue& source, QueryNodeHandoverPatches* patches) - : m_row(patches ? ConstRow() : source.m_row) - { - if (!patches) - return; - - std::unique_ptr patch(new ConstantRowValueHandoverPatch); - ConstRow::generate_patch(source.m_row, patch->row_patch); - patches->emplace_back(patch.release()); - } - - ConstRow m_row; -}; - -template -class SubColumns; - -// This is for LinkList and BackLink too since they're declared as typedefs of Link. -template <> -class Columns : public Subexpr2 { -public: - Query is_null() - { - if (m_link_map.m_link_columns.size() > 1) - throw util::runtime_error("Combining link() and is_null() is currently not supported"); - // Todo, it may be useful to support the above, but we would need to figure out an intuitive behaviour - return make_expression>(m_link_map); - } - - Query is_not_null() - { - if (m_link_map.m_link_columns.size() > 1) - throw util::runtime_error("Combining link() and is_not_null() is currently not supported"); - // Todo, it may be useful to support the above, but we would need to figure out an intuitive behaviour - return make_expression>(m_link_map); - } - - LinkCount count() const - { - return LinkCount(m_link_map); - } - - template - BacklinkCount backlink_count() const - { - return BacklinkCount(m_link_map); - } - - template - SubColumns column(size_t column_ndx) const - { - return SubColumns(Columns(column_ndx, m_link_map.target_table()), m_link_map); - } - - const LinkMap& link_map() const - { - return m_link_map; - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - } - - std::string description(util::serializer::SerialisationState& state) const override - { - return state.describe_columns(m_link_map, realm::npos); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new Columns(*this, patches)); - } - - void evaluate(size_t index, ValueBase& destination) override; - - -private: - LinkMap m_link_map; - friend class Table; - - Columns(size_t column_ndx, const Table* table, const std::vector& links = {}) - : m_link_map(table, links) - { - static_cast(column_ndx); - } - Columns(const Columns& other, QueryNodeHandoverPatches* patches) - : Subexpr2(other) - , m_link_map(other.m_link_map, patches) - { - } -}; - -template -class ListColumns; -template -class ListColumnAggregate; -namespace aggregate_operations { -template -class Minimum; -template -class Maximum; -template -class Sum; -template -class Average; -} - -template <> -class Columns : public Subexpr2 { -public: - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - m_column = &m_link_map.target_table()->get_column_table(m_column_ndx); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - m_link_map.target_table()->verify_column(m_column_ndx, m_column); - } - - std::string description(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialisation of query expressions involving subtables is not yet supported."); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new Columns(*this, patches)); - } - - void evaluate(size_t index, ValueBase& destination) override - { - evaluate_internal(index, destination, ValueBase::chunk_size); - } - - void evaluate_internal(size_t index, ValueBase& destination, size_t nb_elements); - - template - ListColumns column(size_t ndx) const - { - return ListColumns(ndx, Columns(*this, nullptr)); - } - - template - ListColumns list() const - { - return column(0); - } - - SizeOperator> size() - { - return SizeOperator>(this->clone(nullptr)); - } - -private: - LinkMap m_link_map; - size_t m_column_ndx; - const SubtableColumn* m_column = nullptr; - friend class Table; - template - friend class ListColumnsBase; - template - friend class ListColumnAggregate; - - Columns(size_t column_ndx, const Table* table, const std::vector& links = {}) - : m_link_map(table, links) - , m_column_ndx(column_ndx) - , m_column(&m_link_map.target_table()->get_column_table(column_ndx)) - { - } - - Columns(const Columns& other, QueryNodeHandoverPatches* patches) - : Subexpr2(other) - , m_link_map(other.m_link_map, patches) - , m_column_ndx(other.m_column_ndx) - , m_column(other.m_column) - { - if (m_column && patches) - m_column_ndx = m_column->get_column_index(); - } -}; - -template -class ListColumnsBase : public Subexpr2 { -public: - ListColumnsBase(size_t column_ndx, Columns column) - : m_column_ndx(column_ndx) - , m_subtable_column(std::move(column)) - { - } - - ListColumnsBase(const ListColumnsBase& other, QueryNodeHandoverPatches* patches) - : m_column_ndx(other.m_column_ndx) - , m_subtable_column(other.m_subtable_column, patches) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr>(*this, patches); - } - - const Table* get_base_table() const override - { - return m_subtable_column.get_base_table(); - } - - void set_base_table(const Table* table) override - { - m_subtable_column.set_base_table(table); - } - - void verify_column() const override - { - m_subtable_column.verify_column(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - Value subtables; - m_subtable_column.evaluate_internal(index, subtables, 1); - size_t sz = 0; - for (size_t i = 0; i < subtables.m_values; i++) { - auto val = subtables.m_storage[i]; - if (val) - sz += val->size(); - } - auto v = make_value_for_link::type>(false, sz); - size_t k = 0; - for (size_t i = 0; i < subtables.m_values; i++) { - auto table = subtables.m_storage[i]; - if (table) { - size_t s = table->size(); - for (size_t j = 0; j < s; j++) { - if (!table->is_null(m_column_ndx, j)) { - v.m_storage.set(k++, table->get(m_column_ndx, j)); - } - } - } - } - destination.import(v); - } - - virtual std::string description(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialisation of subtable expressions is not yet supported."); - } - - ListColumnAggregate> min() const - { - return {m_column_ndx, m_subtable_column}; - } - - ListColumnAggregate> max() const - { - return {m_column_ndx, m_subtable_column}; - } - - ListColumnAggregate> sum() const - { - return {m_column_ndx, m_subtable_column}; - } - - ListColumnAggregate> average() const - { - return {m_column_ndx, m_subtable_column}; - } - - -private: - // Storing the column index here could be a potential problem if the column - // changes id due to insertion/deletion. - size_t m_column_ndx; - Columns m_subtable_column; -}; - -template -class ListColumns : public ListColumnsBase { -public: - using ListColumnsBase::ListColumnsBase; -}; - -template <> -class ListColumns : public ListColumnsBase { -public: - ListColumns(size_t column_ndx, Columns column) - : ListColumnsBase(column_ndx, column) - { - } - - ListColumns(const ListColumnsBase& other, QueryNodeHandoverPatches* patches) - : ListColumnsBase(other, patches) - { - } - - ListColumns(ListColumns&& other) - : ListColumnsBase(other) - { - } -}; - -template -class ListColumnAggregate : public Subexpr2 { -public: - using R = typename Operation::ResultType; - - ListColumnAggregate(size_t column_ndx, Columns column) - : m_column_ndx(column_ndx) - , m_subtable_column(std::move(column)) - { - } - - ListColumnAggregate(const ListColumnAggregate& other, QueryNodeHandoverPatches* patches) - : m_column_ndx(other.m_column_ndx) - , m_subtable_column(other.m_subtable_column, patches) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr(*this, patches); - } - - const Table* get_base_table() const override - { - return m_subtable_column.get_base_table(); - } - - void set_base_table(const Table* table) override - { - m_subtable_column.set_base_table(table); - } - - void verify_column() const override - { - m_subtable_column.verify_column(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - Value subtables; - m_subtable_column.evaluate_internal(index, subtables, 1); - REALM_ASSERT_DEBUG(subtables.m_values > 0 || subtables.m_from_link_list); - size_t sz = subtables.m_values; - // The result is an aggregate value for each table - auto v = make_value_for_link(!subtables.m_from_link_list, sz); - for (unsigned i = 0; i < sz; i++) { - auto table = subtables.m_storage[i]; - Operation op; - if (table) { - size_t s = table->size(); - for (unsigned j = 0; j < s; j++) { - op.accumulate(table->get(m_column_ndx, j)); - } - } - if (op.is_null()) { - v.m_storage.set_null(i); - } - else { - v.m_storage.set(i, op.result()); - } - } - destination.import(v); - } - - virtual std::string description(util::serializer::SerialisationState&) const override - { - throw SerialisationError("Serialisation of queries involving subtable expressions is not yet supported."); - } - -private: - size_t m_column_ndx; - Columns m_subtable_column; -}; - -template -Query compare(const Subexpr2& left, const ConstRow& row) -{ - static_assert(std::is_same::value || std::is_same::value, - "Links can only be compared for equality."); - const Columns* column = dynamic_cast*>(&left); - if (column) { - const LinkMap& link_map = column->link_map(); - REALM_ASSERT(link_map.target_table() == row.get_table() || !row.is_attached()); -#ifdef REALM_OLDQUERY_FALLBACK - if (link_map.m_link_columns.size() == 1) { - // We can fall back to Query::links_to for != and == operations on links, but only - // for == on link lists. This is because negating query.links_to() is equivalent to - // to "ALL linklist != row" rather than the "ANY linklist != row" semantics we're after. - if (link_map.m_link_types[0] == col_type_Link || - (link_map.m_link_types[0] == col_type_LinkList && std::is_same::value)) { - const Table* t = column->get_base_table(); - Query query(*t); - - if (std::is_same::value) { - // Negate the following `links_to`. - query.Not(); - } - query.links_to(link_map.m_link_column_indexes[0], row); - return query; - } - } -#endif - } - return make_expression>(left.clone(), make_subexpr(row)); -} - -inline Query operator==(const Subexpr2& left, const ConstRow& row) -{ - return compare(left, row); -} -inline Query operator!=(const Subexpr2& left, const ConstRow& row) -{ - return compare(left, row); -} -inline Query operator==(const ConstRow& row, const Subexpr2& right) -{ - return compare(right, row); -} -inline Query operator!=(const ConstRow& row, const Subexpr2& right) -{ - return compare(right, row); -} - -template -Query compare(const Subexpr2& left, null) -{ - static_assert(std::is_same::value || std::is_same::value, - "Links can only be compared for equality."); - return make_expression>(left.clone(), make_subexpr>()); -} - -inline Query operator==(const Subexpr2& left, null) -{ - return compare(left, null()); -} -inline Query operator!=(const Subexpr2& left, null) -{ - return compare(left, null()); -} -inline Query operator==(null, const Subexpr2& right) -{ - return compare(right, null()); -} -inline Query operator!=(null, const Subexpr2& right) -{ - return compare(right, null()); -} - - -template -class Columns : public Subexpr2 { -public: - using ColType = typename ColumnTypeTraits::column_type; - - Columns(size_t column, const Table* table, std::vector links = {}) - : m_link_map(table, std::move(links)) - , m_column_ndx(column) - , m_nullable(m_link_map.target_table()->is_nullable(m_column_ndx)) - { - } - - Columns(const Columns& other, QueryNodeHandoverPatches* patches = nullptr) - : m_link_map(other.m_link_map, patches) - , m_column_ndx(other.m_column_ndx) - , m_nullable(other.m_nullable) - { - if (!other.m_sg) - return; - - if (patches) { - m_column_ndx = other.get_column_base().get_column_index(); - } - else { - if (m_nullable && std::is_same::value) { - init(&other.get_column_base()); - } - else { - init(&other.get_column_base()); - } - } - } - - Columns& operator=(const Columns& other) - { - if (this != &other) { - m_link_map = other.m_link_map; - m_sg.reset(); - m_column_ndx = other.m_column_ndx; - m_nullable = other.m_nullable; - } - return *this; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr>(*this, patches); - } - - // See comment in base class - void set_base_table(const Table* table) override - { - if (m_sg && table == get_base_table()) - return; - - m_link_map.set_base_table(table); - m_nullable = m_link_map.target_table()->is_nullable(m_column_ndx); - - const ColumnBase* c = &m_link_map.target_table()->get_column_base(m_column_ndx); - if (m_nullable && std::is_same::value) { - init(c); - } - else { - init(c); - } - } - - bool has_search_index() const override - { - return m_link_map.target_table()->has_search_index(m_column_ndx); - } - - std::vector find_all(util::Optional value) const override - { - std::vector ret; - ref_type ref = IntegerColumn::create(Allocator::get_default()); - IntegerColumn result; - result.init_from_ref(Allocator::get_default(), ref); - if (m_nullable && std::is_same::value) { - util::Optional val; - if (value) { - val = value->get_int(); - } - auto sgc = static_cast*>(m_sg.get()); - sgc->m_column->find_all(result, val, 0, realm::npos); - } - else { - T val{}; - if (value) { - val = value->get(); - } - auto sgc = static_cast*>(m_sg.get()); - sgc->m_column->find_all(result, val, 0, realm::npos); - } - - auto sz = result.size(); - for (size_t i = 0; i < sz; i++) { - auto ndxs = m_link_map.get_origin_ndxs(size_t(result.get(i))); - ret.insert(ret.end(), ndxs.begin(), ndxs.end()); - } - result.destroy(); - - return ret; - } - - - void verify_column() const override - { - // verify links - m_link_map.verify_columns(); - // verify target table - const Table* target_table = m_link_map.target_table(); - if (target_table && m_column_ndx != npos) { - target_table->verify_column(m_column_ndx, &get_column_base()); - } - } - - template - void init(const ColumnBase* c) - { - REALM_ASSERT_DEBUG(dynamic_cast(c)); - if (m_sg == nullptr) { - m_sg.reset(new SequentialGetter()); - } - static_cast&>(*m_sg).init(static_cast(c)); - } - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and binds it to a Query at a later time - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - template - void evaluate_internal(size_t index, ValueBase& destination) - { - REALM_ASSERT_DEBUG(m_sg.get()); - REALM_ASSERT_DEBUG(dynamic_cast*>(m_sg.get())); - - using U = typename ColType2::value_type; - auto sgc = static_cast*>(m_sg.get()); - REALM_ASSERT_DEBUG(sgc->m_column); - - if (links_exist()) { - // LinkList with more than 0 values. Create Value with payload for all fields - - std::vector links = m_link_map.get_links(index); - auto v = make_value_for_link::type>(m_link_map.only_unary_links(), - links.size()); - - for (size_t t = 0; t < links.size(); t++) { - size_t link_to = links[t]; - sgc->cache_next(link_to); - - if (sgc->m_column->is_null(link_to)) - v.m_storage.set_null(t); - else - v.m_storage.set(t, sgc->get_next(link_to)); - } - destination.import(v); - } - else { - // Not a Link column - // make sequential getter load the respective leaf to access data at column row 'index' - sgc->cache_next(index); - size_t colsize = sgc->m_column->size(); - - // Now load `ValueBase::chunk_size` rows from from the leaf into m_storage. If it's an integer - // leaf, then it contains the method get_chunk() which copies these values in a super fast way (first - // case of the `if` below. Otherwise, copy the values one by one in a for-loop (the `else` case). - if (std::is_same::value && index + ValueBase::chunk_size <= sgc->m_leaf_end) { - Value v(false, ValueBase::chunk_size); - - // If you want to modify 'default_size' then update Array::get_chunk() - REALM_ASSERT_3(ValueBase::chunk_size, ==, 8); - - auto sgc_2 = static_cast*>(m_sg.get()); - sgc_2->m_leaf_ptr->get_chunk(index - sgc->m_leaf_start, v.m_storage.m_first); - - destination.import(v); - } - else { - size_t rows = colsize - index; - if (rows > ValueBase::chunk_size) - rows = ValueBase::chunk_size; - Value::type> v(false, rows); - - for (size_t t = 0; t < rows; t++) - v.m_storage.set(t, sgc->get_next(index + t)); - - destination.import(v); - } - } - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - return state.describe_columns(m_link_map, m_column_ndx); - } - - // Load values from Column into destination - void evaluate(size_t index, ValueBase& destination) override - { - if (m_nullable && std::is_same::value) { - evaluate_internal(index, destination); - } - else { - evaluate_internal(index, destination); - } - } - - bool links_exist() const - { - return m_link_map.m_link_columns.size() > 0; - } - - bool only_unary_links() const - { - return m_link_map.only_unary_links(); - } - - bool is_nullable() const - { - return m_nullable; - } - - LinkMap get_link_map() const - { - return m_link_map; - } - - size_t column_ndx() const noexcept - { - return m_sg ? get_column_base().get_column_index() : m_column_ndx; - } - -private: - LinkMap m_link_map; - - // Fast (leaf caching) value getter for payload column (column in table on which query condition is executed) - std::unique_ptr m_sg; - - // Column index of payload column of m_table - size_t m_column_ndx; - - // set to false by default for stand-alone Columns declaration that are not yet associated with any table - // or oclumn. Call init() to update it or use a constructor that takes table + column index as argument. - bool m_nullable = false; - - const ColumnBase& get_column_base() const noexcept - { - if (m_nullable && std::is_same::value) - return *static_cast&>(*m_sg).m_column; - else - return *static_cast&>(*m_sg).m_column; - } -}; - -template -class SubColumnAggregate; - -template -class SubColumns : public Subexpr { -public: - SubColumns(Columns column, LinkMap link_map) - : m_column(std::move(column)) - , m_link_map(std::move(link_map)) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches*) const override - { - return make_subexpr>(*this); - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - m_column.set_base_table(m_link_map.target_table()); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - m_column.verify_column(); - } - - void evaluate(size_t, ValueBase&) override - { - // SubColumns can only be used in an expression in conjunction with its aggregate methods. - REALM_ASSERT(false); - } - - virtual std::string description(util::serializer::SerialisationState&) const override - { - return ""; // by itself there are no conditions, see SubColumnAggregate - } - - SubColumnAggregate> min() const - { - return {m_column, m_link_map}; - } - - SubColumnAggregate> max() const - { - return {m_column, m_link_map}; - } - - SubColumnAggregate> sum() const - { - return {m_column, m_link_map}; - } - - SubColumnAggregate> average() const - { - return {m_column, m_link_map}; - } - -private: - Columns m_column; - LinkMap m_link_map; -}; - -template -class SubColumnAggregate : public Subexpr2 { -public: - SubColumnAggregate(Columns column, LinkMap link_map) - : m_column(std::move(column)) - , m_link_map(std::move(link_map)) - { - } - SubColumnAggregate(SubColumnAggregate const& other, QueryNodeHandoverPatches* patches) - : m_column(other.m_column, patches) - , m_link_map(other.m_link_map, patches) - { - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr(*this, patches); - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - m_column.set_base_table(m_link_map.target_table()); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - m_column.verify_column(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - std::vector links = m_link_map.get_links(index); - std::sort(links.begin(), links.end()); - - Operation op; - for (size_t link_index = 0; link_index < links.size();) { - Value value; - size_t link = links[link_index]; - m_column.evaluate(link, value); - - // Columns::evaluate fetches values in chunks of ValueBase::default_size. Process all values - // within the chunk that came from rows that we link to. - const auto& value_storage = value.m_storage; - for (size_t value_index = 0; value_index < value.m_values;) { - if (!value_storage.is_null(value_index)) { - op.accumulate(value_storage[value_index]); - } - if (++link_index >= links.size()) { - break; - } - - size_t previous_link = link; - link = links[link_index]; - value_index += link - previous_link; - } - } - if (op.is_null()) { - destination.import(Value(false, 1, null())); - } - else { - destination.import(Value(false, 1, op.result())); - } - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - util::serializer::SerialisationState empty_state; - return state.describe_columns(m_link_map, realm::npos) + util::serializer::value_separator + Operation::description() + util::serializer::value_separator + m_column.description(empty_state); - } - -private: - Columns m_column; - LinkMap m_link_map; -}; - -struct SubQueryCountHandoverPatch : QueryNodeHandoverPatch { - QueryHandoverPatch m_query; -}; - -class SubQueryCount : public Subexpr2 { -public: - SubQueryCount(Query q, LinkMap link_map) - : m_query(std::move(q)) - , m_link_map(std::move(link_map)) - { - } - - const Table* get_base_table() const override - { - return m_link_map.base_table(); - } - - void set_base_table(const Table* table) override - { - m_link_map.set_base_table(table); - } - - void verify_column() const override - { - m_link_map.verify_columns(); - } - - void evaluate(size_t index, ValueBase& destination) override - { - std::vector links = m_link_map.get_links(index); - std::sort(links.begin(), links.end()); - - size_t count = std::accumulate(links.begin(), links.end(), size_t(0), [this](size_t running_count, size_t link) { - return running_count + m_query.count(link, link + 1, 1); - }); - - destination.import(Value(false, 1, size_t(count))); - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - REALM_ASSERT(m_link_map.base_table() != nullptr); - std::string target = state.describe_columns(m_link_map, realm::npos); - std::string var_name = state.get_variable_name(m_link_map.base_table()->get_table_ref()); - state.subquery_prefix_list.push_back(var_name); - std::string desc = "SUBQUERY(" + target + ", " + var_name + ", " + m_query.get_description(state) + ")" - + util::serializer::value_separator + "@count"; - state.subquery_prefix_list.pop_back(); - return desc; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - if (patches) - return std::unique_ptr(new SubQueryCount(*this, patches)); - - return make_subexpr(*this); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - REALM_ASSERT(patches.size()); - std::unique_ptr abstract_patch = std::move(patches.back()); - patches.pop_back(); - - auto patch = dynamic_cast(abstract_patch.get()); - REALM_ASSERT(patch); - - m_query.apply_patch(patch->m_query, group); - } - -private: - SubQueryCount(const SubQueryCount& other, QueryNodeHandoverPatches* patches) - : m_link_map(other.m_link_map, patches) - { - std::unique_ptr patch(new SubQueryCountHandoverPatch); - m_query = Query(other.m_query, patch->m_query, ConstSourcePayload::Copy); - patches->emplace_back(patch.release()); - } - - Query m_query; - LinkMap m_link_map; -}; - -// The unused template parameter is a hack to avoid a circular dependency between table.hpp and query_expression.hpp. -template -class SubQuery { -public: - SubQuery(Columns link_column, Query query) - : m_query(std::move(query)) - , m_link_map(link_column.link_map()) - { - REALM_ASSERT(m_link_map.target_table() == m_query.get_table()); - } - - SubQueryCount count() const - { - return SubQueryCount(m_query, m_link_map); - } - -private: - Query m_query; - LinkMap m_link_map; -}; - -namespace aggregate_operations { -template -class BaseAggregateOperation { - static_assert(std::is_same::value || std::is_same::value || std::is_same::value, - "Numeric aggregates can only be used with subcolumns of numeric types"); - -public: - using ResultType = R; - - void accumulate(T value) - { - m_count++; - m_result = Derived::apply(m_result, value); - } - - bool is_null() const - { - return m_count == 0; - } - ResultType result() const - { - return m_result; - } - -protected: - size_t m_count = 0; - ResultType m_result = Derived::initial_value(); -}; - -template -class Minimum : public BaseAggregateOperation> { -public: - static T initial_value() - { - return std::numeric_limits::max(); - } - static T apply(T a, T b) - { - return std::min(a, b); - } - static std::string description() - { - return "@min"; - } -}; - -template -class Maximum : public BaseAggregateOperation> { -public: - static T initial_value() - { - return std::numeric_limits::min(); - } - static T apply(T a, T b) - { - return std::max(a, b); - } - static std::string description() - { - return "@max"; - } -}; - -template -class Sum : public BaseAggregateOperation> { -public: - static T initial_value() - { - return T(); - } - static T apply(T a, T b) - { - return a + b; - } - bool is_null() const - { - return false; - } - static std::string description() - { - return "@sum"; - } -}; - -template -class Average : public BaseAggregateOperation, double> { - using Base = BaseAggregateOperation, double>; - -public: - static double initial_value() - { - return 0; - } - static double apply(double a, T b) - { - return a + b; - } - double result() const - { - return Base::m_result / Base::m_count; - } - static std::string description() - { - return "@avg"; - } - -}; -} - -template -class UnaryOperator : public Subexpr2 { -public: - UnaryOperator(std::unique_ptr left) - : m_left(std::move(left)) - { - } - - UnaryOperator(const UnaryOperator& other, QueryNodeHandoverPatches* patches) - : m_left(other.m_left->clone(patches)) - { - } - - UnaryOperator& operator=(const UnaryOperator& other) - { - if (this != &other) { - m_left = other.m_left->clone(); - } - return *this; - } - - UnaryOperator(UnaryOperator&&) = default; - UnaryOperator& operator=(UnaryOperator&&) = default; - - // See comment in base class - void set_base_table(const Table* table) override - { - m_left->set_base_table(table); - } - - void verify_column() const override - { - m_left->verify_column(); - } - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and binds it to a Query at a later time - const Table* get_base_table() const override - { - return m_left->get_base_table(); - } - - // destination = operator(left) - void evaluate(size_t index, ValueBase& destination) override - { - Value result; - Value left; - m_left->evaluate(index, left); - result.template fun(&left); - destination.import(result); - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - if (m_left) { - return m_left->description(state); - } - return ""; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr(*this, patches); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_left->apply_handover_patch(patches, group); - } - -private: - typedef typename oper::type T; - std::unique_ptr m_left; -}; - - -template -class Operator : public Subexpr2 { -public: - Operator(std::unique_ptr left, std::unique_ptr right) - : m_left(std::move(left)) - , m_right(std::move(right)) - { - } - - Operator(const Operator& other, QueryNodeHandoverPatches* patches) - : m_left(other.m_left->clone(patches)) - , m_right(other.m_right->clone(patches)) - { - } - - Operator& operator=(const Operator& other) - { - if (this != &other) { - m_left = other.m_left->clone(); - m_right = other.m_right->clone(); - } - return *this; - } - - Operator(Operator&&) = default; - Operator& operator=(Operator&&) = default; - - // See comment in base class - void set_base_table(const Table* table) override - { - m_left->set_base_table(table); - m_right->set_base_table(table); - } - - void verify_column() const override - { - m_left->verify_column(); - m_right->verify_column(); - } - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and - // binds it to a Query at a later time - const Table* get_base_table() const override - { - const Table* l = m_left->get_base_table(); - const Table* r = m_right->get_base_table(); - - // Queries do not support multiple different tables; all tables must be the same. - REALM_ASSERT(l == nullptr || r == nullptr || l == r); - - // nullptr pointer means expression which isn't yet associated with any table, or is a Value - return l ? l : r; - } - - // destination = operator(left, right) - void evaluate(size_t index, ValueBase& destination) override - { - Value result; - Value left; - Value right; - m_left->evaluate(index, left); - m_right->evaluate(index, right); - result.template fun(&left, &right); - destination.import(result); - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - std::string s; - if (m_left) { - s += m_left->description(state); - } - s += (" " + oper::description() + " "); - if (m_right) { - s += m_right->description(state); - } - return s; - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return make_subexpr(*this, patches); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_right->apply_handover_patch(patches, group); - m_left->apply_handover_patch(patches, group); - } - -private: - typedef typename oper::type T; - std::unique_ptr m_left; - std::unique_ptr m_right; -}; - -namespace { -template -inline Mixed get_mixed(const Value& val) -{ - return Mixed(val.m_storage[0]); -} - -template <> -inline Mixed get_mixed(const Value&) -{ - REALM_ASSERT(false); - return Mixed(); -} - -template <> -inline Mixed get_mixed(const Value& val) -{ - return Mixed(int64_t(val.m_storage[0])); -} -} // namespace - -template -class Compare : public Expression { -public: - Compare(std::unique_ptr left, std::unique_ptr right) - : m_left(std::move(left)) - , m_right(std::move(right)) - { - m_left_is_const = m_left->has_constant_evaluation(); - if (m_left_is_const) { - m_left->evaluate(-1/*unused*/, m_left_value); - } - } - - // See comment in base class - void set_base_table(const Table* table) override - { - m_left->set_base_table(table); - m_right->set_base_table(table); - } - - double init() override - { - double dT = m_left_is_const ? 10.0 : 50.0; - if (std::is_same::value && m_left_is_const && m_right->has_search_index()) { - if (m_left_value.m_storage.is_null(0)) { - m_matches = m_right->find_all(util::Optional()); - } - else { - m_matches = m_right->find_all(get_mixed(m_left_value)); - } - // Sort - std::sort(m_matches.begin(), m_matches.end()); - // Remove all duplicates - m_matches.erase(std::unique(m_matches.begin(), m_matches.end()), m_matches.end()); - - m_has_matches = true; - m_index_get = 0; - m_index_end = m_matches.size(); - dT = 0; - } - - return dT; - } - - void verify_column() const override - { - m_left->verify_column(); - m_right->verify_column(); - } - - // Recursively fetch tables of columns in expression tree. Used when user first builds a stand-alone expression - // and binds it to a Query at a later time - const Table* get_base_table() const override - { - const Table* l = m_left->get_base_table(); - const Table* r = m_right->get_base_table(); - - // All main tables in each subexpression of a query (table.columns() or table.link()) must be the same. - REALM_ASSERT(l == nullptr || r == nullptr || l == r); - - // nullptr pointer means expression which isn't yet associated with any table, or is a Value - return l ? l : r; - } - - size_t find_first(size_t start, size_t end) const override - { - if (m_has_matches) { - if (m_index_end == 0) - return not_found; - - if (start <= m_index_last_start) - m_index_get = 0; - else - m_index_last_start = start; - - while (m_index_get < m_index_end) { - size_t ndx = m_matches[m_index_get]; - if (ndx >= end) { - break; - } - m_index_get++; - if (ndx >= start) { - return ndx; - } - } - return not_found; - } - - size_t match; - - Value left; - Value right; - - for (; start < end;) { - if (m_left_is_const) { - m_right->evaluate(start, right); - match = Value::template compare_const(&m_left_value, &right); - } - else { - m_left->evaluate(start, left); - m_right->evaluate(start, right); - match = Value::template compare(&left, &right); - } - - if (match != not_found && match + start < end) - return start + match; - - size_t rows = - (left.m_from_link_list || right.m_from_link_list) ? 1 : minimum(right.m_values, left.m_values); - start += rows; - } - - return not_found; // no match - } - - virtual std::string description(util::serializer::SerialisationState& state) const override - { - if (std::is_same::value - || std::is_same::value - || std::is_same::value - || std::is_same::value - || std::is_same::value - || std::is_same::value - || std::is_same::value - || std::is_same::value) { - // these string conditions have the arguments reversed but the order is important - // operations ==, and != can be reversed because the produce the same results both ways - return util::serializer::print_value(m_right->description(state) + " " + TCond::description() - + " " + m_left->description(state)); - } - return util::serializer::print_value(m_left->description(state) + " " + TCond::description() - + " " + m_right->description(state)); - } - - std::unique_ptr clone(QueryNodeHandoverPatches* patches) const override - { - return std::unique_ptr(new Compare(*this, patches)); - } - - void apply_handover_patch(QueryNodeHandoverPatches& patches, Group& group) override - { - m_right->apply_handover_patch(patches, group); - m_left->apply_handover_patch(patches, group); - } - -private: - Compare(const Compare& other, QueryNodeHandoverPatches* patches) - : m_left(other.m_left->clone(patches)) - , m_right(other.m_right->clone(patches)) - , m_left_is_const(other.m_left_is_const) - { - if (m_left_is_const) { - m_left->evaluate(-1/*unused*/, m_left_value); - } - } - - std::unique_ptr m_left; - std::unique_ptr m_right; - bool m_left_is_const; - Value m_left_value; - bool m_has_matches = false; - std::vector m_matches; - mutable size_t m_index_get = 0; - mutable size_t m_index_last_start = 0; - size_t m_index_end = 0; -}; - -} -#endif // REALM_QUERY_EXPRESSION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/query_operators.hpp b/Lesson14/Pods/Realm/include/core/realm/query_operators.hpp deleted file mode 100644 index 203af84..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/query_operators.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_QUERY_OPERATORS_HPP -#define REALM_QUERY_OPERATORS_HPP - -#include -#include -#include -#include - -namespace realm { - -// This is not supported in the general case -template -struct Size; - -template <> -struct Size { - int64_t operator()(StringData v) const - { - return v.size(); - } - typedef StringData type; -}; - -template <> -struct Size { - int64_t operator()(BinaryData v) const - { - return v.size(); - } - typedef BinaryData type; -}; - -template <> -struct Size { - int64_t operator()(ConstTableRef v) const - { - return v->size(); - } - typedef ConstTableRef type; -}; - -template <> -struct Size { - int64_t operator()(ConstLinkViewRef v) const - { - return v->size(); - } - typedef ConstLinkViewRef type; -}; - -} // namespace realm - -#endif // REALM_QUERY_OPERATORS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/realm_nmmintrin.h b/Lesson14/Pods/Realm/include/core/realm/realm_nmmintrin.h deleted file mode 100644 index 8144da6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/realm_nmmintrin.h +++ /dev/null @@ -1,182 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_NMMINTRIN_H -#define REALM_NMMINTRIN_H - -/* - We must support runtime detection of CPU support of SSE when distributing Realm as a closed source library. - - This is a problem on gcc and llvm: To use SSE intrinsics we need to pass -msse on the command line (to get offered - __builtin_ accessors used by intrinsics functions). However, the -msse flag allows gcc to emit SSE instructions - in its code generation/optimization. This is unwanted because the binary would crash on non-SSE CPUs. - - Since there exists no flag in gcc that enables intrinsics but probits SSE in code generation, we define our - own intrinsics to be assembled by the back end assembler and omit passing -msse to gcc. -*/ - -#ifndef _MSC_VER - -#ifdef REALM_COMPILER_SSE -#include // SSE2 (using __m128i) -#endif - -namespace realm { - -#if 0 -#ifdef REALM_COMPILER_AVX -typedef float __m256 __attribute__((__vector_size__(32), __may_alias__)); -typedef double __m256d __attribute__((__vector_size__(32), __may_alias__)); - -const int _CMP_EQ_OQ = 0x00; // Equal (ordered, non-signaling) -const int _CMP_NEQ_OQ = 0x0c; // Not-equal (ordered, non-signaling) -const int _CMP_LT_OQ = 0x11; // Less-than (ordered, non-signaling) -const int _CMP_LE_OQ = 0x12; // Less-than-or-equal (ordered, non-signaling) -const int _CMP_GE_OQ = 0x1d; // Greater-than-or-equal (ordered, non-signaling) -const int _CMP_GT_OQ = 0x1e; // Greater-than (ordered, non-signaling) - - -template -static int movemask_cmp_ps(__m256* y1, __m256* y2) -{ - int ret; - __asm__("vmovaps %0, %%ymm0" : : "m"(*y1) : "%xmm0" ); - __asm__("vmovaps %0, %%ymm1" : : "m"(*y2) : "%xmm1" ); - __asm__("vcmpps %0, %%ymm0, %%ymm1, %%ymm0" : : "I"(op) : "%xmm0" ); - __asm__("vmovmskps %%ymm0, %0" : "=r"(ret) : : ); - return ret; -} - -template -static inline int movemask_cmp_pd(__m256d* y1, __m256d* y2) -{ - int ret; - __asm__("vmovapd %0, %%ymm0" : : "m"(*y1) : "%xmm0" ); - __asm__("vmovapd %0, %%ymm1" : : "m"(*y2) : "%xmm1" ); - __asm__("vcmppd %0, %%ymm0, %%ymm1, %%ymm0" : : "I"(op) : "%xmm0" ); - __asm__("vmovmskpd %%ymm0, %0" : "=r"(ret) : : ); - return ret; -} - - - -static inline int movemask_cmp_ps(__m256* y1, __m256* y2, int op) -{ - // todo, use constexpr; - if (op == _CMP_EQ_OQ) - return movemask_cmp_ps<_CMP_NEQ_OQ>(y1, y2); - else if (op == _CMP_NEQ_OQ) - return movemask_cmp_ps<_CMP_NEQ_OQ>(y1, y2); - else if (op == _CMP_LT_OQ) - return movemask_cmp_ps<_CMP_LT_OQ>(y1, y2); - else if (op == _CMP_LE_OQ) - return movemask_cmp_ps<_CMP_LE_OQ>(y1, y2); - else if (op == _CMP_GE_OQ) - return movemask_cmp_ps<_CMP_GE_OQ>(y1, y2); - else if (op == _CMP_GT_OQ) - return movemask_cmp_ps<_CMP_GT_OQ>(y1, y2); - - REALM_ASSERT(false); - return 0; -} - -static inline int movemask_cmp_pd(__m256d* y1, __m256d* y2, int op) -{ - // todo, use constexpr; - if (op == _CMP_EQ_OQ) - return movemask_cmp_pd<_CMP_NEQ_OQ>(y1, y2); - else if (op == _CMP_NEQ_OQ) - return movemask_cmp_pd<_CMP_NEQ_OQ>(y1, y2); - else if (op == _CMP_LT_OQ) - return movemask_cmp_pd<_CMP_LT_OQ>(y1, y2); - else if (op == _CMP_LE_OQ) - return movemask_cmp_pd<_CMP_LE_OQ>(y1, y2); - else if (op == _CMP_GE_OQ) - return movemask_cmp_pd<_CMP_GE_OQ>(y1, y2); - else if (op == _CMP_GT_OQ) - return movemask_cmp_pd<_CMP_GT_OQ>(y1, y2); - - REALM_ASSERT(false); - return 0; -} - - -#endif -#endif - -// Instructions introduced by SSE 3 and 4.2 -static inline __m128i _mm_cmpgt_epi64(__m128i xmm1, __m128i xmm2) -{ - __asm__("pcmpgtq %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i _mm_cmpeq_epi64(__m128i xmm1, __m128i xmm2) -{ - __asm__("pcmpeqq %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_min_epi8(__m128i xmm1, __m128i xmm2) -{ - __asm__("pminsb %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_max_epi8(__m128i xmm1, __m128i xmm2) -{ - __asm__("pmaxsb %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_max_epi32(__m128i xmm1, __m128i xmm2) -{ - __asm__("pmaxsd %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_min_epi32(__m128i xmm1, __m128i xmm2) -{ - __asm__("pminsd %1, %0" : "+x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_cvtepi8_epi16(__m128i xmm2) -{ - __m128i xmm1; - __asm__("pmovsxbw %1, %0" : "=x" (xmm1) : "xm" (xmm2) : "xmm1"); - return xmm1; -} -static inline __m128i __attribute__((always_inline)) _mm_cvtepi16_epi32(__m128i xmm2) -{ - __m128i xmm1; - asm("pmovsxwd %1, %0" : "=x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -static inline __m128i __attribute__((always_inline)) _mm_cvtepi32_epi64(__m128i xmm2) -{ - __m128i xmm1; - __asm__("pmovsxdq %1, %0" : "=x" (xmm1) : "xm" (xmm2)); - return xmm1; -} - -} // namespace realm - -#endif -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/replication.hpp b/Lesson14/Pods/Realm/include/core/realm/replication.hpp deleted file mode 100644 index 92a5782..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/replication.hpp +++ /dev/null @@ -1,512 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_REPLICATION_HPP -#define REALM_REPLICATION_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace realm { -namespace util { -class Logger; -} - -// FIXME: Be careful about the possibility of one modification function being called by another where both do -// transaction logging. - -// FIXME: The current table/subtable selection scheme assumes that a TableRef of a subtable is not accessed after any -// modification of one of its ancestor tables. - -// FIXME: Checking on same Table* requires that ~Table checks and nullifies on match. Another option would be to store -// m_selected_table as a TableRef. Yet another option would be to assign unique identifiers to each Table instance via -// Allocator. Yet another option would be to explicitely invalidate subtables recursively when parent is modified. - -/// Replication is enabled by passing an instance of an implementation of this -/// class to the SharedGroup constructor. -class Replication : public _impl::TransactLogConvenientEncoder, protected _impl::TransactLogStream { -public: - // Be sure to keep this type aligned with what is actually used in - // SharedGroup. - using version_type = _impl::History::version_type; - using InputStream = _impl::NoCopyInputStream; - class TransactLogApplier; - class Interrupted; // Exception - class SimpleIndexTranslator; - - enum class TransactionType { trans_Read, trans_Write }; - - /// CAUTION: These values are stored in Realm files, so value reassignment - /// is not allowed. - enum HistoryType { - /// No history available. No support for either continuous transactions - /// or inter-client synchronization. - hist_None = 0, - - /// Out-of-Realm history supporting continuous transactions. - /// - /// NOTE: This history type is no longer in use. The value needs to stay - /// reserved in case someone tries to open an old Realm file. - hist_OutOfRealm = 1, - - /// In-Realm history supporting continuous transactions - /// (make_in_realm_history()). - hist_InRealm = 2, - - /// In-Realm history supporting continuous transactions and client-side - /// synchronization protocol (realm::sync::ClientHistory). - hist_SyncClient = 3, - - /// In-Realm history supporting continuous transactions and server-side - /// synchronization protocol (realm::_impl::ServerHistory). - hist_SyncServer = 4 - }; - - virtual std::string get_database_path() const = 0; - - /// Called during construction of the associated SharedGroup object. - /// - /// \param shared_group The assocoated SharedGroup object. - virtual void initialize(SharedGroup& shared_group) = 0; - - /// Called by the associated SharedGroup object when a session is - /// initiated. A *session* is a sequence of of temporally overlapping - /// accesses to a specific Realm file, where each access consists of a - /// SharedGroup object through which the Realm file is open. Session - /// initiation occurs during the first opening of the Realm file within such - /// a session. - /// - /// Session initiation fails if this function throws. - /// - /// \param version The current version of the associated Realm. Out-of-Realm - /// history implementation can use this to trim off history entries that - /// were successfully added to the history, but for which the corresponding - /// subsequent commits on the Realm file failed. - /// - /// The default implementation does nothing. - virtual void initiate_session(version_type version) = 0; - - /// Called by the associated SharedGroup object when a session is - /// terminated. See initiate_session() for the definition of a - /// session. Session termination occurs upon closing the Realm through the - /// last SharedGroup object within the session. - /// - /// The default implementation does nothing. - virtual void terminate_session() noexcept = 0; - - /// \defgroup replication_transactions - //@{ - - /// From the point of view of the Replication class, a transaction is - /// initiated when, and only when the associated SharedGroup object calls - /// initiate_transact() and the call is successful. The associated - /// SharedGroup object must terminate every initiated transaction either by - /// calling finalize_commit() or by calling abort_transact(). It may only - /// call finalize_commit(), however, after calling prepare_commit(), and - /// only when prepare_commit() succeeds. If prepare_commit() fails (i.e., - /// throws) abort_transact() must still be called. - /// - /// The associated SharedGroup object is supposed to terminate a transaction - /// as soon as possible, and is required to terminate it before attempting - /// to initiate a new one. - /// - /// initiate_transact() is called by the associated SharedGroup object as - /// part of the initiation of a transaction, and at a time where the caller - /// has acquired exclusive write access to the local Realm. The Replication - /// implementation is allowed to perform "precursor transactions" on the - /// local Realm at this time. During the initiated transaction, the - /// associated SharedGroup object must inform the Replication object of all - /// modifying operations by calling set_value() and friends. - /// - /// FIXME: There is currently no way for implementations to perform - /// precursor transactions, since a regular transaction would cause a dead - /// lock when it tries to acquire a write lock. Consider giving access to - /// special non-locking precursor transactions via an extra argument to this - /// function. - /// - /// prepare_commit() serves as the first phase of a two-phase commit. This - /// function is called by the associated SharedGroup object immediately - /// before the commit operation on the local Realm. The associated - /// SharedGroup object will then, as the second phase, either call - /// finalize_commit() or abort_transact() depending on whether the commit - /// operation succeeded or not. The Replication implementation is allowed to - /// modify the Realm via the associated SharedGroup object at this time - /// (important to in-Realm histories). - /// - /// initiate_transact() and prepare_commit() are allowed to block the - /// calling thread if, for example, they need to communicate over the - /// network. If a calling thread is blocked in one of these functions, it - /// must be possible to interrupt the blocking operation by having another - /// thread call interrupt(). The contract is as follows: When interrupt() is - /// called, then any execution of initiate_transact() or prepare_commit(), - /// initiated before the interruption, must complete without blocking, or - /// the execution must be aborted by throwing an Interrupted exception. If - /// initiate_transact() or prepare_commit() throws Interrupted, it counts as - /// a failed operation. - /// - /// finalize_commit() is called by the associated SharedGroup object - /// immediately after a successful commit operation on the local Realm. This - /// happens at a time where modification of the Realm is no longer possible - /// via the associated SharedGroup object. In the case of in-Realm - /// histories, the changes are automatically finalized as part of the commit - /// operation performed by the caller prior to the invocation of - /// finalize_commit(), so in that case, finalize_commit() might not need to - /// do anything. - /// - /// abort_transact() is called by the associated SharedGroup object to - /// terminate a transaction without committing. That is, any transaction - /// that is not terminated by finalize_commit() is terminated by - /// abort_transact(). This could be due to an explicit rollback, or due to a - /// failed commit attempt. - /// - /// Note that finalize_commit() and abort_transact() are not allowed to - /// throw. - /// - /// \param current_version The version of the snapshot that the current - /// transaction is based on. - /// - /// \param history_updated Pass true only when the history has already been - /// updated to reflect the currently bound snapshot, such as when - /// _impl::History::update_early_from_top_ref() was called during the - /// transition from a read transaction to the current write transaction. - /// - /// \return prepare_commit() returns the version of the new snapshot - /// produced by the transaction. - /// - /// \throw Interrupted Thrown by initiate_transact() and prepare_commit() if - /// a blocking operation was interrupted. - - void initiate_transact(TransactionType transaction_type, version_type current_version, bool history_updated); - version_type prepare_commit(version_type current_version); - void finalize_commit() noexcept; - void abort_transact() noexcept; - - //@} - - - /// Interrupt any blocking call to a function in this class. This function - /// may be called asyncronously from any thread, but it may not be called - /// from a system signal handler. - /// - /// Some of the public function members of this class may block, but only - /// when it it is explicitely stated in the documention for those functions. - /// - /// FIXME: Currently we do not state blocking behaviour for all the - /// functions that can block. - /// - /// After any function has returned with an interruption indication, the - /// only functions that may safely be called are abort_transact() and the - /// destructor. If a client, after having received an interruption - /// indication, calls abort_transact() and then clear_interrupt(), it may - /// resume normal operation through this Replication object. - void interrupt() noexcept; - - /// May be called by a client to reset this Replication object after an - /// interrupted transaction. It is not an error to call this function in a - /// situation where no interruption has occured. - void clear_interrupt() noexcept; - - /// Apply a changeset to the specified group. - /// - /// \param changeset The changes to be applied. - /// - /// \param group The destination group to apply the changeset to. - /// - /// \param logger If specified, and the library was compiled in debug mode, - /// then a line describing each individual operation is writted to the - /// specified logger. - /// - /// \throw BadTransactLog If the changeset could not be successfully parsed, - /// or ended prematurely. - static void apply_changeset(InputStream& changeset, Group& group, util::Logger* logger = nullptr); - - /// Returns the type of history maintained by this Replication - /// implementation, or \ref hist_None if no history is maintained by it. - /// - /// This type is used to ensure that all session participants agree on - /// history type, and that the Realm file contains a compatible type of - /// history, at the beginning of a new session. - /// - /// As a special case, if there is no top array (Group::m_top) at the - /// beginning of a new session, then the history type is still undecided and - /// all history types (as returned by get_history_type()) are threfore - /// allowed for the session initiator. Note that this case only arises if - /// there was no preceding session, or if no transaction was sucessfully - /// committed during any of the preceding sessions. As soon as a transaction - /// is successfully committed, the Realm contains at least a top array, and - /// from that point on, the history type is generally fixed, although still - /// subject to certain allowed changes (as mentioned below). - /// - /// For the sake of backwards compatibility with older Realm files that does - /// not store any history type, the following rule shall apply: - /// - /// - If the top array of a Realm file (Group::m_top) does not contain a - /// history type, because it is too short, it shall be understood as - /// implicitly storing the type \ref hist_None. - /// - /// Note: In what follows, the meaning of *preceding session* is: The last - /// preceding session that modified the Realm by sucessfully committing a - /// new snapshot. - /// - /// It shall be allowed to switch to a \ref hist_InRealm history if the - /// stored history type is \ref hist_None. This can be done simply by adding - /// a new history to the Realm file. This is possible because histories of - /// this type a transient in nature, and need not survive from one session - /// to the next. - /// - /// On the other hand, as soon as a history of type \ref hist_InRealm is - /// added to a Realm file, that history type is binding for all subsequent - /// sessions. In theory, this constraint is not necessary, and a later - /// switch to \ref hist_None would be possible because of the transient - /// nature of it, however, because the \ref hist_InRealm history remains in - /// the Realm file, there are practical complications, and for that reason, - /// such switching shall not be supported. - /// - /// The \ref hist_SyncClient history type can only be used if the stored - /// history type is also \ref hist_SyncClient, or when there is no top array - /// yet. Likewise, the \ref hist_SyncServer history type can only be used if - /// the stored history type is also \ref hist_SyncServer, or when there is - /// no top array yet. Additionally, when the stored history type is \ref - /// hist_SyncClient or \ref hist_SyncServer, then all subsequent sessions - /// must have the same type. These restrictions apply because such a history - /// needs to be maintained persistently across sessions. - /// - /// In general, if there is no stored history type (no top array) at the - /// beginning of a new session, or if the stored type disagrees with what is - /// returned by get_history_type() (which is possible due to particular - /// allowed changes of history type), the actual history type (as returned - /// by get_history_type()) used during that session, must be stored in the - /// Realm during the first successfully committed transaction in that - /// session. But note that there is still no need to expand the top array to - /// store the history type \ref hist_None, due to the rule mentioned above. - /// - /// This function must return \ref hist_None when, and only when - /// get_history() returns null. - virtual HistoryType get_history_type() const noexcept = 0; - - /// Returns the schema version of the history maintained by this Replication - /// implementation, or 0 if no history is maintained by it. All session - /// participants must agree on history schema version. - /// - /// Must return 0 if get_history_type() returns \ref hist_None. - virtual int get_history_schema_version() const noexcept = 0; - - /// Implementation may assume that this function is only ever called with a - /// stored schema version that is less than what was returned by - /// get_history_schema_version(). - virtual bool is_upgradable_history_schema(int stored_schema_version) const noexcept = 0; - - /// The implementation may assume that this function is only ever called if - /// is_upgradable_history_schema() was called with the same stored schema - /// version, and returned true. This implies that the specified stored - /// schema version is always strictly less than what was returned by - /// get_history_schema_version(). - virtual void upgrade_history_schema(int stored_schema_version) = 0; - - /// Returns an object that gives access to the history of changesets in a - /// way that allows for continuous transactions to work - /// (Group::advance_transact() in particular). - /// - /// This function must return null when, and only when get_history_type() - /// returns \ref hist_None. - virtual _impl::History* get_history() = 0; - - /// Returns false by default, but must return true if, and only if this - /// history object represents a session participant that is a sync - /// agent. This is used to enforce the "maximum one sync agent per session" - /// constraint. - virtual bool is_sync_agent() const noexcept; - - virtual ~Replication() noexcept - { - } - -protected: - Replication(); - - - //@{ - - /// do_initiate_transact() is called by initiate_transact(), and likewise - /// for do_prepare_commit), do_finalize_commit(), and do_abort_transact(). - /// - /// With respect to exception safety, the Replication implementation has two - /// options: It can prepare to accept the accumulated changeset in - /// do_prepapre_commit() by allocating all required resources, and delay the - /// actual acceptance to do_finalize_commit(), which requires that the final - /// acceptance can be done without any risk of failure. Alternatively, the - /// Replication implementation can fully accept the changeset in - /// do_prepapre_commit() (allowing for failure), and then discard that - /// changeset during the next invocation of do_initiate_transact() if - /// `current_version` indicates that the previous transaction failed. - - virtual void do_initiate_transact(TransactionType, version_type current_version) = 0; - virtual version_type do_prepare_commit(version_type orig_version) = 0; - virtual void do_finalize_commit() noexcept = 0; - virtual void do_abort_transact() noexcept = 0; - - //@} - - - virtual void do_interrupt() noexcept = 0; - - virtual void do_clear_interrupt() noexcept = 0; - - friend class _impl::TransactReverser; -}; - - -class Replication::Interrupted : public std::exception { -public: - const char* what() const noexcept override - { - return "Interrupted"; - } -}; - - -class TrivialReplication : public Replication { -public: - ~TrivialReplication() noexcept - { - } - - std::string get_database_path() const override; -protected: - typedef Replication::version_type version_type; - - TrivialReplication(const std::string& database_file); - - virtual version_type prepare_changeset(const char* data, size_t size, version_type orig_version) = 0; - virtual void finalize_changeset() noexcept = 0; - - static void apply_changeset(const char* data, size_t size, SharedGroup& target, util::Logger* logger = nullptr); - - BinaryData get_uncommitted_changes() const noexcept; - - void initialize(SharedGroup&) override; - void do_initiate_transact(TransactionType, version_type) override; - version_type do_prepare_commit(version_type orig_version) override; - void do_finalize_commit() noexcept override; - void do_abort_transact() noexcept override; - void do_interrupt() noexcept override; - void do_clear_interrupt() noexcept override; - void transact_log_reserve(size_t n, char** new_begin, char** new_end) override; - void transact_log_append(const char* data, size_t size, char** new_begin, char** new_end) override; - -private: - const std::string m_database_file; - util::Buffer m_transact_log_buffer; - void internal_transact_log_reserve(size_t, char** new_begin, char** new_end); - - size_t transact_log_size(); -}; - - -// Implementation: - -inline Replication::Replication() - : _impl::TransactLogConvenientEncoder(static_cast<_impl::TransactLogStream&>(*this)) -{ -} - -inline void Replication::initiate_transact(TransactionType transaction_type, version_type current_version, - bool history_updated) -{ - if (auto hist = get_history()) { - hist->set_updated(history_updated); - } - do_initiate_transact(transaction_type, current_version); - reset_selection_caches(); -} - -inline Replication::version_type Replication::prepare_commit(version_type orig_version) -{ - return do_prepare_commit(orig_version); -} - -inline void Replication::finalize_commit() noexcept -{ - do_finalize_commit(); -} - -inline void Replication::abort_transact() noexcept -{ - do_abort_transact(); -} - -inline void Replication::interrupt() noexcept -{ - do_interrupt(); -} - -inline void Replication::clear_interrupt() noexcept -{ - do_clear_interrupt(); -} - -inline bool Replication::is_sync_agent() const noexcept -{ - return false; -} - -inline TrivialReplication::TrivialReplication(const std::string& database_file) - : m_database_file(database_file) -{ -} - -inline BinaryData TrivialReplication::get_uncommitted_changes() const noexcept -{ - const char* data = m_transact_log_buffer.data(); - size_t size = write_position() - data; - return BinaryData(data, size); -} - -inline size_t TrivialReplication::transact_log_size() -{ - return write_position() - m_transact_log_buffer.data(); -} - -inline void TrivialReplication::transact_log_reserve(size_t n, char** new_begin, char** new_end) -{ - internal_transact_log_reserve(n, new_begin, new_end); -} - -inline void TrivialReplication::internal_transact_log_reserve(size_t n, char** new_begin, char** new_end) -{ - char* data = m_transact_log_buffer.data(); - size_t size = write_position() - data; - m_transact_log_buffer.reserve_extra(size, n); - data = m_transact_log_buffer.data(); // May have changed - *new_begin = data + size; - *new_end = data + m_transact_log_buffer.size(); -} - -} // namespace realm - -#endif // REALM_REPLICATION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/row.hpp b/Lesson14/Pods/Realm/include/core/realm/row.hpp deleted file mode 100644 index 66b7c58..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/row.hpp +++ /dev/null @@ -1,862 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_ROW_HPP -#define REALM_ROW_HPP - -#include - -#include -#include -#include -#include -#include - -namespace realm { - -template -class BasicRow; - - -/// This class is a "mixin" and contains the common set of functions for several -/// distinct row-like classes. -/// -/// There is a direct and natural correspondance between the functions in this -/// class and functions in Table of the same name. For example: -/// -/// table[i].get_int(j) == table.get_int(i,j) -/// -/// The effect of calling most of the row accessor functions on a detached -/// accessor is unspecified and may lead to general corruption, and/or a -/// crash. The exceptions are is_attached(), detach(), get_table(), get_index(), -/// and the destructor. Note however, that get_index() will still return an -/// unspecified value for a deatched accessor. -/// -/// When a row accessor is evaluated in a boolean context, it evaluates to true -/// if, and only if it is attached. -/// -/// \tparam T A const or non-const table type (currently either `Table` or -/// `const Table`). -/// -/// \tparam R A specific row accessor class (BasicRow or BasicRowExpr) providing -/// members `T* impl_get_table() const`, `size_t impl_get_row_ndx() -/// const`, and `void impl_detach()`. Neither are allowed to throw. -/// -/// \sa Table -/// \sa BasicRow -template -class RowFuncs { -public: - typedef T table_type; - - typedef BasicTableRef ConstTableRef; - typedef BasicTableRef TableRef; // Same as ConstTableRef if `T` is 'const' - - typedef typename util::CopyConst::type L; - using ConstLinkViewRef = std::shared_ptr; - using LinkViewRef = std::shared_ptr; // Same as ConstLinkViewRef if `T` is 'const' - - int_fast64_t get_int(size_t col_ndx) const noexcept; - bool get_bool(size_t col_ndx) const noexcept; - float get_float(size_t col_ndx) const noexcept; - double get_double(size_t col_ndx) const noexcept; - StringData get_string(size_t col_ndx) const noexcept; - BinaryData get_binary(size_t col_ndx) const noexcept; - OldDateTime get_olddatetime(size_t col_ndx) const noexcept; - Timestamp get_timestamp(size_t col_ndx) const noexcept; - ConstTableRef get_subtable(size_t col_ndx) const; - TableRef get_subtable(size_t col_ndx); - size_t get_subtable_size(size_t col_ndx) const noexcept; - size_t get_link(size_t col_ndx) const noexcept; - bool is_null_link(size_t col_ndx) const noexcept; - bool is_null(size_t col_ndx) const noexcept; - ConstLinkViewRef get_linklist(size_t col_ndx) const; - LinkViewRef get_linklist(size_t col_ndx); - bool linklist_is_empty(size_t col_ndx) const noexcept; - size_t get_link_count(size_t col_ndx) const noexcept; - Mixed get_mixed(size_t col_ndx) const noexcept; - DataType get_mixed_type(size_t col_ndx) const noexcept; - - template - U get(size_t col_ndx) const noexcept; - - void set_int(size_t col_ndx, int_fast64_t value); - void set_int_unique(size_t col_ndx, int_fast64_t value); - void add_int(size_t col_ndx, int_fast64_t value); - void set_bool(size_t col_ndx, bool value); - void set_float(size_t col_ndx, float value); - void set_double(size_t col_ndx, double value); - void set_string(size_t col_ndx, StringData value); - void set_string_unique(size_t col_ndx, StringData value); - void set_binary(size_t col_ndx, BinaryData value); - void set_olddatetime(size_t col_ndx, OldDateTime value); - void set_timestamp(size_t col_ndx, Timestamp value); - void set_subtable(size_t col_ndx, const Table* value); - void set_link(size_t col_ndx, size_t value); - void nullify_link(size_t col_ndx); - void set_mixed(size_t col_ndx, Mixed value); - void set_mixed_subtable(size_t col_ndx, const Table* value); - void set_null(size_t col_ndx); - void set_null_unique(size_t col_ndx); - - template - void set(size_t col_ndx, U&& value, bool is_default = false); - - template - void set_unique(size_t col_ndx, U&& value); - - void insert_substring(size_t col_ndx, size_t pos, StringData); - void remove_substring(size_t col_ndx, size_t pos, size_t size); - - //@{ - /// Note that these operations will cause the row accessor to be detached. - void remove(); - void move_last_over(); - //@} - - size_t get_backlink_count() const noexcept; - size_t get_backlink_count(const Table& src_table, size_t src_col_ndx) const noexcept; - size_t get_backlink(const Table& src_table, size_t src_col_ndx, size_t backlink_ndx) const noexcept; - - size_t get_column_count() const noexcept; - DataType get_column_type(size_t col_ndx) const noexcept; - StringData get_column_name(size_t col_ndx) const noexcept; - size_t get_column_index(StringData name) const noexcept; - - /// Returns true if, and only if this accessor is currently attached to a - /// row. - /// - /// A row accesor may get detached from the underlying row for various - /// reasons (see below). When it does, it no longer refers to anything, and - /// can no longer be used, except for calling is_attached(), detach(), - /// get_table(), get_index(), and the destructor. The consequences of - /// calling other methods on a detached row accessor are unspecified. There - /// are a few Realm functions (Table::find_pkey_int()) that return a - /// detached row accessor to indicate a 'null' result. In all other cases, - /// however, row accessors obtained by calling functions in the Realm API - /// are always in the 'attached' state immediately upon return from those - /// functions. - /// - /// A row accessor becomes detached if the underlying row is removed, if the - /// associated table accessor becomes detached, or if the detach() method is - /// called. A row accessor does not become detached for any other reason. - bool is_attached() const noexcept; - - /// Detach this accessor from the row it was attached to. This function has - /// no effect if the accessor was already detached (idempotency). - void detach() noexcept; - - /// The table containing the row to which this accessor is currently - /// bound. For a detached accessor, the returned value is null. - const table_type* get_table() const noexcept; - table_type* get_table() noexcept; - - /// The index of the row to which this accessor is currently bound. For a - /// detached accessor, the returned value is unspecified. - size_t get_index() const noexcept; - - explicit operator bool() const noexcept; - -private: - const T* table() const noexcept; - T* table() noexcept; - size_t row_ndx() const noexcept; -}; - - -/// This class is a special kind of row accessor. It differes from a real row -/// accessor (BasicRow) by having a trivial and fast copy constructor and -/// descructor. It is supposed to be used as the return type of functions such -/// as Table::operator[](), and then to be used as a basis for constructing a -/// real row accessor. Objects of this class are intended to only ever exist as -/// temporaries. -/// -/// In contrast to a real row accessor (`BasicRow`), objects of this class do -/// not keep the parent table "alive", nor are they maintained (adjusted) across -/// row insertions and row removals like real row accessors are. -/// -/// \sa BasicRow -template -class BasicRowExpr : public RowFuncs> { -public: - BasicRowExpr() noexcept = default; - - template - BasicRowExpr(const BasicRowExpr&) noexcept; - - template - BasicRowExpr(const BasicRow&) noexcept; - -private: - T* m_table = nullptr; // nullptr if detached. - size_t m_row_ndx = 0; // Undefined if detached. - - BasicRowExpr(T*, size_t init_row_ndx) noexcept; - - T* impl_get_table() const noexcept; - size_t impl_get_row_ndx() const noexcept; - void impl_detach() noexcept; - - // Make impl_get_table(), impl_get_row_ndx(), and impl_detach() accessible - // from RowFuncs. - friend class RowFuncs>; - - // Make m_table and m_row_ndx accessible from BasicRowExpr(const - // BasicRowExpr&) for any U. - template - friend class BasicRowExpr; - - // Make m_table and m_row_ndx accessible from - // BasicRow::BaicRow(BasicRowExpr) for any U. - template - friend class BasicRow; - - // Make BasicRowExpr(T*, size_t) accessible from Table. - friend class Table; -}; - -// fwd decl -class Group; - -class RowBase { -protected: - TableRef m_table; // nullptr if detached. - size_t m_row_ndx = -1; // Undefined if detached. - - void attach(Table*, size_t row_ndx) noexcept; - void reattach(Table*, size_t row_ndx) noexcept; - void impl_detach() noexcept; - - RowBase() - { - } - - RowBase(const RowBase&) = delete; - using HandoverPatch = RowBaseHandoverPatch; - - RowBase(const RowBase& source, HandoverPatch& patch); - -public: - static void generate_patch(const RowBase& source, HandoverPatch& patch); - void apply_patch(HandoverPatch& patch, Group& group); - -private: - RowBase* m_prev = nullptr; // nullptr if first, undefined if detached. - RowBase* m_next = nullptr; // nullptr if last, undefined if detached. - - // Table needs to be able to modify m_table and m_row_ndx. - friend class Table; -}; - - -/// An accessor class for table rows (a.k.a. a "row accessor"). -/// -/// For as long as it remains attached, a row accessor will keep the parent -/// table accessor alive. In case the lifetime of the parent table is not -/// managed by reference counting (such as when the table is an automatic -/// variable on the stack), the destruction of the table will cause all -/// remaining row accessors to be detached. -/// -/// While attached, a row accessor is bound to a particular row of the parent -/// table. If that row is removed, the accesssor becomes detached. If rows are -/// inserted or removed before it (at lower row index), then the accessor is -/// automatically adjusted to account for the change in index of the row to -/// which the accessor is bound. In other words, a row accessor is bound to the -/// contents of a row, not to a row index. See also is_attached(). -/// -/// Row accessors are created and used as follows: -/// -/// Row row = table[7]; // 8th row of `table` -/// ConstRow crow = ctable[2]; // 3rd row of const `ctable` -/// Row first_row = table.front(); -/// Row last_row = table.back(); -/// -/// float v = row.get_float(1); // Get the float in the 2nd column -/// row.set_string(0, "foo"); // Update the string in the 1st column -/// -/// Table* t = row.get_table(); // The parent table -/// size_t i = row.get_index(); // The current row index -/// -/// \sa RowFuncs -template -class BasicRow : private RowBase, public RowFuncs> { -public: - BasicRow() noexcept; - - template - BasicRow(BasicRowExpr) noexcept; - - BasicRow(const BasicRow&) noexcept; - - template - BasicRow(const BasicRow&) noexcept; - - template - BasicRow& operator=(BasicRowExpr) noexcept; - - template - BasicRow& operator=(BasicRow) noexcept; - - BasicRow& operator=(const BasicRow&) noexcept; - - ~BasicRow() noexcept; - -private: - T* impl_get_table() const noexcept; - size_t impl_get_row_ndx() const noexcept; - - // Make impl_get_table(), impl_get_row_ndx(), and impl_detach() accessible - // from RowFuncs. - friend class RowFuncs>; - - // Make m_table and m_row_ndx accessible from BasicRow(const BasicRow&) - // for any U. - template - friend class BasicRow; - - // Make m_table and m_row_ndx accessible from BasicRowExpr(const - // BasicRow&) for any U. - template - friend class BasicRowExpr; - -public: - std::unique_ptr> clone_for_handover(std::unique_ptr& patch) const - { - patch.reset(new HandoverPatch); - std::unique_ptr> retval(new BasicRow(*this, *patch)); - return retval; - } - - static void generate_patch(const BasicRow& row, std::unique_ptr& patch) - { - patch.reset(new HandoverPatch); - RowBase::generate_patch(row, *patch); - } - - void apply_and_consume_patch(std::unique_ptr& patch, Group& group) - { - apply_patch(*patch, group); - patch.reset(); - } - - void apply_patch(HandoverPatch& patch, Group& group) - { - RowBase::apply_patch(patch, group); - } - -private: - BasicRow(const BasicRow& source, HandoverPatch& patch) - : RowBase(source, patch) - { - } - friend class SharedGroup; -}; - -typedef BasicRow
Row; -typedef BasicRow ConstRow; - - -// Implementation - -template -inline int_fast64_t RowFuncs::get_int(size_t col_ndx) const noexcept -{ - return table()->get_int(col_ndx, row_ndx()); -} - -template -inline bool RowFuncs::get_bool(size_t col_ndx) const noexcept -{ - return table()->get_bool(col_ndx, row_ndx()); -} - -template -inline float RowFuncs::get_float(size_t col_ndx) const noexcept -{ - return table()->get_float(col_ndx, row_ndx()); -} - -template -inline double RowFuncs::get_double(size_t col_ndx) const noexcept -{ - return table()->get_double(col_ndx, row_ndx()); -} - -template -inline StringData RowFuncs::get_string(size_t col_ndx) const noexcept -{ - return table()->get_string(col_ndx, row_ndx()); -} - -template -inline BinaryData RowFuncs::get_binary(size_t col_ndx) const noexcept -{ - return table()->get_binary(col_ndx, row_ndx()); -} - -template -inline OldDateTime RowFuncs::get_olddatetime(size_t col_ndx) const noexcept -{ - return table()->get_olddatetime(col_ndx, row_ndx()); -} - -template -inline Timestamp RowFuncs::get_timestamp(size_t col_ndx) const noexcept -{ - return table()->get_timestamp(col_ndx, row_ndx()); -} - -template -inline typename RowFuncs::ConstTableRef RowFuncs::get_subtable(size_t col_ndx) const -{ - return table()->get_subtable(col_ndx, row_ndx()); // Throws -} - -template -inline typename RowFuncs::TableRef RowFuncs::get_subtable(size_t col_ndx) -{ - return table()->get_subtable(col_ndx, row_ndx()); // Throws -} - -template -inline size_t RowFuncs::get_subtable_size(size_t col_ndx) const noexcept -{ - return table()->get_subtable_size(col_ndx, row_ndx()); -} - -template -inline size_t RowFuncs::get_link(size_t col_ndx) const noexcept -{ - return table()->get_link(col_ndx, row_ndx()); -} - -template -inline bool RowFuncs::is_null_link(size_t col_ndx) const noexcept -{ - return table()->is_null_link(col_ndx, row_ndx()); -} - -template -inline bool RowFuncs::is_null(size_t col_ndx) const noexcept -{ - return table()->is_null(col_ndx, row_ndx()); -} - -template -inline typename RowFuncs::ConstLinkViewRef RowFuncs::get_linklist(size_t col_ndx) const -{ - return table()->get_linklist(col_ndx, row_ndx()); // Throws -} - -template -inline typename RowFuncs::LinkViewRef RowFuncs::get_linklist(size_t col_ndx) -{ - return table()->get_linklist(col_ndx, row_ndx()); // Throws -} - -template -inline bool RowFuncs::linklist_is_empty(size_t col_ndx) const noexcept -{ - return table()->linklist_is_empty(col_ndx, row_ndx()); -} - -template -inline size_t RowFuncs::get_link_count(size_t col_ndx) const noexcept -{ - return table()->get_link_count(col_ndx, row_ndx()); -} - -template -inline Mixed RowFuncs::get_mixed(size_t col_ndx) const noexcept -{ - return table()->get_mixed(col_ndx, row_ndx()); -} - -template -inline DataType RowFuncs::get_mixed_type(size_t col_ndx) const noexcept -{ - return table()->get_mixed_type(col_ndx, row_ndx()); -} - -template -template -inline U RowFuncs::get(size_t col_ndx) const noexcept -{ - return table()->template get(col_ndx, row_ndx()); -} - -template -inline void RowFuncs::set_int(size_t col_ndx, int_fast64_t value) -{ - table()->set_int(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_int_unique(size_t col_ndx, int_fast64_t value) -{ - table()->set_int_unique(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::add_int(size_t col_ndx, int_fast64_t value) -{ - table()->add_int(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_bool(size_t col_ndx, bool value) -{ - table()->set_bool(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_float(size_t col_ndx, float value) -{ - table()->set_float(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_double(size_t col_ndx, double value) -{ - table()->set_double(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_string(size_t col_ndx, StringData value) -{ - table()->set_string(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_string_unique(size_t col_ndx, StringData value) -{ - table()->set_string_unique(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_binary(size_t col_ndx, BinaryData value) -{ - table()->set_binary(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_olddatetime(size_t col_ndx, OldDateTime value) -{ - table()->set_olddatetime(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_timestamp(size_t col_ndx, Timestamp value) -{ - table()->set_timestamp(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_subtable(size_t col_ndx, const Table* value) -{ - table()->set_subtable(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_link(size_t col_ndx, size_t value) -{ - table()->set_link(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::nullify_link(size_t col_ndx) -{ - table()->nullify_link(col_ndx, row_ndx()); // Throws -} - -template -inline void RowFuncs::set_mixed(size_t col_ndx, Mixed value) -{ - table()->set_mixed(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_mixed_subtable(size_t col_ndx, const Table* value) -{ - table()->set_mixed_subtable(col_ndx, row_ndx(), value); // Throws -} - -template -inline void RowFuncs::set_null(size_t col_ndx) -{ - table()->set_null(col_ndx, row_ndx()); // Throws -} - -template -inline void RowFuncs::set_null_unique(size_t col_ndx) -{ - table()->set_null_unique(col_ndx, row_ndx()); // Throws -} - -template -template -inline void RowFuncs::set(size_t col_ndx, U&& value, bool is_default) -{ - table()->set(col_ndx, row_ndx(), std::forward(value), is_default); // Throws -} - -template -template -inline void RowFuncs::set_unique(size_t col_ndx, U&& value) -{ - table()->set_unique(col_ndx, row_ndx(), std::forward(value)); // Throws -} - -template -inline void RowFuncs::insert_substring(size_t col_ndx, size_t pos, StringData value) -{ - table()->insert_substring(col_ndx, row_ndx(), pos, value); // Throws -} - -template -inline void RowFuncs::remove_substring(size_t col_ndx, size_t pos, size_t size) -{ - table()->remove_substring(col_ndx, row_ndx(), pos, size); // Throws -} - -template -inline void RowFuncs::remove() -{ - table()->remove(row_ndx()); // Throws -} - -template -inline void RowFuncs::move_last_over() -{ - table()->move_last_over(row_ndx()); // Throws -} - -template -inline size_t RowFuncs::get_backlink_count() const noexcept -{ - return table()->get_backlink_count(row_ndx()); -} - -template -inline size_t RowFuncs::get_backlink_count(const Table& src_table, size_t src_col_ndx) const noexcept -{ - return table()->get_backlink_count(row_ndx(), src_table, src_col_ndx); -} - -template -inline size_t RowFuncs::get_backlink(const Table& src_table, size_t src_col_ndx, size_t backlink_ndx) const - noexcept -{ - return table()->get_backlink(row_ndx(), src_table, src_col_ndx, backlink_ndx); -} - -template -inline size_t RowFuncs::get_column_count() const noexcept -{ - return table()->get_column_count(); -} - -template -inline DataType RowFuncs::get_column_type(size_t col_ndx) const noexcept -{ - return table()->get_column_type(col_ndx); -} - -template -inline StringData RowFuncs::get_column_name(size_t col_ndx) const noexcept -{ - return table()->get_column_name(col_ndx); -} - -template -inline size_t RowFuncs::get_column_index(StringData name) const noexcept -{ - return table()->get_column_index(name); -} - -template -inline bool RowFuncs::is_attached() const noexcept -{ - return static_cast(this)->impl_get_table(); -} - -template -inline void RowFuncs::detach() noexcept -{ - static_cast(this)->impl_detach(); -} - -template -inline const T* RowFuncs::get_table() const noexcept -{ - return table(); -} - -template -inline T* RowFuncs::get_table() noexcept -{ - return table(); -} - -template -inline size_t RowFuncs::get_index() const noexcept -{ - return row_ndx(); -} - -template -inline RowFuncs::operator bool() const noexcept -{ - return is_attached(); -} - -template -inline const T* RowFuncs::table() const noexcept -{ - return static_cast(this)->impl_get_table(); -} - -template -inline T* RowFuncs::table() noexcept -{ - return static_cast(this)->impl_get_table(); -} - -template -inline size_t RowFuncs::row_ndx() const noexcept -{ - return static_cast(this)->impl_get_row_ndx(); -} - - -template -template -inline BasicRowExpr::BasicRowExpr(const BasicRowExpr& expr) noexcept - : m_table(expr.m_table) - , m_row_ndx(expr.m_row_ndx) -{ -} - -template -template -inline BasicRowExpr::BasicRowExpr(const BasicRow& row) noexcept - : m_table(row.m_table.get()) - , m_row_ndx(row.m_row_ndx) -{ -} - -template -inline BasicRowExpr::BasicRowExpr(T* init_table, size_t init_row_ndx) noexcept - : m_table(init_table) - , m_row_ndx(init_row_ndx) -{ -} - -template -inline T* BasicRowExpr::impl_get_table() const noexcept -{ - return m_table; -} - -template -inline size_t BasicRowExpr::impl_get_row_ndx() const noexcept -{ - return m_row_ndx; -} - -template -inline void BasicRowExpr::impl_detach() noexcept -{ - m_table = nullptr; -} - - -template -inline BasicRow::BasicRow() noexcept -{ -} - -template -inline BasicRow::BasicRow(const BasicRow& row) noexcept - : RowBase() -{ - attach(const_cast(row.m_table.get()), row.m_row_ndx); -} - -template -template -inline BasicRow::BasicRow(BasicRowExpr expr) noexcept -{ - T* expr_table = expr.m_table; // Check that pointer types are compatible - attach(const_cast(expr_table), expr.m_row_ndx); -} - -template -template -inline BasicRow::BasicRow(const BasicRow& row) noexcept -{ - T* row_table = row.m_table.get(); // Check that pointer types are compatible - attach(const_cast(row_table), row.m_row_ndx); -} - -template -template -inline BasicRow& BasicRow::operator=(BasicRowExpr expr) noexcept -{ - T* expr_table = expr.m_table; // Check that pointer types are compatible - reattach(const_cast(expr_table), expr.m_row_ndx); - return *this; -} - -template -template -inline BasicRow& BasicRow::operator=(BasicRow row) noexcept -{ - T* row_table = row.m_table.get(); // Check that pointer types are compatible - reattach(const_cast(row_table), row.m_row_ndx); - return *this; -} - -template -inline BasicRow& BasicRow::operator=(const BasicRow& row) noexcept -{ - reattach(const_cast(row.m_table.get()), row.m_row_ndx); - return *this; -} - -template -inline BasicRow::~BasicRow() noexcept -{ - RowBase::impl_detach(); -} - -template -inline T* BasicRow::impl_get_table() const noexcept -{ - return m_table.get(); -} - -template -inline size_t BasicRow::impl_get_row_ndx() const noexcept -{ - return m_row_ndx; -} - -} // namespace realm - -#endif // REALM_ROW_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/spec.hpp b/Lesson14/Pods/Realm/include/core/realm/spec.hpp deleted file mode 100644 index 6b793f0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/spec.hpp +++ /dev/null @@ -1,388 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_SPEC_HPP -#define REALM_SPEC_HPP - -#include -#include -#include -#include -#include -#include - -namespace realm { - -class Table; - -class Spec { -public: - ~Spec() noexcept; - - Allocator& get_alloc() const noexcept; - - bool has_strong_link_columns() noexcept; - - void insert_column(size_t column_ndx, ColumnType type, StringData name, ColumnAttr attr = col_attr_None); - void rename_column(size_t column_ndx, StringData new_name); - - /// Erase the column at the specified index, and move columns at - /// succeeding indexes to the next lower index. - /// - /// This function is guaranteed to *never* throw if the spec is - /// used in a non-transactional context, or if the spec has - /// already been successfully modified within the current write - /// transaction. - void erase_column(size_t column_ndx); - - //@{ - // If a new Spec is constructed from the returned subspec - // reference, it is the responsibility of the application that the - // parent Spec object (this) is kept alive for at least as long as - // the new Spec object. - Spec* get_subtable_spec(size_t column_ndx) noexcept; - //@} - - // Column info - size_t get_column_count() const noexcept; - size_t get_public_column_count() const noexcept; - DataType get_public_column_type(size_t column_ndx) const noexcept; - ColumnType get_column_type(size_t column_ndx) const noexcept; - StringData get_column_name(size_t column_ndx) const noexcept; - - /// Returns size_t(-1) if the specified column is not found. - size_t get_column_index(StringData name) const noexcept; - - // Column Attributes - ColumnAttr get_column_attr(size_t column_ndx) const noexcept; - - size_t get_subspec_ndx(size_t column_ndx) const noexcept; - ref_type get_subspec_ref(size_t subspec_ndx) const noexcept; - Spec* get_subspec_by_ndx(size_t subspec_ndx) noexcept; - const Spec* get_subspec_by_ndx(size_t subspec_ndx) const noexcept; - - // Auto Enumerated string columns - void upgrade_string_to_enum(size_t column_ndx, ref_type keys_ref, ArrayParent*& keys_parent, size_t& keys_ndx); - size_t get_enumkeys_ndx(size_t column_ndx) const noexcept; - ref_type get_enumkeys_ref(size_t column_ndx, ArrayParent** keys_parent = nullptr, - size_t* keys_ndx = nullptr) noexcept; - - // Links - size_t get_opposite_link_table_ndx(size_t column_ndx) const noexcept; - void set_opposite_link_table_ndx(size_t column_ndx, size_t table_ndx); - - // Backlinks - bool has_backlinks() const noexcept; - size_t first_backlink_column_index() const noexcept; - size_t backlink_column_count() const noexcept; - void set_backlink_origin_column(size_t backlink_col_ndx, size_t origin_col_ndx); - size_t get_origin_column_ndx(size_t backlink_col_ndx) const noexcept; - size_t find_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx) const noexcept; - - /// Get position in `Table::m_columns` of the specified column. It may be - /// different from the specified logical column index due to the presence of - /// search indexes, since their top refs are stored in Table::m_columns as - /// well. - size_t get_column_ndx_in_parent(size_t column_ndx) const; - - //@{ - /// Compare two table specs for equality. - bool operator==(const Spec&) const noexcept; - bool operator!=(const Spec&) const noexcept; - //@} - - void detach() noexcept; - void destroy() noexcept; - - size_t get_ndx_in_parent() const noexcept; - void set_ndx_in_parent(size_t) noexcept; - -#ifdef REALM_DEBUG - void verify() const; - void to_dot(std::ostream&, StringData title = StringData()) const; -#endif - -private: - // Underlying array structure. - // - // `m_subspecs` contains one entry for each subtable column, one entry for - // each link or link list columns, two entries for each backlink column, and - // zero entries for all other column types. For subtable columns the entry - // is a ref pointing to the subtable spec, for link and link list columns it - // is the group-level table index of the target table, and for backlink - // columns the first entry is the group-level table index of the origin - // table, and the second entry is the index of the origin column in the - // origin table. - Array m_top; - ArrayInteger m_types; // 1st slot in m_top - ArrayString m_names; // 2nd slot in m_top - ArrayInteger m_attr; // 3rd slot in m_top - Array m_subspecs; // 4th slot in m_top (optional) - Array m_enumkeys; // 5th slot in m_top (optional) - struct SubspecPtr { - SubspecPtr(bool is_spec_ptr = false) - : m_is_spec_ptr(is_spec_ptr) - { - } - std::unique_ptr m_spec; - bool m_is_spec_ptr; - }; - using SubspecPtrs = std::vector; - SubspecPtrs m_subspec_ptrs; - bool m_has_strong_link_columns; - - Spec(Allocator&) noexcept; // Unattached - - bool init(ref_type) noexcept; - void init(MemRef) noexcept; - void update_has_strong_link_columns() noexcept; - void reset_subspec_ptrs(); - void adj_subspec_ptrs(); - - // Returns true in case the ref has changed. - bool init_from_parent() noexcept; - - ref_type get_ref() const noexcept; - - /// Called in the context of Group::commit() to ensure that - /// attached table accessors stay valid across a commit. Please - /// note that this works only for non-transactional commits. Table - /// accessors obtained during a transaction are always detached - /// when the transaction ends. - bool update_from_parent(size_t old_baseline) noexcept; - - void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept; - - void set_column_type(size_t column_ndx, ColumnType type); - void set_column_attr(size_t column_ndx, ColumnAttr attr); - - /// Construct an empty spec and return just the reference to the - /// underlying memory. - static MemRef create_empty_spec(Allocator&); - - struct ColumnInfo { - size_t m_column_ref_ndx = 0; ///< Index within Table::m_columns - bool m_has_search_index = false; - }; - - ColumnInfo get_column_info(size_t column_ndx) const noexcept; - - size_t get_subspec_ndx_after(size_t column_ndx, size_t skip_column_ndx) const noexcept; - size_t get_subspec_entries_for_col_type(ColumnType type) const noexcept; - bool has_subspec() const noexcept; - - // Returns false if the spec has no columns, otherwise it returns - // true and sets `type` to the type of the first column. - static bool get_first_column_type_from_ref(ref_type, Allocator&, ColumnType& type) noexcept; - - friend class Replication; - friend class Group; - friend class Table; -}; - -// Implementation: - -inline Allocator& Spec::get_alloc() const noexcept -{ - return m_top.get_alloc(); -} - -inline bool Spec::has_strong_link_columns() noexcept -{ - return m_has_strong_link_columns; -} - -inline ref_type Spec::get_subspec_ref(size_t subspec_ndx) const noexcept -{ - REALM_ASSERT(subspec_ndx < m_subspecs.size()); - - // Note that this addresses subspecs directly, indexing - // by number of sub-table columns - return m_subspecs.get_as_ref(subspec_ndx); -} - -// Uninitialized Spec (call init() to init) -inline Spec::Spec(Allocator& alloc) noexcept - : m_top(alloc) - , m_types(alloc) - , m_names(alloc) - , m_attr(alloc) - , m_subspecs(alloc) - , m_enumkeys(alloc) -{ -} - -inline Spec* Spec::get_subtable_spec(size_t column_ndx) noexcept -{ - REALM_ASSERT(column_ndx < get_column_count()); - REALM_ASSERT(get_column_type(column_ndx) == col_type_Table); - size_t subspec_ndx = get_subspec_ndx(column_ndx); - return get_subspec_by_ndx(subspec_ndx); -} - -inline const Spec* Spec::get_subspec_by_ndx(size_t subspec_ndx) const noexcept -{ - return const_cast(this)->get_subspec_by_ndx(subspec_ndx); -} - -inline bool Spec::init_from_parent() noexcept -{ - ref_type ref = m_top.get_ref_from_parent(); - return init(ref); -} - -inline void Spec::destroy() noexcept -{ - m_top.destroy_deep(); -} - -inline size_t Spec::get_ndx_in_parent() const noexcept -{ - return m_top.get_ndx_in_parent(); -} - -inline void Spec::set_ndx_in_parent(size_t ndx) noexcept -{ - m_top.set_ndx_in_parent(ndx); -} - -inline ref_type Spec::get_ref() const noexcept -{ - return m_top.get_ref(); -} - -inline void Spec::set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept -{ - m_top.set_parent(parent, ndx_in_parent); -} - -inline void Spec::rename_column(size_t column_ndx, StringData new_name) -{ - REALM_ASSERT(column_ndx < m_types.size()); - m_names.set(column_ndx, new_name); -} - -inline size_t Spec::get_column_count() const noexcept -{ - // This is the total count of columns, including backlinks (not public) - return m_types.size(); -} - -inline size_t Spec::get_public_column_count() const noexcept -{ - // Backlinks are the last columns, and do not have names, so getting - // the number of names gives us the count of user facing columns - return m_names.size(); -} - -inline ColumnType Spec::get_column_type(size_t ndx) const noexcept -{ - REALM_ASSERT(ndx < get_column_count()); - return ColumnType(m_types.get(ndx)); -} - -inline void Spec::set_column_type(size_t column_ndx, ColumnType type) -{ - REALM_ASSERT(column_ndx < get_column_count()); - - // At this point we only support upgrading to string enum - REALM_ASSERT(ColumnType(m_types.get(column_ndx)) == col_type_String); - REALM_ASSERT(type == col_type_StringEnum); - - m_types.set(column_ndx, type); // Throws - - update_has_strong_link_columns(); -} - -inline ColumnAttr Spec::get_column_attr(size_t ndx) const noexcept -{ - REALM_ASSERT(ndx < get_column_count()); - return ColumnAttr(m_attr.get(ndx)); -} - -inline void Spec::set_column_attr(size_t column_ndx, ColumnAttr attr) -{ - REALM_ASSERT(column_ndx < get_column_count()); - - // At this point we only allow one attr at a time - // so setting it will overwrite existing. In the future - // we will allow combinations. - m_attr.set(column_ndx, attr); - - update_has_strong_link_columns(); -} - -inline StringData Spec::get_column_name(size_t ndx) const noexcept -{ - REALM_ASSERT(ndx < get_column_count()); - return m_names.get(ndx); -} - -inline size_t Spec::get_column_index(StringData name) const noexcept -{ - return m_names.find_first(name); -} - -inline bool Spec::get_first_column_type_from_ref(ref_type top_ref, Allocator& alloc, ColumnType& type) noexcept -{ - const char* top_header = alloc.translate(top_ref); - ref_type types_ref = to_ref(Array::get(top_header, 0)); - const char* types_header = alloc.translate(types_ref); - if (Array::get_size_from_header(types_header) == 0) - return false; - type = ColumnType(Array::get(types_header, 0)); - return true; -} - -inline bool Spec::has_backlinks() const noexcept -{ - // backlinks are always last and do not have names. - return m_names.size() < m_types.size(); - - // Fixme: It's bad design that backlinks are stored and recognized like this. Backlink columns - // should be a column type like any other, and we should find another way to hide them away from - // the user. -} - -inline size_t Spec::first_backlink_column_index() const noexcept -{ - return m_names.size(); -} - -inline size_t Spec::backlink_column_count() const noexcept -{ - return m_types.size() - m_names.size(); -} - -// Spec will have a subspec when it contains a column which is one of: -// link, linklist, backlink, or subtable. It is possible for m_top.size() -// to contain an entry for m_subspecs (at index 3) but this reference -// may be empty if the spec contains enumkeys (at index 4) but no subspec types. -inline bool Spec::has_subspec() const noexcept -{ - return (m_top.size() >= 4) && (m_top.get_as_ref(3) != 0); -} - -inline bool Spec::operator!=(const Spec& s) const noexcept -{ - return !(*this == s); -} - -} // namespace realm - -#endif // REALM_SPEC_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/string_data.hpp b/Lesson14/Pods/Realm/include/core/realm/string_data.hpp deleted file mode 100644 index 0917fc9..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/string_data.hpp +++ /dev/null @@ -1,410 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_STRING_HPP -#define REALM_STRING_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - -/// Selects CityHash64 on 64-bit platforms, and Murmur2 on 32-bit platforms. -/// This is what libc++ does, and it is a good general choice for a -/// non-cryptographic hash function (suitable for std::unordered_map etc.). -size_t murmur2_or_cityhash(const unsigned char* data, size_t len) noexcept; - -uint_least32_t murmur2_32(const unsigned char* data, size_t len) noexcept; -uint_least64_t cityhash_64(const unsigned char* data, size_t len) noexcept; - - -/// A reference to a chunk of character data. -/// -/// An instance of this class can be thought of as a type tag on a region of -/// memory. It does not own the referenced memory, nor does it in any other way -/// attempt to manage the lifetime of it. -/// -/// A null character inside the referenced region is considered a part of the -/// string by Realm. -/// -/// For compatibility with C-style strings, when a string is stored in a Realm -/// database, it is always followed by a terminating null character, regardless -/// of whether the string itself has internal null characters. This means that -/// when a StringData object is extracted from Realm, the referenced region is -/// guaranteed to be followed immediately by an extra null character, but that -/// null character is not inside the referenced region. Therefore, all of the -/// following forms are guaranteed to return a pointer to a null-terminated -/// string: -/// -/// \code{.cpp} -/// -/// group.get_table_name(...).data() -/// table.get_column_name().data() -/// table.get_string(...).data() -/// table.get_mixed(...).get_string().data() -/// -/// \endcode -/// -/// Note that in general, no assumptions can be made about what follows a string -/// that is referenced by a StringData object, or whether anything follows it at -/// all. In particular, the receiver of a StringData object cannot assume that -/// the referenced string is followed by a null character unless there is an -/// externally provided guarantee. -/// -/// This class makes it possible to distinguish between a 'null' reference and a -/// reference to the empty string (see is_null()). -/// -/// \sa BinaryData -/// \sa Mixed -class StringData { -public: - /// Construct a null reference. - StringData() noexcept; - - /// If \a external_data is 'null', \a data_size must be zero. - StringData(const char* external_data, size_t data_size) noexcept; - - template - StringData(const std::basic_string&); - - template - operator std::basic_string() const; - - // StringData does not store data, callers must manage their own strings. - template - StringData(const std::basic_string&&) = delete; - - template - StringData(const util::Optional>&); - - StringData(const null&) noexcept; - - /// Initialize from a zero terminated C style string. Pass null to construct - /// a null reference. - StringData(const char* c_str) noexcept; - - char operator[](size_t i) const noexcept; - - const char* data() const noexcept; - size_t size() const noexcept; - - /// Is this a null reference? - /// - /// An instance of StringData is a null reference when, and only when the - /// stored size is zero (size()) and the stored pointer is the null pointer - /// (data()). - /// - /// In the case of the empty string, the stored size is still zero, but the - /// stored pointer is **not** the null pointer. It could for example point - /// to the empty string literal. Note that the actual value of the pointer - /// is immaterial in this case (as long as it is not zero), because when the - /// size is zero, it is an error to dereference the pointer. - /// - /// Conversion of a StringData object to `bool` yields the logical negation - /// of the result of calling this function. In other words, a StringData - /// object is converted to true if it is not the null reference, otherwise - /// it is converted to false. - bool is_null() const noexcept; - - friend bool operator==(const StringData&, const StringData&) noexcept; - friend bool operator!=(const StringData&, const StringData&) noexcept; - - //@{ - /// Trivial bytewise lexicographical comparison. - friend bool operator<(const StringData&, const StringData&) noexcept; - friend bool operator>(const StringData&, const StringData&) noexcept; - friend bool operator<=(const StringData&, const StringData&) noexcept; - friend bool operator>=(const StringData&, const StringData&) noexcept; - //@} - - bool begins_with(StringData) const noexcept; - bool ends_with(StringData) const noexcept; - bool contains(StringData) const noexcept; - bool contains(StringData d, const std::array &charmap) const noexcept; - - // Wildcard matching ('?' for single char, '*' for zero or more chars) - // case insensitive version in unicode.hpp - bool like(StringData) const noexcept; - - //@{ - /// Undefined behavior if \a n, \a i, or i+n is greater than - /// size(). - StringData prefix(size_t n) const noexcept; - StringData suffix(size_t n) const noexcept; - StringData substr(size_t i, size_t n) const noexcept; - StringData substr(size_t i) const noexcept; - //@} - - template - friend std::basic_ostream& operator<<(std::basic_ostream&, const StringData&); - - explicit operator bool() const noexcept; - - /// If the StringData is NULL, the hash is 0. Otherwise, the function - /// `murmur2_or_cityhash()` is called on the data. - size_t hash() const noexcept; - -private: - const char* m_data; - size_t m_size; - - static bool matchlike(const StringData& text, const StringData& pattern) noexcept; - static bool matchlike_ins(const StringData& text, const StringData& pattern_upper, - const StringData& pattern_lower) noexcept; - - friend bool string_like_ins(StringData, StringData) noexcept; - friend bool string_like_ins(StringData, StringData, StringData) noexcept; -}; - - -// Implementation: - -inline StringData::StringData() noexcept - : m_data(nullptr) - , m_size(0) -{ -} - -inline StringData::StringData(const char* external_data, size_t data_size) noexcept - : m_data(external_data) - , m_size(data_size) -{ - REALM_ASSERT_DEBUG(external_data || data_size == 0); -} - -template -inline StringData::StringData(const std::basic_string& s) - : m_data(s.data()) - , m_size(s.size()) -{ -} - -template -inline StringData::operator std::basic_string() const -{ - return std::basic_string(m_data, m_size); -} - -template -inline StringData::StringData(const util::Optional>& s) - : m_data(s ? s->data() : nullptr) - , m_size(s ? s->size() : 0) -{ -} - -inline StringData::StringData(const null&) noexcept - : m_data(nullptr) - , m_size(0) -{ -} - -inline StringData::StringData(const char* c_str) noexcept - : m_data(c_str) - , m_size(0) -{ - if (c_str) - m_size = std::char_traits::length(c_str); -} - -inline char StringData::operator[](size_t i) const noexcept -{ - return m_data[i]; -} - -inline const char* StringData::data() const noexcept -{ - return m_data; -} - -inline size_t StringData::size() const noexcept -{ - return m_size; -} - -inline bool StringData::is_null() const noexcept -{ - return !m_data; -} - -inline bool operator==(const StringData& a, const StringData& b) noexcept -{ - return a.m_size == b.m_size && a.is_null() == b.is_null() && safe_equal(a.m_data, a.m_data + a.m_size, b.m_data); -} - -inline bool operator!=(const StringData& a, const StringData& b) noexcept -{ - return !(a == b); -} - -inline bool operator<(const StringData& a, const StringData& b) noexcept -{ - if (a.is_null() && !b.is_null()) { - // Null strings are smaller than all other strings, and not - // equal to empty strings. - return true; - } - return std::lexicographical_compare(a.m_data, a.m_data + a.m_size, b.m_data, b.m_data + b.m_size); -} - -inline bool operator>(const StringData& a, const StringData& b) noexcept -{ - return b < a; -} - -inline bool operator<=(const StringData& a, const StringData& b) noexcept -{ - return !(b < a); -} - -inline bool operator>=(const StringData& a, const StringData& b) noexcept -{ - return !(a < b); -} - -inline bool StringData::begins_with(StringData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - return d.m_size <= m_size && safe_equal(m_data, m_data + d.m_size, d.m_data); -} - -inline bool StringData::ends_with(StringData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - return d.m_size <= m_size && safe_equal(m_data + m_size - d.m_size, m_data + m_size, d.m_data); -} - -inline bool StringData::contains(StringData d) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - - return d.m_size == 0 || std::search(m_data, m_data + m_size, d.m_data, d.m_data + d.m_size) != m_data + m_size; -} - -/// This method takes an array that maps chars to distance that can be moved (and zero for chars not in needle), -/// allowing the method to apply Boyer-Moore for quick substring search -/// The map is calculated in the StringNode class (so it can be reused across searches) -inline bool StringData::contains(StringData d, const std::array &charmap) const noexcept -{ - if (is_null() && !d.is_null()) - return false; - - size_t needle_size = d.size(); - if (needle_size == 0) - return true; - - // Prepare vars to avoid lookups in loop - size_t last_char_pos = d.size()-1; - unsigned char lastChar = d[last_char_pos]; - - // Do Boyer-Moore search - size_t p = last_char_pos; - while (p < m_size) { - unsigned char c = m_data[p]; // Get candidate for last char - - if (c == lastChar) { - StringData candidate = substr(p-needle_size+1, needle_size); - if (candidate == d) - return true; // text found! - } - - // If we don't have a match, see how far we can move char_pos - if (charmap[c] == 0) - p += needle_size; // char was not present in search string - else - p += charmap[c]; - } - - return false; -} - -inline bool StringData::like(StringData d) const noexcept -{ - if (is_null() || d.is_null()) { - return (is_null() && d.is_null()); - } - - return matchlike(*this, d); -} - -inline StringData StringData::prefix(size_t n) const noexcept -{ - return substr(0, n); -} - -inline StringData StringData::suffix(size_t n) const noexcept -{ - return substr(m_size - n); -} - -inline StringData StringData::substr(size_t i, size_t n) const noexcept -{ - return StringData(m_data + i, n); -} - -inline StringData StringData::substr(size_t i) const noexcept -{ - return substr(i, m_size - i); -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const StringData& d) -{ - for (const char* i = d.m_data; i != d.m_data + d.m_size; ++i) - out << *i; - return out; -} - -inline StringData::operator bool() const noexcept -{ - return !is_null(); -} - -inline size_t StringData::hash() const noexcept -{ - if (is_null()) - return 0; - auto unsigned_data = reinterpret_cast(m_data); - return murmur2_or_cityhash(unsigned_data, m_size); -} - -} // namespace realm - -namespace std { -template <> -struct hash<::realm::StringData> { - inline size_t operator()(const ::realm::StringData& str) const noexcept - { - return str.hash(); - } -}; -} // namespace std - -#endif // REALM_STRING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/changeset.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/changeset.hpp deleted file mode 100644 index 7a79240..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/changeset.hpp +++ /dev/null @@ -1,701 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2017] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_CHANGESET_HPP -#define REALM_SYNC_CHANGESET_HPP - -#include -#include -#include -#include - -#include - -namespace realm { -namespace sync { - -using InternStrings = util::metered::vector; - -struct BadChangesetError : ExceptionWithBacktrace { - const char* m_message; - BadChangesetError() : BadChangesetError("Bad changeset") {} - BadChangesetError(const char* msg) : m_message(msg) {} - const char* message() const noexcept override - { - return m_message; - } -}; - -struct Changeset { - struct Range; - using timestamp_type = uint_fast64_t; - using file_ident_type = uint_fast64_t; - using version_type = uint_fast64_t; // FIXME: Get from `History`. - using StringBuffer = util::BasicStringBuffer; - - Changeset(); - struct share_buffers_tag {}; - Changeset(const Changeset&, share_buffers_tag); - Changeset(Changeset&&) = default; - Changeset& operator=(Changeset&&) = default; - Changeset(const Changeset&) = delete; - Changeset& operator=(const Changeset&) = delete; - - InternString intern_string(StringData); // Slow! - InternString find_string(StringData) const noexcept; // Slow! - StringData string_data() const noexcept; - - StringBuffer& string_buffer() noexcept; - const StringBuffer& string_buffer() const noexcept; - const InternStrings& interned_strings() const noexcept; - InternStrings& interned_strings() noexcept; - - StringBufferRange get_intern_string(InternString) const noexcept; - util::Optional try_get_intern_string(InternString) const noexcept; - util::Optional try_get_string(StringBufferRange) const noexcept; - StringData get_string(StringBufferRange) const noexcept; - StringData get_string(InternString) const noexcept; - StringBufferRange append_string(StringData); - - /// Mark the changeset as "dirty" (i.e. modified by the merge algorithm). - void set_dirty(bool dirty = true) noexcept; - - /// Whether or not the changeset is "dirty" (i.e. has been modified by the - /// merge algorithm). - bool is_dirty() const noexcept; - - // Interface to imitate std::vector: - template struct IteratorImpl; - using iterator = IteratorImpl; - using const_iterator = IteratorImpl; - using value_type = Instruction; - iterator begin() noexcept; - iterator end() noexcept; - const_iterator begin() const noexcept; - const_iterator end() const noexcept; - const_iterator cbegin() const noexcept; - const_iterator cend() const noexcept; - bool empty() const noexcept; - - /// Size of the Changeset, not counting tombstones. - /// - /// FIXME: This is an O(n) operation. - size_t size() const noexcept; - - void clear() noexcept; - - //@{ - /// Insert instructions, invalidating all iterators. - iterator insert(const_iterator pos, Instruction); - template - iterator insert(const_iterator pos, InputIt begin, InputIt end); - //@} - - /// Erase an instruction, invalidating all iterators. - iterator erase(const_iterator); - - /// Insert an instruction at the end, invalidating all iterators. - void push_back(const Instruction&); - - //@{ - /// Insert instructions at \a position without invalidating other - /// iterators. - /// - /// Only iterators created before any call to `insert_stable()` may be - /// considered stable across calls to `insert_stable()`. In addition, - /// "iterator stability" has a very specific meaning here: Other copies of - /// \a position in the program will point to the newly inserted elements - /// after calling `insert_stable()`, rather than point to the value at the - /// position prior to insertion. This is different from, say, a tree - /// structure, where iterator stability signifies the property that - /// iterators keep pointing to the same element after insertion before or - /// after that position. - /// - /// For the purpose of supporting `ChangesetIndex`, and the OT merge - /// algorithm, these semantics are acceptable, since prepended instructions - /// can never create new object or table references. - iterator insert_stable(const_iterator position, Instruction); - template - iterator insert_stable(const_iterator position, InputIt begin, InputIt end); - //@} - - /// Erase instruction at \a position without invalidating other iterators. - /// If erasing the object would invalidate other iterators, it is turned - /// into a tombstone instead, and subsequent derefencing of the iterator - /// will return `nullptr`. An iterator pointing to a tombstone remains valid - /// and can be incremented. - /// - /// Only iterators created before any call to `insert_stable()` may be - /// considered stable across calls to `erase_stable()`. If other copies of - /// \a position exist in the program, they will either point to the - /// subsequent element if that element was previously inserted with - /// `insert_stable()`, or otherwise it will be turned into a tombstone. - iterator erase_stable(const_iterator position); - -#if REALM_DEBUG - struct Reflector; - struct Printer; - void verify() const; - void print(std::ostream&) const; - void print() const; // prints to std::err -#endif - - /// The version that this changeset produced. Note: This may not be the - /// version produced by this changeset on the client on which this changeset - /// originated, but may for instance be the version produced on the server - /// after receiving and re-sending this changeset to another client. - /// - /// FIXME: The explanation above is confusing. The truth is that if this - /// changeset was received by a client from the server, then \a version is - /// the version that was produced on the server by this changeset. - /// - /// FIXME: This property, as well as \a last_integrated_remote_version, \a - /// origin_timestamp, and \a origin_file_ident should probably be removed - /// from this class, as they are not a logical part of a changeset, and also - /// are difficult to document without knowing more about what context the - /// changeset object occurs. Also, functions such as - /// InstructionApplier::apply() that a changeset as argument, but do not - /// care about those properties. - version_type version = 0; - - /// On clients, the last integrated server version. On the server, this is - /// the last integrated client version. - /// - /// FIXME: The explanation above is confusing. The truth is that if this - /// changeset was received by a client from the server, then \a - /// last_integrated_remote_version is the last client version that was - /// integrated by the server at the server version referencened by \a - /// version. - version_type last_integrated_remote_version = 0; - - /// Timestamp at origin when the original untransformed changeset was - /// produced. - timestamp_type origin_timestamp = 0; - - /// The identifier of the file in the context of which the original - /// untransformed changeset was produced. - file_ident_type origin_file_ident = 0; - -private: - struct MultiInstruction { - util::metered::vector instructions; - }; - static_assert(sizeof(MultiInstruction) <= Instruction::max_instruction_size, "Instruction::max_instruction_size too low"); - - // In order to achieve iterator semi-stability (just enough to be able to - // run the merge algorithm while maintaining a ChangesetIndex), a Changeset - // is really a list of lists. A Changeset is a vector of - // `InstructionContainer`s, and each `InstructionContainer` represents 0-N - // "real" instructions. - // - // As an optimization, there is a special case for when the - // `InstructionContainer` represents exactly 1 instruction, in which case it - // is represented inside the `InstructionContainer` without any additional - // allocations or indirections. The `InstructionContainer` derived from - // the `Instruction` struct, and co-opts the `type` field such that if the - // (invalid) value of `type` is 0xff, the contents of the `Instruction` are - // instead interpreted as an instance of `MultiInstruction`, which holds - // a vector of `Instruction`s. - // - // The size of the `MultiInstruction` may also be zero, in which case it is - // considered a "tombstone" - always as a result of a call to - // `Changeset::erase_stable()`. The potential existence of these tombstones - // is the reason that the value type of `Changeset::iterator` is - // `Instruction*`, rather than `Instruction&`. - // - // FIXME: It would be better if `Changeset::iterator::value_type` could be - // `util::Optional`, but this is prevented by a bug in - // `util::Optional`. - struct InstructionContainer : Instruction { - InstructionContainer(); - InstructionContainer(const Instruction& instr); - InstructionContainer(InstructionContainer&&) noexcept; - InstructionContainer(const InstructionContainer&); - ~InstructionContainer(); - InstructionContainer& operator=(InstructionContainer&&) noexcept; - InstructionContainer& operator=(const InstructionContainer&); - - bool is_multi() const noexcept; - void convert_to_multi(); - void insert(size_t position, Instruction instr); - void erase(size_t position); - size_t size() const noexcept; - bool is_empty() const noexcept; - - Instruction& at(size_t pos) noexcept; - const Instruction& at(size_t pos) const noexcept; - - MultiInstruction& get_multi() noexcept; - const MultiInstruction& get_multi() const noexcept; - }; - - util::metered::vector m_instructions; - std::shared_ptr m_string_buffer; - std::shared_ptr m_strings; - bool m_is_dirty = false; - - iterator const_iterator_to_iterator(const_iterator); -}; - -/// An iterator type that hides the implementation details of the support for -/// iterator stability. -/// -/// A `Changeset::iterator` is composed of an -/// `std::vector::iterator` and a `size_t` representing -/// the index into the current `InstructionContainer`. If that container is -/// empty, and the position is zero, the iterator is pointing to a tombstone. -template -struct Changeset::IteratorImpl { - using list_type = util::metered::vector; - using inner_iterator_type = std::conditional_t; - - // reference_type is a pointer because we have no way to create a reference - // to a tombstone instruction. Alternatively, it could have been - // `util::Optional`, but that runs into other issues. - using reference_type = std::conditional_t; - - using pointer_type = std::conditional_t; - using difference_type = std::ptrdiff_t; - - IteratorImpl() : m_pos(0) {} - template - IteratorImpl(const IteratorImpl& other, std::enable_if_t* = nullptr) - : m_inner(other.m_inner), m_pos(other.m_pos) {} - IteratorImpl(inner_iterator_type inner, size_t pos = 0) : m_inner(inner), m_pos(pos) {} - - inline IteratorImpl& operator++() - { - ++m_pos; - if (m_pos >= m_inner->size()) { - ++m_inner; - m_pos = 0; - } - return *this; - } - - IteratorImpl operator++(int) - { - auto copy = *this; - ++(*this); - return copy; - } - - IteratorImpl& operator--() - { - if (m_pos == 0) { - --m_inner; - m_pos = m_inner->size(); - if (m_pos != 0) - --m_pos; - } - else { - --m_pos; - } - return *this; - } - - IteratorImpl operator--(int) - { - auto copy = *this; - --(*this); - return copy; - } - - reference_type operator*() const - { - if (m_inner->size()) { - return &m_inner->at(m_pos); - } - // It was a tombstone. - return nullptr; - } - - pointer_type operator->() const - { - if (m_inner->size()) { - return &m_inner->at(m_pos); - } - // It was a tombstone. - return nullptr; - } - - bool operator==(const IteratorImpl& other) const - { - return m_inner == other.m_inner && m_pos == other.m_pos; - } - - bool operator!=(const IteratorImpl& other) const - { - return !(*this == other); - } - - bool operator<(const IteratorImpl& other) const - { - if (m_inner == other.m_inner) - return m_pos < other.m_pos; - return m_inner < other.m_inner; - } - - bool operator<=(const IteratorImpl& other) const - { - if (m_inner == other.m_inner) - return m_pos <= other.m_pos; - return m_inner < other.m_inner; - } - - bool operator>(const IteratorImpl& other) const - { - if (m_inner == other.m_inner) - return m_pos > other.m_pos; - return m_inner > other.m_inner; - } - - bool operator>=(const IteratorImpl& other) const - { - if (m_inner == other.m_inner) - return m_pos >= other.m_pos; - return m_inner > other.m_inner; - } - - inner_iterator_type m_inner; - size_t m_pos; -}; - -struct Changeset::Range { - iterator begin; - iterator end; -}; - -#if REALM_DEBUG -struct Changeset::Reflector { - struct Tracer { - virtual void name(StringData) = 0; - virtual void field(StringData, StringData) = 0; - virtual void field(StringData, ObjectID) = 0; - virtual void field(StringData, int64_t) = 0; - virtual void field(StringData, double) = 0; - virtual void after_each() {} - virtual void before_each() {} - }; - - Reflector(Tracer& tracer, const Changeset& log) : - m_tracer(tracer), m_log(log) - {} - - void visit_all() const; -private: - Tracer& m_tracer; - const Changeset& m_log; - - friend struct Instruction; // permit access for visit() -#define REALM_DEFINE_REFLECTOR_VISITOR(X) void operator()(const Instruction::X&) const; - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_REFLECTOR_VISITOR) -#undef REALM_DEFINE_REFLECTOR_VISITOR -}; - -struct Changeset::Printer : Changeset::Reflector::Tracer { - explicit Printer(std::ostream& os) : m_out(os) - {} - - // ChangesetReflector::Tracer interface: - void name(StringData) final; - void field(StringData, StringData) final; - void field(StringData, ObjectID) final; - void field(StringData, int64_t) final; - void field(StringData, double) final; - void after_each() final; - -private: - std::ostream& m_out; - bool m_first = true; - void pad_or_ellipsis(StringData, int width) const; - void print_field(StringData name, std::string value); -}; -#endif // REALM_DEBUG - - - -/// Implementation: - -inline Changeset::iterator Changeset::begin() noexcept -{ - return m_instructions.begin(); -} - -inline Changeset::iterator Changeset::end() noexcept -{ - return m_instructions.end(); -} - -inline Changeset::const_iterator Changeset::begin() const noexcept -{ - return m_instructions.begin(); -} - -inline Changeset::const_iterator Changeset::end() const noexcept -{ - return m_instructions.end(); -} - -inline Changeset::const_iterator Changeset::cbegin() const noexcept -{ - return m_instructions.cbegin(); -} - -inline Changeset::const_iterator Changeset::cend() const noexcept -{ - return m_instructions.end(); -} - -inline bool Changeset::empty() const noexcept -{ - return size() == 0; -} - -inline size_t Changeset::size() const noexcept -{ - size_t sum = 0; - for (auto& x: m_instructions) - sum += x.size(); - return sum; -} - -inline void Changeset::clear() noexcept -{ - m_instructions.clear(); -} - -inline util::Optional Changeset::try_get_intern_string(InternString string) const noexcept -{ - if (string.value >= m_strings->size()) - return util::none; - return (*m_strings)[string.value]; -} - -inline StringBufferRange Changeset::get_intern_string(InternString string) const noexcept -{ - auto str = try_get_intern_string(string); - REALM_ASSERT(str); - return *str; -} - -inline InternStrings& Changeset::interned_strings() noexcept -{ - return *m_strings; -} - -inline const InternStrings& Changeset::interned_strings() const noexcept -{ - return *m_strings; -} - -inline auto Changeset::string_buffer() noexcept -> StringBuffer& -{ - return *m_string_buffer; -} - -inline auto Changeset::string_buffer() const noexcept -> const StringBuffer& -{ - return *m_string_buffer; -} - -inline util::Optional Changeset::try_get_string(StringBufferRange range) const noexcept -{ - if (range.offset > m_string_buffer->size()) - return util::none; - if (range.offset + range.size > m_string_buffer->size()) - return util::none; - return StringData{m_string_buffer->data() + range.offset, range.size}; -} - -inline StringData Changeset::get_string(StringBufferRange range) const noexcept -{ - auto string = try_get_string(range); - REALM_ASSERT(string); - return *string; -} - -inline StringData Changeset::get_string(InternString string) const noexcept -{ - return get_string(get_intern_string(string)); -} - -inline StringData Changeset::string_data() const noexcept -{ - return StringData{m_string_buffer->data(), m_string_buffer->size()}; -} - -inline StringBufferRange Changeset::append_string(StringData string) -{ - m_string_buffer->reserve(1024); // we expect more strings - size_t offset = m_string_buffer->size(); - m_string_buffer->append(string.data(), string.size()); - return StringBufferRange{uint32_t(offset), uint32_t(string.size())}; -} - -inline bool Changeset::is_dirty() const noexcept -{ - return m_is_dirty; -} - -inline void Changeset::set_dirty(bool dirty) noexcept -{ - m_is_dirty = dirty; -} - -inline Changeset::iterator Changeset::insert(const_iterator pos, Instruction instr) -{ - Instruction* p = &instr; - return insert(pos, p, p + 1); -} - -template -inline Changeset::iterator Changeset::insert(const_iterator pos, InputIt begin, InputIt end) -{ - if (pos.m_pos == 0) - return m_instructions.insert(pos.m_inner, begin, end); - return insert_stable(pos, begin, end); -} - -inline Changeset::iterator Changeset::erase(const_iterator pos) -{ - if (pos.m_inner->size() <= 1) - return m_instructions.erase(pos.m_inner); - return erase_stable(pos); -} - -inline Changeset::iterator Changeset::insert_stable(const_iterator pos, Instruction instr) -{ - Instruction* p = &instr; - return insert_stable(pos, p, p + 1); -} - -template -inline Changeset::iterator Changeset::insert_stable(const_iterator cpos, InputIt begin, InputIt end) -{ - iterator pos = const_iterator_to_iterator(cpos); - size_t i = 0; - for (auto it = begin; it != end; ++it, ++i) { - pos.m_inner->insert(pos.m_pos + i, *it); - } - return pos; -} - -inline Changeset::iterator Changeset::erase_stable(const_iterator cpos) -{ - auto pos = const_iterator_to_iterator(cpos); - auto begin = m_instructions.begin(); - auto end = m_instructions.end(); - REALM_ASSERT(pos.m_inner >= begin); - REALM_ASSERT(pos.m_inner < end); - pos.m_inner->erase(pos.m_pos); - if (pos.m_pos >= pos.m_inner->size()) { - do { - ++pos.m_inner; - } while (pos.m_inner != end && pos.m_inner->is_empty()); - pos.m_pos = 0; - } - return pos; -} - -inline void Changeset::push_back(const Instruction& instr) -{ - m_instructions.emplace_back(instr); -} - -inline auto Changeset::const_iterator_to_iterator(const_iterator cpos) -> iterator -{ - size_t offset = cpos.m_inner - m_instructions.cbegin(); - return iterator{m_instructions.begin() + offset, cpos.m_pos}; -} - -inline Changeset::InstructionContainer::~InstructionContainer() -{ - if (is_multi()) { - get_multi().~MultiInstruction(); - } - // Instruction subtypes are required to be POD-types (trivially - // destructible), and this is checked by a static_assert in - // instructions.hpp. Therefore, it is safe to do nothing if this is not a - // multi-instruction. -} - -inline bool Changeset::InstructionContainer::is_multi() const noexcept -{ - return type == Type(InstrTypeMultiInstruction); -} - -inline size_t Changeset::InstructionContainer::size() const noexcept -{ - if (is_multi()) - return get_multi().instructions.size(); - return 1; -} - -inline bool Changeset::InstructionContainer::is_empty() const noexcept -{ - if (is_multi()) { - return get_multi().instructions.empty(); - } - return false; -} - -inline Instruction& Changeset::InstructionContainer::at(size_t pos) noexcept -{ - REALM_ASSERT(pos < size()); - if (is_multi()) - return get_multi().instructions[pos]; - return *this; -} - -inline const Instruction& Changeset::InstructionContainer::at(size_t pos) const noexcept -{ - REALM_ASSERT(pos < size()); - if (is_multi()) - return get_multi().instructions[pos]; - return *this; -} - -inline Changeset::MultiInstruction& Changeset::InstructionContainer::get_multi() noexcept -{ - REALM_ASSERT(is_multi()); - return *reinterpret_cast(&m_storage); -} - -inline const Changeset::MultiInstruction& Changeset::InstructionContainer::get_multi() const noexcept -{ - REALM_ASSERT(is_multi()); - return *reinterpret_cast(&m_storage); -} - -} // namespace sync -} // namespace realm - -namespace std { - -template -struct iterator_traits> { - using difference_type = std::ptrdiff_t; - using iterator_category = std::bidirectional_iterator_tag; -}; - -} // namespace std - -#endif // REALM_SYNC_CHANGESET_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp deleted file mode 100644 index 3d003be..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_cooker.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#include - -#ifndef REALM_SYNC_CHANGESET_COOKER_HPP -#define REALM_SYNC_CHANGESET_COOKER_HPP - -namespace realm { -namespace sync { - -/// Copy raw changesets unmodified. -class TrivialChangesetCooker: public ClientHistory::ChangesetCooker { -public: - bool cook_changeset(const Group&, const char* changeset, - std::size_t changeset_size, - util::AppendBuffer&) override; -}; - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CHANGESET_COOKER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp deleted file mode 100644 index 5c3618a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_encoder.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2017] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_CHANGESET_ENCODER_HPP -#define REALM_SYNC_CHANGESET_ENCODER_HPP - -#include -#include -#include - -namespace realm { -namespace sync { - -struct ChangesetEncoder: InstructionHandler { - using Buffer = util::AppendBuffer; - - Buffer release() noexcept; - void reset() noexcept; - const Buffer& buffer() const noexcept; - InternString intern_string(StringData); - - void set_intern_string(uint32_t index, StringBufferRange) override; - // FIXME: This doesn't copy the input, but the drawback is that there can - // only be a single StringBufferRange per instruction. Luckily, no - // instructions exist that require two or more. - StringBufferRange add_string_range(StringData) override; - void operator()(const Instruction&) override; - -#define REALM_DEFINE_INSTRUCTION_HANDLER(X) void operator()(const Instruction::X&); - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_HANDLER) -#undef REALM_DEFINE_INSTRUCTION_HANDLER - - void encode_single(const Changeset& log); - -protected: - template static void encode(E& encoder, const Instruction&); - - StringData get_string(StringBufferRange) const noexcept; - -private: - template - void append(Instruction::Type t, Args&&...); - void append_string(StringBufferRange); // does not intern the string - void append_bytes(const void*, size_t); - - template void append_int(T); - void append_payload(const Instruction::Payload&); - void append_value(DataType); - void append_value(bool); - void append_value(uint8_t); - void append_value(int64_t); - void append_value(uint32_t); - void append_value(uint64_t); - void append_value(float); - void append_value(double); - void append_value(InternString); - void append_value(sync::ObjectID); - void append_value(Timestamp); - - Buffer m_buffer; - util::metered::map m_intern_strings_rev; - StringData m_string_range; -}; - -template -void encode_changeset(const Changeset&, util::AppendBuffer& out_buffer); - - -// Implementation - -inline auto ChangesetEncoder::buffer() const noexcept -> const Buffer& -{ - return m_buffer; -} - -inline void ChangesetEncoder::operator()(const Instruction& instr) -{ - encode(*this, instr); // Throws -} - -template inline void ChangesetEncoder::encode(E& encoder, const Instruction& instr) -{ - instr.visit(encoder); // Throws -} - -inline StringData ChangesetEncoder::get_string(StringBufferRange range) const noexcept -{ - const char* data = m_string_range.data() + range.offset; - std::size_t size = std::size_t(range.size); - return StringData{data, size}; -} - -template -void encode_changeset(const Changeset& changeset, util::AppendBuffer& out_buffer) -{ - ChangesetEncoder encoder; - encoder.encode_single(changeset); // Throws - auto& buffer = encoder.buffer(); - out_buffer.append(buffer.data(), buffer.size()); // Throws -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CHANGESET_ENCODER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_parser.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/changeset_parser.hpp deleted file mode 100644 index f331569..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/changeset_parser.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2017] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_CHANGESET_PARSER_HPP -#define REALM_SYNC_CHANGESET_PARSER_HPP - -#include -#include - -namespace realm { -namespace sync { - -struct ChangesetParser { - /// Throws BadChangesetError if parsing fails. - /// - /// FIXME: Consider using std::error_code instead of throwing exceptions on - /// parse errors. - void parse(_impl::NoCopyInputStream&, InstructionHandler&); -private: - struct State; -}; - -void parse_changeset(_impl::NoCopyInputStream&, Changeset& out_log); -void parse_changeset(_impl::InputStream&, Changeset& out_log); - - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CHANGESET_PARSER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/client.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/client.hpp deleted file mode 100644 index 9521130..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/client.hpp +++ /dev/null @@ -1,1364 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2012] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_SYNC_CLIENT_HPP -#define REALM_SYNC_CLIENT_HPP - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace realm { -namespace sync { - - -class Client { -public: - enum class Error; - - enum class ReconnectMode { - /// This is the mode that should always be used in production. In this - /// mode the client uses a scheme for determining a reconnect delay that - /// prevents it from creating too many connection requests in a short - /// amount of time (i.e., a server hammering protection mechanism). - normal, - - /// For testing purposes only. - /// - /// Never reconnect automatically after the connection is closed due to - /// an error. Allow immediate reconnect if the connection was closed - /// voluntarily (e.g., due to sessions being abandoned). - /// - /// In this mode, Client::cancel_reconnect_delay() and - /// Session::cancel_reconnect_delay() can still be used to trigger - /// another reconnection attempt (with no delay) after an error has - /// caused the connection to be closed. - testing - }; - - using port_type = util::network::Endpoint::port_type; - using RoundtripTimeHandler = void(milliseconds_type roundtrip_time); - - static constexpr milliseconds_type default_connect_timeout = 120000; // 2 minutes - static constexpr milliseconds_type default_connection_linger_time = 30000; // 30 seconds - static constexpr milliseconds_type default_ping_keepalive_period = 60000; // 1 minute - static constexpr milliseconds_type default_pong_keepalive_timeout = 120000; // 2 minutes - static constexpr milliseconds_type default_fast_reconnect_limit = 60000; // 1 minute - - struct Config { - Config() {} - - /// An optional custom platform description to be sent to server as part - /// of a user agent description (HTTP `User-Agent` header). - /// - /// If left empty, the platform description will be whatever is returned - /// by util::get_platform_info(). - std::string user_agent_platform_info; - - /// Optional information about the application to be added to the user - /// agent description as sent to the server. The intention is that the - /// application describes itself using the following (rough) syntax: - /// - /// ::= ( )* - /// ::= "/" [
] - /// ::= ()+ - /// ::= ( | "." | "-" | "_")* - ///
::= - /// ::= "(" ( | )* ")" - /// - /// Where `` is a single space character, `` is a decimal - /// digit, `` is any alphanumeric character, and `` is - /// any character other than `(` and `)`. - /// - /// When multiple levels are present, the innermost layer (the one that - /// is closest to this API) should appear first. - /// - /// Example: - /// - /// RealmJS/2.13.0 RealmStudio/2.9.0 - /// - /// Note: The user agent description is not intended for machine - /// interpretation, but should still follow the specified syntax such - /// that it remains easily interpretable by human beings. - std::string user_agent_application_info; - - /// The maximum number of Realm files that will be kept open - /// concurrently by this client. The client keeps a cache of open Realm - /// files for efficiency reasons. - long max_open_files = 256; - - /// An optional logger to be used by the client. If no logger is - /// specified, the client will use an instance of util::StderrLogger - /// with the log level threshold set to util::Logger::Level::info. The - /// client does not require a thread-safe logger, and it guarantees that - /// all logging happens either on behalf of the constructor or on behalf - /// of the invocation of run(). - util::Logger* logger = nullptr; - - /// Use ports 80 and 443 by default instead of 7800 and 7801 - /// respectively. Ideally, these default ports should have been made - /// available via a different URI scheme instead (http/https or ws/wss). - bool enable_default_port_hack = true; - - /// For testing purposes only. - ReconnectMode reconnect_mode = ReconnectMode::normal; - - /// Create a separate connection for each session. For testing purposes - /// only. - /// - /// FIXME: This setting needs to be true for now, due to limitations in - /// the load balancer. - bool one_connection_per_session = true; - - /// Do not access the local file system. Sessions will act as if - /// initiated on behalf of an empty (or nonexisting) local Realm - /// file. Received DOWNLOAD messages will be accepted, but otherwise - /// ignored. No UPLOAD messages will be generated. For testing purposes - /// only. - /// - /// Many operations, such as serialized transactions, are not suppored - /// in this mode. - bool dry_run = false; - - /// The default changeset cooker to be used by new sessions. Can be - /// overridden by Session::Config::changeset_cooker. - /// - /// \sa make_client_history(), TrivialChangesetCooker. - std::shared_ptr changeset_cooker; - - /// The maximum number of milliseconds to allow for a connection to - /// become fully established. This includes the time to resolve the - /// network address, the TCP connect operation, the SSL handshake, and - /// the WebSocket handshake. - milliseconds_type connect_timeout = default_connect_timeout; - - /// The number of milliseconds to keep a connection open after all - /// sessions have been abandoned (or suspended by errors). - /// - /// The purpose of this linger time is to avoid close/reopen cycles - /// during short periods of time where there are no sessions interested - /// in using the connection. - /// - /// If the connection gets closed due to an error before the linger time - /// expires, the connection will be kept closed until there are sessions - /// willing to use it again. - milliseconds_type connection_linger_time = default_connection_linger_time; - - /// The client will send PING messages periodically to allow the server - /// to detect dead connections (heartbeat). This parameter specifies the - /// time, in milliseconds, between these PING messages. When scheduling - /// the next PING message, the client will deduct a small random amount - /// from the specified value to help spread the load on the server from - /// many clients. - milliseconds_type ping_keepalive_period = default_ping_keepalive_period; - - /// Whenever the server receives a PING message, it is supposed to - /// respond with a PONG messsage to allow the client to detect dead - /// connections (heartbeat). This parameter specifies the time, in - /// milliseconds, that the client will wait for the PONG response - /// message before it assumes that the connection is dead, and - /// terminates it. - milliseconds_type pong_keepalive_timeout = default_pong_keepalive_timeout; - - /// The maximum amount of time, in milliseconds, since the loss of a - /// prior connection, for a new connection to be considered a *fast - /// reconnect*. - /// - /// In general, when a client establishes a connection to the server, - /// the uploading process remains suspended until the initial - /// downloading process completes (as if by invocation of - /// Session::async_wait_for_download_completion()). However, to avoid - /// unnecessary latency in change propagation during ongoing - /// application-level activity, if the new connection is established - /// less than a certain amount of time (`fast_reconnect_limit`) since - /// the client was previously connected to the server, then the - /// uploading process will be activated immediately. - /// - /// For now, the purpose of the general delaying of the activation of - /// the uploading process, is to increase the chance of multiple initial - /// transactions on the client-side, to be uploaded to, and processed by - /// the server as a single unit. In the longer run, the intention is - /// that the client should upload transformed (from reciprocal history), - /// rather than original changesets when applicable to reduce the need - /// for changeset to be transformed on both sides. The delaying of the - /// upload process will increase the number of cases where this is - /// possible. - /// - /// FIXME: Currently, the time between connections is not tracked across - /// sessions, so if the application closes its session, and opens a new - /// one immediately afterwards, the activation of the upload process - /// will be delayed unconditionally. - milliseconds_type fast_reconnect_limit = default_fast_reconnect_limit; - - /// Set to true to completely disable delaying of the upload process. In - /// this mode, the upload process will be activated immediately, and the - /// value of `fast_reconnect_limit` is ignored. - /// - /// For testing purposes only. - bool disable_upload_activation_delay = false; - - /// If `disable_upload_compaction` is true, every changeset will be - /// compacted before it is uploaded to the server. Compaction will - /// reduce the size of a changeset if the same field is set multiple - /// times or if newly created objects are deleted within the same - /// transaction. Log compaction increeses CPU usage and memory - /// consumption. - bool disable_upload_compaction = false; - - /// Set the `TCP_NODELAY` option on all TCP/IP sockets. This disables - /// the Nagle algorithm. Disabling it, can in some cases be used to - /// decrease latencies, but possibly at the expense of scalability. Be - /// sure to research the subject before you enable this option. - bool tcp_no_delay = false; - - /// The specified function will be called whenever a PONG message is - /// received on any connection. The round-trip time in milliseconds will - /// be pased to the function. The specified function will always be - /// called by the client's event loop thread, i.e., the thread that - /// calls `Client::run()`. This feature is mainly for testing purposes. - std::function roundtrip_time_handler; - - /// Disable sync to disk (fsync(), msync()) for all realm files managed - /// by this client. - /// - /// Testing/debugging feature. Should never be enabled in production. - bool disable_sync_to_disk = false; - }; - - /// \throw util::EventLoop::Implementation::NotAvailable if no event loop - /// implementation was specified, and - /// util::EventLoop::Implementation::get_default() throws it. - Client(Config = {}); - Client(Client&&) noexcept; - ~Client() noexcept; - - /// Run the internal event-loop of the client. At most one thread may - /// execute run() at any given time. The call will not return until somebody - /// calls stop(). - void run(); - - /// See run(). - /// - /// Thread-safe. - void stop() noexcept; - - /// \brief Cancel current or next reconnect delay for all servers. - /// - /// This corresponds to calling Session::cancel_reconnect_delay() on all - /// bound sessions, but will also cancel reconnect delays applying to - /// servers for which there are currently no bound sessions. - /// - /// Thread-safe. - void cancel_reconnect_delay(); - - /// \brief Wait for session termination to complete. - /// - /// Wait for termination of all sessions whose termination was initiated - /// prior this call (the completion condition), or until the client's event - /// loop thread exits from Client::run(), whichever happens - /// first. Termination of a session can be initiated implicitly (e.g., via - /// destruction of the session object), or explicitly by Session::detach(). - /// - /// Note: After session termination (when this function returns true) no - /// session specific callback function can be called or continue to execute, - /// and the client is guaranteed to no longer have a Realm file open on - /// behalf of the terminated session. - /// - /// CAUTION: If run() returns while a wait operation is in progress, this - /// waiting function will return immediately, even if the completion - /// condition is not yet satisfied. The completion condition is guaranteed - /// to be satisfied only when these functions return true. If it returns - /// false, session specific callback functions may still be executing or get - /// called, and the associated Realm files may still not have been closed. - /// - /// If a new wait operation is initiated while another wait operation is in - /// progress by another thread, the waiting period of fist operation may, or - /// may not get extended. The application must not assume either. - /// - /// Note: Session termination does not imply that the client has received an - /// UNBOUND message from the server (see the protocol specification). This - /// may happen later. - /// - /// \return True only if the completion condition was satisfied. False if - /// the client's event loop thread exited from Client::run() in which case - /// the completion condition may, or may not have been satisfied. - /// - /// Note: These functions are fully thread-safe. That is, they may be called - /// by any thread, and by multiple threads concurrently. - bool wait_for_session_terminations_or_client_stopped(); - - /// Returns false if the specified URL is invalid. - bool decompose_server_url(const std::string& url, ProtocolEnvelope& protocol, - std::string& address, port_type& port, std::string& path) const; - -private: - class Impl; - std::unique_ptr m_impl; - friend class Session; -}; - - -class BadServerUrl; // Exception - - -/// \brief Client-side representation of a Realm file synchronization session. -/// -/// A synchronization session deals with precisely one local Realm file. To -/// synchronize multiple local Realm files, you need multiple sessions. -/// -/// A session object is always associated with a particular client object (\ref -/// Client). The application must ensure that the destruction of the associated -/// client object never happens before the destruction of the session -/// object. The consequences of a violation are unspecified. -/// -/// A session object is always associated with a particular local Realm file, -/// however, a session object does not represent a session until it is bound to -/// a server side Realm, i.e., until bind() is called. From the point of view of -/// the thread that calls bind(), the session starts precisely when the -/// execution of bind() starts, i.e., before bind() returns. -/// -/// At most one session is allowed to exist for a particular local Realm file -/// (file system inode) at any point in time. Multiple session objects may -/// coexists for a single file, as long as bind() has been called on at most one -/// of them. Additionally, two bound session objects for the same file are -/// allowed to exist at different times, if they have no overlap in time (in -/// their bound state), as long as they are associated with the same client -/// object, or with two different client objects that do not overlap in -/// time. This means, in particular, that it is an error to create two bound -/// session objects for the same local Realm file, it they are associated with -/// two different client objects that overlap in time, even if the session -/// objects do not overlap in time (in their bound state). It is the -/// responsibility of the application to ensure that these rules are adhered -/// to. The consequences of a violation are unspecified. -/// -/// Thread-safety: It is safe for multiple threads to construct, use (with some -/// exceptions), and destroy session objects concurrently, regardless of whether -/// those session objects are associated with the same, or with different Client -/// objects. Please note that some of the public member functions are fully -/// thread-safe, while others are not. -/// -/// Callback semantics: All session specific callback functions will be executed -/// by the event loop thread, i.e., the thread that calls Client::run(). No -/// callback function will be called before Session::bind() is called. Callback -/// functions that are specified prior to calling bind() (e.g., any passed to -/// set_progress_handler()) may start to execute before bind() returns, as long -/// as some thread is executing Client::run(). Likewise, completion handlers, -/// such as those passed to async_wait_for_sync_completion() may start to -/// execute before the submitting function returns. All session specific -/// callback functions (including completion handlers) are guaranteed to no -/// longer be executing when session termination completes, and they are -/// guaranteed to not be called after session termination completes. Termination -/// is an event that completes asynchronously with respect to the application, -/// but is initiated by calling detach(), or implicitely by destroying a session -/// object. After having initiated one or more session terminations, the -/// application can wait for those terminations to complete by calling -/// Client::wait_for_session_terminations_or_client_stopped(). Since callback -/// functinos are always executed by the event loop thread, they are also -/// guaranteed to not be executing after Client::run() has returned. -class Session { -public: - using port_type = util::network::Endpoint::port_type; - using SyncTransactCallback = void(VersionID old_version, VersionID new_version); - using ProgressHandler = void(std::uint_fast64_t downloaded_bytes, - std::uint_fast64_t downloadable_bytes, - std::uint_fast64_t uploaded_bytes, - std::uint_fast64_t uploadable_bytes, - std::uint_fast64_t progress_version, - std::uint_fast64_t snapshot_version); - using WaitOperCompletionHandler = std::function; - using SerialTransactChangeset = util::Buffer; - using SerialTransactInitiationHandler = std::function; - using SerialTransactCompletionHandler = std::function; - using SSLVerifyCallback = bool(const std::string& server_address, - port_type server_port, - const char* pem_data, - size_t pem_size, - int preverify_ok, - int depth); - - struct Config { - Config() {} - - /// server_address is the fully qualified host name, or IP address of - /// the server. - std::string server_address = "localhost"; - - /// server_port is the port at which the server listens. If server_port - /// is zero, the default port for the specified protocol is used. See - /// ProtocolEnvelope for information on default ports. - port_type server_port = 0; - - /// server_path is the virtual path by which the server identifies the - /// Realm. This path must always be an absolute path, and must therefore - /// always contain a leading slash (`/`). Further more, each segment of the - /// virtual path must consist of one or more characters that are either - /// alpha-numeric or in (`_`, `-`, `.`), and each segment is not allowed to - /// equal `.` or `..`, and must not end with `.realm`, `.realm.lock`, or - /// `.realm.management`. These rules are necessary because the server - /// currently reserves the right to use the specified path as part of the - /// file system path of a Realm file. It is expected that these rules will - /// be significantly relaxed in the future by completely decoupling the - /// virtual paths from actual file system paths. - std::string server_path = "/"; - - /// The protocol used for communicating with the server. See - /// ProtocolEnvelope. - ProtocolEnvelope protocol_envelope = ProtocolEnvelope::realm; - - /// url_prefix is a prefix that is prepended to the server_path - /// in the HTTP GET request that initiates a sync connection. The value - /// specified here must match with the server's expectation. Changing - /// the value of url_prefix should be matched with a corresponding - /// change of the server side proxy. - std::string url_prefix = "/realm-sync"; - - /// authorization_header_name is the name of the HTTP header containing - /// the Realm access token. The value of the HTTP header is - /// "Realm-Access-Token version=1 token=....". - /// authorization_header_name does not participate in session - /// multiplexing partitioning. - std::string authorization_header_name = "Authorization"; - - /// custom_http_headers is a map of custom HTTP headers. The keys of the map - /// are HTTP header names, and the values are the corresponding HTTP - /// header values. - /// If "Authorization" is used as a custom header name, - /// authorization_header_name must be set to anther value. - std::map custom_http_headers; - - /// Sessions can be multiplexed over the same TCP/SSL connection. - /// Sessions might share connection if they have identical server_address, - /// server_port, and protocol. multiplex_ident is a parameter that allows - /// finer control over session multiplexing. If two sessions have distinct - /// multiplex_ident, they will never share connection. The typical use of - /// multilex_ident is to give sessions with incompatible SSL requirements - /// distinct multiplex_idents. - /// multiplex_ident can be any string and the value has no meaning except - /// for partitioning the sessions. - std::string multiplex_ident; - - /// Controls whether the server certificate is verified for SSL - /// connections. It should generally be true in production. - bool verify_servers_ssl_certificate = true; - - /// ssl_trust_certificate_path is the path of a trust/anchor - /// certificate used by the client to verify the server certificate. - /// ssl_trust_certificate_path is only used if the protocol is ssl and - /// verify_servers_ssl_certificate is true. - /// - /// A server certificate is verified by first checking that the - /// certificate has a valid signature chain back to a trust/anchor - /// certificate, and secondly checking that the server_address matches - /// a host name contained in the certificate. The host name of the - /// certificate is stored in either Common Name or the Alternative - /// Subject Name (DNS section). - /// - /// If ssl_trust_certificate_path is None (default), ssl_verify_callback - /// (see below) is used if set, and the default device trust/anchor - /// store is used otherwise. - util::Optional ssl_trust_certificate_path; - - /// If Client::Config::ssl_verify_callback is set, that function is called - /// to verify the certificate, unless verify_servers_ssl_certificate is - /// false. - - /// ssl_verify_callback is used to implement custom SSL certificate - /// verification. it is only used if the protocol is SSL, - /// verify_servers_ssl_certificate is true and ssl_trust_certificate_path - /// is None. - /// - /// The signature of ssl_verify_callback is - /// - /// bool(const std::string& server_address, - /// port_type server_port, - /// const char* pem_data, - /// size_t pem_size, - /// int preverify_ok, - /// int depth); - /// - /// server address and server_port is the address and port of the server - /// that a SSL connection is being established to. They are identical to - /// the server_address and server_port set in this config file and are - /// passed for convenience. - /// pem_data is the certificate of length pem_size in - /// the PEM format. preverify_ok is OpenSSL's preverification of the - /// certificate. preverify_ok is either 0, or 1. If preverify_ok is 1, - /// OpenSSL has accepted the certificate and it will generally be safe - /// to trust that certificate. depth represents the position of the - /// certificate in the certificate chain sent by the server. depth = 0 - /// represents the actual server certificate that should contain the - /// host name(server address) of the server. The highest depth is the - /// root certificate. - /// The callback function will receive the certificates starting from - /// the root certificate and moving down the chain until it reaches the - /// server's own certificate with a host name. The depth of the last - /// certificate is 0. The depth of the first certificate is chain - /// length - 1. - /// - /// The return value of the callback function decides whether the - /// client accepts the certificate. If the return value is false, the - /// processing of the certificate chain is interrupted and the SSL - /// connection is rejected. If the return value is true, the verification - /// process continues. If the callback function returns true for all - /// presented certificates including the depth == 0 certificate, the - /// SSL connection is accepted. - /// - /// A recommended way of using the callback function is to return true - /// if preverify_ok = 1 and depth > 0, - /// always check the host name if depth = 0, - /// and use an independent verification step if preverify_ok = 0. - /// - /// Another possible way of using the callback is to collect all the - /// certificates until depth = 0, and present the entire chain for - /// independent verification. - std::function ssl_verify_callback; - - /// signed_user_token is a cryptographically signed token describing the - /// identity and access rights of the current user. - std::string signed_user_token; - - /// If not null, overrides whatever is specified by - /// Client::Config::changeset_cooker. - /// - /// The shared ownership over the cooker will be relinquished shortly - /// after the destruction of the session object as long as the event - /// loop of the client is being executed (Client::run()). - /// - /// CAUTION: ChangesetCooker::cook_changeset() of the specified cooker - /// may get called before the call to bind() returns, and it may get - /// called (or continue to execute) after the session object is - /// destroyed. Please see "Callback semantics" section under Client for - /// more on this. - /// - /// \sa make_client_history(), TrivialChangesetCooker. - std::shared_ptr changeset_cooker; - - /// The encryption key the SharedGroup will be opened with. - util::Optional> encryption_key; - - /// ClientReset is used for both async open and client reset. If - /// client_reset is not util::none, the sync client will perform - /// async open for this session if the local Realm does not exist, and - /// client reset if the local Realm exists. If client_reset is - /// util::none, an ordinary sync session will take place. - /// - /// A session will perform async open by downloading a state Realm, and - /// some metadata, from the server, patching up the metadata part of - /// the Realm and finally move the downloaded Realm into the path of - /// the local Realm. After completion of async open, the application - /// can open and use the Realm. - /// - /// A session will perform client reset by downloading a state Realm, and - /// some metadata, from the server. After download, the state Realm will - /// be integrated into the local Realm in a write transaction. The - /// application is free to use the local realm during the entire client - /// reset. Like a DOWNLOAD message, the application will not be able - /// to perform a write transaction at the same time as the sync client - /// performs its own write transaction. Client reset is not more - /// disturbing for the application than any DOWNLOAD message. The - /// application can listen to change notifications from the client - /// reset exactly as in a DOWNLOAD message. - /// - /// The client reset will recover non-uploaded changes in the local - /// Realm if and only if 'recover_local_changes' is true. In case, - /// 'recover_local_changes' is false, the local Realm state will hence - /// be set to the server's state (server wins). - /// - /// Async open and client reset require a private directory for - /// metadata. This directory must be specified in the option - /// 'metadata_dir'. The metadata_dir must not be touched during async - /// open or client reset. The metadata_dir can safely be removed at - /// times where async open or client reset do not take place. The sync - /// client attempts to clean up metadata_dir. The metadata_dir can be - /// reused across app restarts to resume an interrupted download. It is - /// recommended to leave the metadata_dir unchanged except when it is - /// known that async open or client reset is done. - /// - /// The recommended usage of async open is to use it for the initial - /// bootstrap if Realm usage is not needed until after the server state - /// has been downloaded. - /// - /// The recommended usage of client reset is after a previous session - /// encountered an error that implies the need for a client reset. It - /// is not recommended to persist the need for a client reset. The - /// application should just attempt to synchronize in the usual fashion - /// and only after hitting an error, start a new session with a client - /// reset. In other words, if the application crashes during a client reset, - /// the application should attempt to perform ordinary synchronization - /// after restart and switch to client reset if needed. - /// - /// Error codes that imply the need for a client reset are the session - /// level error codes: - /// - /// bad_client_file_ident = 208, // Bad client file identifier (IDENT) - /// bad_server_version = 209, // Bad server version (IDENT, UPLOAD) - /// bad_client_version = 210, // Bad client version (IDENT, UPLOAD) - /// diverging_histories = 211, // Diverging histories (IDENT) - /// - /// However, other errors such as bad changeset (UPLOAD) could also be resolved - /// with a client reset. Client reset can even be used without any prior error - /// if so desired. - /// - /// After completion of async open and client reset, the sync client - /// will continue synchronizing with the server in the usual fashion. - /// - /// The progress of async open and client reset can be tracked with the - /// standard progress handler. - /// - /// Async open and client reset are done when the progress handler - /// arguments satisfy "progress_version > 0". However, if the - /// application wants to ensure that it has all data present on the - /// server, it should wait for download completion using either - /// void async_wait_for_download_completion(WaitOperCompletionHandler) - /// or - /// bool wait_for_download_complete_or_client_stopped(). - /// - /// The option 'require_recent_state_realm' is used for async open to - /// request a recent state Realm. A recent state Realm is never empty - /// (unless there is no data), and is recent in the sense that it was - /// produced by the current incarnation of the server. Recent does not - /// mean the absolutely newest possible state Realm, since that might - /// lead to too excessive work on the server. Setting - /// 'require_recent_state_realm' to true might lead to more work - /// performed by the server but it ensures that more data is downloaded - /// using async open instead of ordinary synchronization. It is - /// recommended to set 'require_recent_state_realm' to true. Client - /// reset always downloads a recent state Realm. - struct ClientReset { - std::string metadata_dir; - bool recover_local_changes = true; - bool require_recent_state_realm = true; - }; - util::Optional client_reset_config; - - struct ProxyConfig { - enum class Type { HTTP, HTTPS } type; - std::string address; - port_type port; - }; - util::Optional proxy_config; - - /// Set to true to disable the upload process for this session. This - /// includes the sending of empty UPLOAD messages. - /// - /// This feature exists exclusively for testing purposes at this time. - bool disable_upload = false; - - /// Set to true to disable sending of empty UPLOAD messages for this - /// session. - /// - /// This feature exists exclusively for testing purposes at this time. - bool disable_empty_upload = false; - - /// Set to true to cause the integration of the first received changeset - /// (in a DOWNLOAD message) to fail. - /// - /// This feature exists exclusively for testing purposes at this time. - bool simulate_integration_error = false; - }; - - /// \brief Start a new session for the specified client-side Realm. - /// - /// Note that the session is not fully activated until you call bind(). - /// Also note that if you call set_sync_transact_callback(), it must be - /// done before calling bind(). - /// - /// \param realm_path The file-system path of a local client-side Realm - /// file. - Session(Client&, std::string realm_path, Config = {}); - - /// This leaves the right-hand side session object detached. See "Thread - /// safety" section under detach(). - Session(Session&&) noexcept; - - /// Create a detached session object (see detach()). - Session() noexcept; - - /// Implies detachment. See "Thread safety" section under detach(). - ~Session() noexcept; - - /// Detach the object on the left-hand side, then "steal" the session from - /// the object on the right-hand side, if there is one. This leaves the - /// object on the right-hand side detached. See "Thread safety" section - /// under detach(). - Session& operator=(Session&&) noexcept; - - /// Detach this sesion object from the client object (Client). If the - /// session object is already detached, this function has no effect - /// (idempotency). - /// - /// Detachment initiates session termination, which is an event that takes - /// place shortly therafter in the context of the client's event loop - /// thread. - /// - /// A detached session object may be destroyed, move-assigned to, and moved - /// from. Apart from that, it is an error to call any function other than - /// detach() on a detached session object. - /// - /// Thread safety: Detachment is not a thread-safe operation. This means - /// that detach() may not be executed by two threads concurrently, and may - /// not execute concurrently with object destruction. Additionally, - /// detachment must not execute concurrently with a moving operation - /// involving the session object on the left or right-hand side. See move - /// constructor and assigment operator. - void detach() noexcept; - - /// \brief Set a function to be called when the local Realm has changed due - /// to integration of a downloaded changeset. - /// - /// Specify the callback function that will be called when one or more - /// transactions are performed to integrate downloaded changesets into the - /// client-side Realm, that is associated with this session. - /// - /// The callback function will always be called by the thread that executes - /// the event loop (Client::run()), but not until bind() is called. If the - /// callback function throws an exception, that exception will "travel" out - /// through Client::run(). - /// - /// Note: Any call to this function must have returned before bind() is - /// called. If this function is called multiple times, each call overrides - /// the previous setting. - /// - /// Note: This function is **not thread-safe**. That is, it is an error if - /// it is called while another thread is executing any member function on - /// the same Session object. - /// - /// CAUTION: The specified callback function may get called before the call - /// to bind() returns, and it may get called (or continue to execute) after - /// the session object is destroyed. Please see "Callback semantics" section - /// under Session for more on this. - void set_sync_transact_callback(std::function); - - /// \brief Set a handler to monitor the state of download and upload - /// progress. - /// - /// The handler must have signature - /// - /// void(uint_fast64_t downloaded_bytes, uint_fast64_t downloadable_bytes, - /// uint_fast64_t uploaded_bytes, uint_fast64_t uploadable_bytes, - /// uint_fast64_t progress_version); - /// - /// downloaded_bytes is the size in bytes of all downloaded changesets. - /// downloadable_bytes is equal to downloaded_bytes plus an estimate of - /// the size of the remaining server history. - /// - /// uploaded_bytes is the size in bytes of all locally produced changesets - /// that have been received and acknowledged by the server. - /// uploadable_bytes is the size in bytes of all locally produced changesets. - /// - /// Due to the nature of the merge rules, it is possible that the size of an - /// uploaded changeset uploaded from one client is not equal to the size of - /// the changesets that other clients will download. - /// - /// Typical uses of this function: - /// - /// Upload completion can be checked by - /// - /// bool upload_complete = (uploaded_bytes == uploadable_bytes); - /// - /// Download completion could be checked by - /// - /// bool download_complete = (downloaded_bytes == downloadable_bytes); - /// - /// However, download completion might never be reached because the server - /// can receive new changesets from other clients. downloadable_bytes can - /// decrease for two reasons: server side compaction and changesets of - /// local origin. Code using downloadable_bytes must not assume that it - /// is increasing. - /// - /// Upload progress can be calculated by caching an initial value of - /// uploaded_bytes from the last, or next, callback. Then - /// - /// double upload_progress = - /// (uploaded_bytes - initial_uploaded_bytes) - /// ------------------------------------------- - /// (uploadable_bytes - initial_uploaded_bytes) - /// - /// Download progress can be calculates similarly: - /// - /// double download_progress = - /// (downloaded_bytes - initial_downloaded_bytes) - /// ----------------------------------------------- - /// (downloadable_bytes - initial_downloaded_bytes) - /// - /// progress_version is 0 at the start of a session. When at least one - /// DOWNLOAD message has been received from the server, progress_version is - /// positive. progress_version can be used to ensure that the reported - /// progress contains information obtained from the server in the current - /// session. The server will send a message as soon as possible, and the - /// progress handler will eventually be called with a positive progress_version - /// unless the session is interrupted before a message from the server has - /// been received. - /// - /// The handler is called on the event loop thread.The handler after bind(), - /// after each DOWNLOAD message, and after each local transaction - /// (nonsync_transact_notify). - /// - /// set_progress_handler() is not thread safe and it must be called before - /// bind() is called. Subsequent calls to set_progress_handler() overwrite - /// the previous calls. Typically, this function is called once per session. - /// - /// CAUTION: The specified callback function may get called before the call - /// to bind() returns, and it may get called (or continue to execute) after - /// the session object is destroyed. Please see "Callback semantics" section - /// under Session for more on this. - void set_progress_handler(std::function); - - enum class ConnectionState { disconnected, connecting, connected }; - - /// \brief Information about an error causing a session to be temporarily - /// disconnected from the server. - /// - /// In general, the connection will be automatically reestablished - /// later. Whether this happens quickly, generally depends on \ref - /// is_fatal. If \ref is_fatal is true, it means that the error is deemed to - /// be of a kind that is likely to persist, and cause all future reconnect - /// attempts to fail. In that case, if another attempt is made at - /// reconnecting, the delay will be substantial (at least an hour). - /// - /// \ref error_code specifies the error that caused the connection to be - /// closed. For the list of errors reported by the server, see \ref - /// ProtocolError (or `protocol.md`). For the list of errors corresponding - /// to protocol violations that are detected by the client, see - /// Client::Error. The error may also be a system level error, or an error - /// from one of the potential intermediate protocol layers (SSL or - /// WebSocket). - /// - /// \ref detailed_message is the most detailed message available to describe - /// the error. It is generally equal to `error_code.message()`, but may also - /// be a more specific message (one that provides extra context). The - /// purpose of this message is mostly to aid in debugging. For non-debugging - /// purposes, `error_code.message()` should generally be considered - /// sufficient. - /// - /// \sa set_connection_state_change_listener(). - struct ErrorInfo { - std::error_code error_code; - bool is_fatal; - const std::string& detailed_message; - }; - - using ConnectionStateChangeListener = void(ConnectionState, const ErrorInfo*); - - /// \brief Install a connection state change listener. - /// - /// Sets a function to be called whenever the state of the underlying - /// network connection changes between "disconnected", "connecting", and - /// "connected". The initial state is always "disconnected". The next state - /// after "disconnected" is always "connecting". The next state after - /// "connecting" is either "connected" or "disconnected". The next state - /// after "connected" is always "disconnected". A switch to the - /// "disconnected" state only happens when an error occurs. - /// - /// Whenever the installed function is called, an ErrorInfo object is passed - /// when, and only when the passed state is ConnectionState::disconnected. - /// - /// When multiple sessions share a single connection, the state changes will - /// be reported for each session in turn. - /// - /// The callback function will always be called by the thread that executes - /// the event loop (Client::run()), but not until bind() is called. If the - /// callback function throws an exception, that exception will "travel" out - /// through Client::run(). - /// - /// Note: Any call to this function must have returned before bind() is - /// called. If this function is called multiple times, each call overrides - /// the previous setting. - /// - /// Note: This function is **not thread-safe**. That is, it is an error if - /// it is called while another thread is executing any member function on - /// the same Session object. - /// - /// CAUTION: The specified callback function may get called before the call - /// to bind() returns, and it may get called (or continue to execute) after - /// the session object is destroyed. Please see "Callback semantics" section - /// under Session for more on this. - void set_connection_state_change_listener(std::function); - - //@{ - /// Deprecated! Use set_connection_state_change_listener() instead. - using ErrorHandler = void(std::error_code, bool is_fatal, const std::string& detailed_message); - void set_error_handler(std::function); - //@} - - /// @{ \brief Bind this session to the specified server side Realm. - /// - /// No communication takes place on behalf of this session before the - /// session is bound, but as soon as the session becomes bound, the server - /// will start to push changes to the client, and vice versa. - /// - /// If a callback function was set using set_sync_transact_callback(), then - /// that callback function will start to be called as changesets are - /// downloaded and integrated locally. It is important to understand that - /// callback functions are executed by the event loop thread (Client::run()) - /// and the callback function may therefore be called before bind() returns. - /// - /// Note: It is an error if this function is called more than once per - /// Session object. - /// - /// Note: This function is **not thread-safe**. That is, it is an error if - /// it is called while another thread is executing any member function on - /// the same Session object. - /// - /// bind() binds this session to the specified server side Realm using the - /// parameters specified in the Session::Config object. - /// - /// The two other forms of bind() are convenience functions. - /// void bind(std::string server_address, std::string server_path, - /// std::string signed_user_token, port_type server_port = 0, - /// ProtocolEnvelope protocol = ProtocolEnvelope::realm); - /// replaces the corresponding parameters from the Session::Config object - /// before the session is bound. - /// void bind(std::string server_url, std::string signed_user_token) parses - /// the \param server_url and replaces the parameters in the Session::Config object - /// before the session is bound. - /// - /// \param server_url For example "realm://sync.realm.io/test". See - /// server_address, server_path, and server_port in Session::Config for - /// information about the individual components of the URL. See - /// ProtocolEnvelope for the list of available URL schemes and the - /// associated default ports. - /// - /// \throw BadServerUrl if the specified server URL is malformed. - void bind(); - void bind(std::string server_url, std::string signed_user_token); - void bind(std::string server_address, std::string server_path, - std::string signed_user_token, port_type server_port = 0, - ProtocolEnvelope protocol = ProtocolEnvelope::realm); - /// @} - - /// \brief Refresh the access token associated with this session. - /// - /// This causes the REFRESH protocol message to be sent to the server. See - /// ProtocolEnvelope. It is an error to pass a token with a different user - /// identity than the token used to initiate the session. - /// - /// In an on-going session the application may expect the access token to - /// expire at a certain time and schedule acquisition of a fresh access - /// token (using a refresh token or by other means) in due time to provide a - /// better user experience, and seamless connectivity to the server. - /// - /// If the application does not proactively refresh an expiring token, the - /// session will eventually be disconnected. The application can detect this - /// by monitoring the connection state - /// (set_connection_state_change_listener()), and check whether the error - /// code is `ProtocolError::token_expired`. Such a session can then be - /// revived by calling refresh() with a newly acquired access token. - /// - /// Due to protocol techicalities, a race condition exists that can cause a - /// session to become, and remain disconnected after a new access token has - /// been passed to refresh(). The application can work around this race - /// condition by detecting the `ProtocolError::token_expired` error, and - /// always initiate a token renewal in this case. - /// - /// It is an error to call this function before calling `Client::bind()`. - /// - /// Note: This function is thread-safe. - /// - /// \param signed_user_token A cryptographically signed token describing the - /// identity and access rights of the current user. See ProtocolEnvelope. - void refresh(std::string signed_user_token); - - /// \brief Inform the synchronization agent about changes of local origin. - /// - /// This function must be called by the application after a transaction - /// performed on its behalf, that is, after a transaction that is not - /// performed to integrate a changeset that was downloaded from the server. - /// - /// It is an error to call this function before bind() has been called, and - /// has returned. - /// - /// Note: This function is fully thread-safe. That is, it may be called by - /// any thread, and by multiple threads concurrently. - void nonsync_transact_notify(version_type new_version); - - /// @{ \brief Wait for upload, download, or upload+download completion. - /// - /// async_wait_for_upload_completion() initiates an asynchronous wait for - /// upload to complete, async_wait_for_download_completion() initiates an - /// asynchronous wait for download to complete, and - /// async_wait_for_sync_completion() initiates an asynchronous wait for - /// upload and download to complete. - /// - /// Upload is considered complete when all non-empty changesets of local - /// origin have been uploaded to the server, and the server has acknowledged - /// reception of them. Changesets of local origin introduced after the - /// initiation of the session (after bind() is called) will generally not be - /// considered for upload unless they are announced to this client through - /// nonsync_transact_notify() prior to the initiation of the wait operation, - /// i.e., prior to the invocation of async_wait_for_upload_completion() or - /// async_wait_for_sync_completion(). Unannounced changesets may get picked - /// up, but there is no guarantee that they will be, however, if a certain - /// changeset is announced, then all previous changesets are implicitly - /// announced. Also all preexisting changesets are implicitly announced - /// when the session is initiated. - /// - /// Download is considered complete when all non-empty changesets of remote - /// origin have been downloaded from the server, and integrated into the - /// local Realm state. To know what is currently outstanding on the server, - /// the client always sends a special "marker" message to the server, and - /// waits until it has downloaded all outstanding changesets that were - /// present on the server at the time when the server received that marker - /// message. Each call to async_wait_for_download_completion() and - /// async_wait_for_sync_completion() therefore requires a full client <-> - /// server round-trip. - /// - /// If a new wait operation is initiated while another wait operation is in - /// progress by another thread, the waiting period of first operation may, - /// or may not get extended. The application must not assume either. The - /// application may assume, however, that async_wait_for_upload_completion() - /// will not affect the waiting period of - /// async_wait_for_download_completion(), and vice versa. - /// - /// It is an error to call these functions before bind() has been called, - /// and has returned. - /// - /// The specified completion handlers will always be executed by the thread - /// that executes the event loop (the thread that calls Client::run()). If - /// the handler throws an exception, that exception will "travel" out - /// through Client::run(). - /// - /// If incomplete wait operations exist when the session is terminated, - /// those wait operations will be canceled. Session termination is an event - /// that happens in the context of the client's event loop thread shortly - /// after the destruction of the session object. The std::error_code - /// argument passed to the completion handler of a canceled wait operation - /// will be `util::error::operation_aborted`. For uncanceled wait operations - /// it will be `std::error_code{}`. Note that as long as the client's event - /// loop thread is running, all completion handlers will be called - /// regardless of whether the operations get canceled or not. - /// - /// CAUTION: The specified completion handlers may get called before the - /// call to the waiting function returns, and it may get called (or continue - /// to execute) after the session object is destroyed. Please see "Callback - /// semantics" section under Session for more on this. - /// - /// Note: These functions are fully thread-safe. That is, they may be called - /// by any thread, and by multiple threads concurrently. - void async_wait_for_sync_completion(WaitOperCompletionHandler); - void async_wait_for_upload_completion(WaitOperCompletionHandler); - void async_wait_for_download_completion(WaitOperCompletionHandler); - /// @} - - /// @{ \brief Synchronous wait for upload or download completion. - /// - /// These functions are synchronous equivalents of - /// async_wait_for_upload_completion() and - /// async_wait_for_download_completion() respectively. This means that they - /// block the caller until the completion condition is satisfied, or the - /// client's event loop thread exits from Client::run(), whichever happens - /// first. - /// - /// It is an error to call these functions before bind() has been called, - /// and has returned. - /// - /// CAUTION: If Client::run() returns while a wait operation is in progress, - /// these waiting functions return immediately, even if the completion - /// condition is not yet satisfied. The completion condition is guaranteed - /// to be satisfied only when these functions return true. - /// - /// \return True only if the completion condition was satisfied. False if - /// the client's event loop thread exited from Client::run() in which case - /// the completion condition may, or may not have been satisfied. - /// - /// Note: These functions are fully thread-safe. That is, they may be called - /// by any thread, and by multiple threads concurrently. - bool wait_for_upload_complete_or_client_stopped(); - bool wait_for_download_complete_or_client_stopped(); - /// @} - - /// \brief Cancel the current or next reconnect delay for the server - /// associated with this session. - /// - /// When the network connection is severed, or an attempt to establish - /// connection fails, a certain delay will take effect before the client - /// will attempt to reestablish the connection. This delay will generally - /// grow with the number of unsuccessful reconnect attempts, and can grow to - /// over a minute. In some cases however, the application will know when it - /// is a good time to stop waiting and retry immediately. One example is - /// when a device has been offline for a while, and the operating system - /// then tells the application that network connectivity has been restored. - /// - /// Clearly, this function should not be called too often and over extended - /// periods of time, as that would effectively disable the built-in "server - /// hammering" protection. - /// - /// It is an error to call this function before bind() has been called, and - /// has returned. - /// - /// This function is fully thread-safe. That is, it may be called by any - /// thread, and by multiple threads concurrently. - void cancel_reconnect_delay(); - - /// \brief Change address of server for this session. - void override_server(std::string address, port_type); - - /// \brief Initiate a serialized transaction. - /// - /// Asynchronously waits for completion of any serialized transactions, that - /// are already in progress via the same session object, then waits for - /// the download process to complete (async_wait_for_download_completion()), - /// then pauses the upload process. The upload process will be resumed when - /// async_try_complete_serial_transact() or abort_serial_transact() is - /// called. - /// - /// Changesets produced by local transactions, that are committed after the - /// completion of the initiation of a serialized transaction, are guaranteed - /// to not be uploaded until after (or during) the completion of that - /// serialized transaction (async_try_complete_serial_transact()). - /// - /// If the initiation of a serialized transaction is successfully completed, - /// that is, if the specified handler gets called with an std::error_code - /// argument that evaluates to false in a boolean context, then the - /// application is required to eventually call - /// async_try_complete_serial_transact() to complete the transaction, or - /// abort_serial_transact() to abort it. If - /// async_try_complete_serial_transact() fails (throws), the application is - /// required to follow up with a call to abort_serial_transact(). - /// - /// If the session object is destroyed before initiation process completes, - /// the specified handler will be called with error - /// `util::error::operation_aborted`. Currently, this is the only possible - /// error that can be reported through this handler. - /// - /// This feature is only available when the server supports version 28, or - /// later, of the synchronization protocol. See - /// get_current_protocol_version(). - /// - /// This feature is not currently supported with Partial Synchronization, - /// and in a server cluster, it is currently only supported on the root - /// node. - void async_initiate_serial_transact(SerialTransactInitiationHandler); - - /// \brief Complete a serialized transaction. - /// - /// Initiate the completion of the serialized transaction. This involves - /// sending the specified changeset to the server, and waiting for the - /// servers response. - /// - /// If the session object is destroyed before completion process completes, - /// the specified handler will be called with error - /// `util::error::operation_aborted`. - /// - /// Otherwise, if the server does not support serialized transactions, the - /// specified handler will be called with error - /// `util::MiscExtErrors::operation_not_supported`. This happens if the - /// negotiated protocol version is too old, if serialized transactions are - /// disallowed by the server, or if it is not allowed for the Realm file in - /// question (partial synchronization). - /// - /// Otherwise, the specified handler will be called with an error code - /// argument that evaluates to false in a boolean context, and the - /// `accepted` argument will be true if, and only if the transaction was - /// accepted by the server. - /// - /// \param upload_anchor The upload cursor associated with the snapshot on - /// which the specified changeset is based. Use - /// sync::ClientHistory::get_upload_anchor_of_current_transact() to obtain - /// it. Note that - /// sync::ClientHistory::get_upload_anchor_of_current_transact() needs to be - /// called during the transaction that is used to produce the changeset of - /// the serialized transaction. - /// - /// \param changeset A changeset obtained from an aborted transaction on the - /// Realm file associated with this session. Use - /// sync::ClientHistory::get_sync_changeset() to obtain it. The transaction, - /// which is used to produce teh changeset, needs to be rolled back rather - /// than committed, because the decision of whether to accept the changes - /// need to be delegated to the server. Note that - /// sync::ClientHistory::get_sync_Changeset_of_current_transact() needs to - /// be called at the end of the transaction, that is used to produce the - /// changeset, but before the rollback operation. - void async_try_complete_serial_transact(UploadCursor upload_anchor, - SerialTransactChangeset changeset, - SerialTransactCompletionHandler); - - /// \brief Abort a serialized transaction. - /// - /// Must be called if async_try_complete_serial_transact() fails, i.e., if - /// it throws, or if async_try_complete_serial_transact() is not called at - /// all. Must not be called if async_try_complete_serial_transact() - /// succeeds, i.e., if it does not throw. - /// - /// Will resume upload process. - void abort_serial_transact() noexcept; - -private: - class Impl; - Impl* m_impl = nullptr; - - void abandon() noexcept; - void async_wait_for(bool upload_completion, bool download_completion, - WaitOperCompletionHandler); -}; - - -/// \brief Protocol errors discovered by the client. -/// -/// These errors will terminate the network connection (disconnect all sessions -/// associated with the affected connection), and the error will be reported to -/// the application via the connection state change listeners of the affected -/// sessions. -enum class Client::Error { - connection_closed = 100, ///< Connection closed (no error) - unknown_message = 101, ///< Unknown type of input message - bad_syntax = 102, ///< Bad syntax in input message head - limits_exceeded = 103, ///< Limits exceeded in input message - bad_session_ident = 104, ///< Bad session identifier in input message - bad_message_order = 105, ///< Bad input message order - bad_client_file_ident = 106, ///< Bad client file identifier (IDENT) - bad_progress = 107, ///< Bad progress information (DOWNLOAD) - bad_changeset_header_syntax = 108, ///< Bad syntax in changeset header (DOWNLOAD) - bad_changeset_size = 109, ///< Bad changeset size in changeset header (DOWNLOAD) - bad_origin_file_ident = 110, ///< Bad origin file identifier in changeset header (DOWNLOAD) - bad_server_version = 111, ///< Bad server version in changeset header (DOWNLOAD) - bad_changeset = 112, ///< Bad changeset (DOWNLOAD) - bad_request_ident = 113, ///< Bad request identifier (MARK) - bad_error_code = 114, ///< Bad error code (ERROR), - bad_compression = 115, ///< Bad compression (DOWNLOAD) - bad_client_version = 116, ///< Bad last integrated client version in changeset header (DOWNLOAD) - ssl_server_cert_rejected = 117, ///< SSL server certificate rejected - pong_timeout = 118, ///< Timeout on reception of PONG respone message - bad_client_file_ident_salt = 119, ///< Bad client file identifier salt (IDENT) - bad_file_ident = 120, ///< Bad file identifier (ALLOC) - connect_timeout = 121, ///< Sync connection was not fully established in time - bad_timestamp = 122, ///< Bad timestamp (PONG) - bad_protocol_from_server = 123, ///< Bad or missing protocol version information from server - client_too_old_for_server = 124, ///< Protocol version negotiation failed: Client is too old for server - client_too_new_for_server = 125, ///< Protocol version negotiation failed: Client is too new for server - protocol_mismatch = 126, ///< Protocol version negotiation failed: No version supported by both client and server - bad_state_message = 127, ///< Bad values in state message (STATE) - missing_protocol_feature = 128, ///< Requested feature missing in negotiated protocol version - bad_serial_transact_status = 129, ///< Bad status of serialized transaction (TRANSACT) - bad_object_id_substitutions = 130, ///< Bad encoded object identifier substitutions (TRANSACT) - http_tunnel_failed = 131, ///< Failed to establish HTTP tunnel with configured proxy -}; - -const std::error_category& client_error_category() noexcept; - -std::error_code make_error_code(Client::Error) noexcept; - -std::ostream& operator<<(std::ostream& os, Session::Config::ProxyConfig::Type); - -} // namespace sync -} // namespace realm - -namespace std { - -template<> struct is_error_code_enum { - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace sync { - - - -// Implementation - -class BadServerUrl: public std::exception { -public: - const char* what() const noexcept override - { - return "Bad server URL"; - } -}; - -inline Session::Session(Session&& sess) noexcept: - m_impl{sess.m_impl} -{ - sess.m_impl = nullptr; -} - -inline Session::Session() noexcept -{ -} - -inline Session::~Session() noexcept -{ - if (m_impl) - abandon(); -} - -inline Session& Session::operator=(Session&& sess) noexcept -{ - if (m_impl) - abandon(); - m_impl = sess.m_impl; - sess.m_impl = nullptr; - return *this; -} - -inline void Session::detach() noexcept -{ - if (m_impl) - abandon(); - m_impl = nullptr; -} - -inline void Session::set_error_handler(std::function handler) -{ - auto handler_2 = [handler=std::move(handler)](ConnectionState state, - const ErrorInfo* error_info) { - if (state != ConnectionState::disconnected) - return; - REALM_ASSERT(error_info); - std::error_code ec = error_info->error_code; - bool is_fatal = error_info->is_fatal; - const std::string& detailed_message = error_info->detailed_message; - handler(ec, is_fatal, detailed_message); // Throws - }; - set_connection_state_change_listener(std::move(handler_2)); // Throws -} - -inline void Session::async_wait_for_sync_completion(WaitOperCompletionHandler handler) -{ - bool upload_completion = true, download_completion = true; - async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws -} - -inline void Session::async_wait_for_upload_completion(WaitOperCompletionHandler handler) -{ - bool upload_completion = true, download_completion = false; - async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws -} - -inline void Session::async_wait_for_download_completion(WaitOperCompletionHandler handler) -{ - bool upload_completion = false, download_completion = true; - async_wait_for(upload_completion, download_completion, std::move(handler)); // Throws -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CLIENT_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/crypto.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/crypto.hpp deleted file mode 100644 index 40ade0e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/crypto.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_CRYPTO_HPP -#define REALM_SYNC_CRYPTO_HPP - -#include -#include - -#include -#include - -namespace realm { -namespace sync { -namespace crypto { - -/// The digest functions calculate the message digest of the input in \param -/// in_buffer of size \param in_buffer_size. The digest is placed in \param -/// out_buffer. The caller must guarantee that the output buffer is large -/// enough to contain the digest. -/// -/// The functions throw if the underlying platform dependent implementations -/// throw. Typically, exceptions are "out of memory" errors. -/// -/// sha1() calculates the SHA-1 hash value of output size 20. -/// sha256() calculates the SHA-256 hash value of output size 32. -void sha1(const char* in_buffer, size_t in_buffer_size, unsigned char* out_buffer); -void sha256(const char* in_buffer, size_t in_buffer_size, unsigned char* out_buffer); - -} // namespace crypto -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CRYPTO_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/crypto_server.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/crypto_server.hpp deleted file mode 100644 index c241a71..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/crypto_server.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_CRYPTO_SERVER_HPP -#define REALM_SYNC_CRYPTO_SERVER_HPP - -#include -#include - -#include -#include - -namespace realm { -namespace sync { - -struct CryptoError: std::runtime_error { - CryptoError(std::string message) : std::runtime_error(std::move(message)) {} -}; - -/// This class represents a public/private keypair, or more commonly a single public -/// key used for verifying signatures. -/// -/// Only RSA keys are supported for now. -/// -/// Its methods correspond roughly to the EVP_PKEY_* set of functionality found in -/// the OpenSSL library. -class PKey { -public: - PKey(PKey&&); - PKey& operator=(PKey&&); - ~PKey(); - - /// Load RSA public key from \a pemfile. - static PKey load_public(const std::string& pemfile); - /// Load RSA public key from a PEM buffer - static PKey load_public(BinaryData pem_buffer); - - /// Load RSA public/private keypair from \a pemfile. - static PKey load_private(const std::string& pemfile); - /// Load RSA public/private keypair from a PEM buffer - static PKey load_private(BinaryData pem_buffer); - - /// Whether or not the key can be used for signing. - /// - /// True if the private part is loaded. - bool can_sign() const noexcept; - - /// Whether or not the key can be used for verifying. - /// - /// Always true for RSA keys. - bool can_verify() const noexcept; - - /// Sign \a message with the loaded key, if the private part is - /// loaded. Store the signed message as binary data in \a signature. - /// - /// If a private key is not loaded, throws an exception of type CryptoError. - void sign(BinaryData message, util::Buffer& signature) const; - - /// Verify that \a signature is a valid digest of \a message. - /// - /// Returns true if the signature is valid, otherwise false. If an error occurs while - /// attempting verification, an exception of type CryptoError is thrown. - bool verify(BinaryData message, BinaryData signature) const; - -private: - PKey(); - struct Impl; - std::unique_ptr m_impl; -}; - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_CRYPTO_SERVER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/feature_token.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/feature_token.hpp deleted file mode 100644 index 86db015..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/feature_token.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2012] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_SYNC_FEATURE_TOKEN_HPP -#define REALM_SYNC_FEATURE_TOKEN_HPP - -#include - -#if !REALM_MOBILE && !defined(REALM_EXCLUDE_FEATURE_TOKENS) -#define REALM_HAVE_FEATURE_TOKENS 1 -#else -#define REALM_HAVE_FEATURE_TOKENS 0 -#endif - -#if REALM_HAVE_FEATURE_TOKENS - -#include - -#include - -namespace realm { -namespace sync { - -class FeatureGate { -public: - - // The constructor takes a JWT token as argument. - // The constructor throws a std::runtime_error if - // the token is invalid. An invalid token is a token - // that has bad syntax, is not signed by Realm, or is - // expired. - FeatureGate(StringData token); - - // Constructs a feature gate without any features. - FeatureGate(); - ~FeatureGate(); - - FeatureGate(FeatureGate&&); - FeatureGate& operator=(FeatureGate&&); - - bool has_feature(StringData feature_name); - -private: - struct Impl; - std::unique_ptr m_impl; -}; - - -} // namespace sync -} // namespace realm - -#endif // REALM_HAVE_FEATURE_TOKENS -#endif // REALM_SYNC_FEATURE_TOKEN_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/fingerprint.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/fingerprint.hpp deleted file mode 100644 index 13b54ab..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/fingerprint.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_ENCRYPT_FINGERPRINT_HPP -#define REALM_ENCRYPT_FINGERPRINT_HPP - -#include -#include - -#include - -namespace realm { -namespace encrypt { - -// calculate_fingerprint() calculates, and returns, a fingerprint of an -// encryption key. The input key can be util::none in order to calculate a -// fingerprint even in the case of unencrypted Realms. -// -// An intruder cannot recover an unknown encryption_key from the fingerprint, -// and it is safe to save the fingerprint in a file together with the encrypted -// Realms. -// -// calculate_fingerprint() can be considered opaque, but currently the -// fingerprint is a colon separated hex representation of the SHA-256 hash of -// the encryption key. -std::string calculate_fingerprint(const util::Optional> encryption_key); - -// verify_fingerprint() returns true if `fingerprint` was obtained previously -// from calculate_fingerprint() with `encryption_key` as argument. Otherwise, -// verify_fingerprint() returns false with extremely high probability. -bool verify_fingerprint(const std::string& fingerprint, - const util::Optional> encryption_key); - -} // namespace encrypt -} // namespace realm - -#endif // REALM_ENCRYPT_FINGERPRINT_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/history.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/history.hpp deleted file mode 100644 index 5fc571f..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/history.hpp +++ /dev/null @@ -1,613 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#ifndef REALM_SYNC_HISTORY_HPP -#define REALM_SYNC_HISTORY_HPP - - -namespace realm { -namespace _impl { - -struct ObjectIDHistoryState; - -} // namespace _impl -} // namespace realm - - -namespace realm { -namespace sync { - -struct VersionInfo { - /// Realm snapshot version. - version_type realm_version = 0; - - /// The synchronization version corresponding to `realm_version`. - /// - /// In the context of the client-side history type `sync_version.version` - /// will currently always be equal to `realm_version` and - /// `sync_version.salt` will always be zero. - SaltedVersion sync_version = {0, 0}; -}; - - -struct SerialTransactSubstitutions { - struct Class { - InternString name; - std::size_t substitutions_end; - }; - std::vector classes; - std::vector> substitutions; -}; - - -timestamp_type generate_changeset_timestamp() noexcept; - -// FIXME: in C++17, switch to using std::timespec in place of last two -// arguments. -void map_changeset_timestamp(timestamp_type, std::time_t& seconds_since_epoch, - long& nanoseconds) noexcept; - - -/// Thrown if changeset cooking is not either consistently on or consistently -/// off during synchronization (ClientHistory::set_sync_progress() and -/// ClientHistory::integrate_server_changesets()). -class InconsistentUseOfCookedHistory; - -/// Thrown if a bad server version is passed to -/// ClientHistory::get_cooked_status(). -class BadCookedServerVersion; - - -class ClientHistoryBase : - public InstructionReplication { -public: - using SyncTransactCallback = void(VersionID old_version, VersionID new_version); - - /// Get the version of the latest snapshot of the associated Realm, as well - /// as the client file identifier and the synchronization progress as they - /// are stored in that snapshot. - /// - /// The returned current client version is the version produced by the last - /// changeset in the history. The type of version returned here, is the one - /// that identifies an entry in the sync history. Whether this is the same - /// as the snapshot number of the Realm file depends on the history - /// implementation. - /// - /// The returned client file identifier is the one that was last stored by - /// set_client_file_ident(), or `SaltedFileIdent{0, 0}` if - /// set_client_file_ident() has never been called. - /// - /// The returned SyncProgress is the one that was last stored by - /// set_sync_progress(), or `SyncProgress{}` if set_sync_progress() has - /// never been called. - virtual void get_status(version_type& current_client_version, - SaltedFileIdent& client_file_ident, - SyncProgress& progress) const = 0; - - /// Stores the server assigned client file identifier in the associated - /// Realm file, such that it is available via get_status() during future - /// synchronization sessions. It is an error to set this identifier more - /// than once per Realm file. - /// - /// \param client_file_ident The server assigned client-side file - /// identifier. A client-side file identifier is a non-zero positive integer - /// strictly less than 2**64. The server guarantees that all client-side - /// file identifiers generated on behalf of a particular server Realm are - /// unique with respect to each other. The server is free to generate - /// identical identifiers for two client files if they are associated with - /// different server Realms. - /// - /// \param fix_up_object_ids The object ids that depend on client file ident - /// will be fixed in both state and history if this parameter is true. If - /// it is known that there are no objects to fix, it can be set to false to - /// achieve higher performance. - /// - /// The client is required to obtain the file identifier before engaging in - /// synchronization proper, and it must store the identifier and use it to - /// reestablish the connection between the client file and the server file - /// when engaging in future synchronization sessions. - virtual void set_client_file_ident(SaltedFileIdent client_file_ident, - bool fix_up_object_ids) = 0; - - /// Stores the synchronization progress in the associated Realm file in a - /// way that makes it available via get_status() during future - /// synchronization sessions. Progress is reported by the server in the - /// DOWNLOAD message. - /// - /// See struct SyncProgress for a description of \a progress. - /// - /// \param downloadable_bytes If specified, and if the implementation cares - /// about byte-level progress, this function updates the persistent record - /// of the estimate of the number of remaining bytes to be downloaded. - /// - /// \throw InconsistentUseOfCookedHistory If a changeset cooker has been - /// attached to this history object, and the Realm file does not have a - /// cooked history, and a cooked history can no longer be added because some - /// synchronization has already happened. Or if no changeset cooker has been - /// attached, and the Realm file does have a cooked history. - virtual void set_sync_progress(const SyncProgress& progress, - const std::uint_fast64_t* downloadable_bytes, VersionInfo&) = 0; - - struct UploadChangeset { - timestamp_type origin_timestamp; - file_ident_type origin_file_ident; - UploadCursor progress; - ChunkedBinaryData changeset; - std::unique_ptr buffer; - }; - - /// \brief Scan through the history for changesets to be uploaded. - /// - /// This function scans the history for changesets to be uploaded, i.e., for - /// changesets that are not empty, and were not produced by integration of - /// changesets recieved from the server. The scan begins at the position - /// specified by the initial value of \a upload_progress.client_version, and - /// ends no later than at the position specified by \a end_version. - /// - /// The implementation is allowed to end the scan before \a end_version, - /// such as to limit the combined size of returned changesets. However, if - /// the specified range contains any changesets that are supposed to be - /// uploaded, this function must return at least one. - /// - /// Upon return, \a upload_progress will have been updated to point to the - /// position from which the next scan should resume. This must be a position - /// after the last returned changeset, and before any remaining changesets - /// that are supposed to be uploaded, although never a position that - /// succeeds \a end_version. - /// - /// The value passed as \a upload_progress by the caller, must either be one - /// that was produced by an earlier invocation of - /// find_uploadable_changesets(), one that was returned by get_status(), or - /// one that was received by the client in a DOWNLOAD message from the - /// server. When the value comes from a DOWNLOAD message, it is supposed to - /// reflect a value of UploadChangeset::progress produced by an earlier - /// invocation of find_uploadable_changesets(). - /// - /// Found changesets are added to \a uploadable_changesets. - /// - /// \param locked_server_version will be set to the value that should be - /// used as `` in a DOWNLOAD message. - /// - /// For changesets of local origin, UploadChangeset::origin_file_ident will - /// be zero. - virtual void find_uploadable_changesets(UploadCursor& upload_progress, version_type end_version, - std::vector& uploadable_changesets, - version_type& locked_server_version) const = 0; - - using RemoteChangeset = Transformer::RemoteChangeset; - - // FIXME: Apparently, this feature is expected by object store, but why? - // What is it ultimately used for? (@tgoyne) - class SyncTransactReporter { - public: - virtual void report_sync_transact(VersionID old_version, VersionID new_version) = 0; - protected: - ~SyncTransactReporter() {} - }; - - enum class IntegrationError { - bad_origin_file_ident, - bad_changeset - }; - - /// \brief Integrate a sequence of changesets received from the server using - /// a single Realm transaction. - /// - /// Each changeset will be transformed as if by a call to - /// Transformer::transform_remote_changeset(), and then applied to the - /// associated Realm. - /// - /// As a final step, each changeset will be added to the local history (list - /// of applied changesets). - /// - /// This function checks whether the specified changesets specify valid - /// remote origin file identifiers and whether the changesets contain valid - /// sequences of instructions. The caller must already have ensured that the - /// origin file identifiers are strictly positive and not equal to the file - /// identifier assigned to this client by the server. - /// - /// If any of the changesets are invalid, this function returns false and - /// sets `integration_error` to the appropriate value. If they are all - /// deemed valid, this function updates \a version_info to reflect the new - /// version produced by the transaction. - /// - /// \param progress The synchronization progress is what was received in the - /// DOWNLOAD message along with the specified changesets. The progress will - /// be persisted along with the changesets. - /// - /// \param downloadable_bytes If specified, and if the implementation cares - /// about byte-level progress, this function updates the persistent record - /// of the estimate of the number of remaining bytes to be downloaded. - /// - /// \param num_changesets The number of passed changesets. Must be non-zero. - /// - /// \param transact_reporter An optional callback which will be called with the - /// version immediately processing the sync transaction and that of the sync - /// transaction. - /// - /// \throw InconsistentUseOfCookedHistory If a changeset cooker has been - /// attached to this history object, and the Realm file does not have a - /// cooked history, and a cooked history can no longer be added because some - /// synchronization has already happened. Or if no changeset cooker has been - /// attached, and the Realm file does have a cooked history. - virtual bool integrate_server_changesets(const SyncProgress& progress, - const std::uint_fast64_t* downloadable_bytes, - const RemoteChangeset* changesets, - std::size_t num_changesets, VersionInfo& new_version, - IntegrationError& integration_error, util::Logger&, - SyncTransactReporter* transact_reporter = nullptr, - const SerialTransactSubstitutions* = nullptr) = 0; - -protected: - ClientHistoryBase(const std::string& realm_path); -}; - - - -class ClientHistory : public ClientHistoryBase { -public: - class ChangesetCooker; - class Config; - - /// Get the persisted upload/download progress in bytes. - virtual void get_upload_download_bytes(std::uint_fast64_t& downloaded_bytes, - std::uint_fast64_t& downloadable_bytes, - std::uint_fast64_t& uploaded_bytes, - std::uint_fast64_t& uploadable_bytes, - std::uint_fast64_t& snapshot_version) = 0; - - /// See set_cooked_progress(). - struct CookedProgress { - std::int_fast64_t changeset_index = 0; - std::int_fast64_t intrachangeset_progress = 0; - }; - - /// Get information about the current state of the cooked history including - /// the point of progress of its consumption. - /// - /// \param server_version The server version associated with the last cooked - /// changeset that should be skipped. See `/doc/cooked_history.md` for an - /// explanation of the rationale behind this. Specifying zero means that no - /// changesets should be skipped. It is an error to specify a nonzero server - /// version that is not the server version associated with any of of the - /// cooked changesets, or to specify a nonzero server version that precedes - /// the one, that is associated with the last cooked changeset that was - /// marked as consumed. Doing so, will cause BadCookedServerVersion to be - /// thrown. - /// - /// \param num_changesets Set to the total number of produced cooked - /// changesets over the lifetime of the Realm file to which this history - /// accessor object is attached. This is the number of previously consumed - /// changesets plus the number of unconsumed changesets remaining in the - /// Realm file. - /// - /// \param progress The point of progress of the consumption of the cooked - /// history. Initially, and until explicitly modified by - /// set_cooked_progress(), both `CookedProgress::changeset_index` and - /// `CookedProgress::intrachangeset_progress` are zero. If a nonzero value - /// was passed for \a server_version, \a progress will be transparently - /// adjusted to account for the skipped changesets. See also \a - /// num_skipped_changesets. If one or more changesets are skipped, - /// `CookedProgress::intrachangeset_progress` will be set to zero. - /// - /// \param num_skipped_changesets The number of skipped changesets. See also - /// \a server_version. - /// - /// \throw BadCookedServerVersion See \a server_version. - virtual void get_cooked_status(version_type server_version, std::int_fast64_t& num_changesets, - CookedProgress& progress, - std::int_fast64_t& num_skipped_changesets) const = 0; - - /// Fetch the cooked changeset at the specified index. - /// - /// Cooked changesets are made available in the order they are produced by - /// the changeset cooker (ChangesetCooker). - /// - /// Behaviour is undefined if the specified index is less than the index - /// (CookedProgress::changeset_index) returned by get_cooked_progress(), or - /// if it is greater than, or equal to the total number of cooked changesets - /// (as returned by get_num_cooked_changesets()). - /// - /// The callee must append the bytes of the located cooked changeset to the - /// specified buffer, which does not have to be empty initially. - /// - /// \param server_version Will be set to the version produced on the server - /// by an earlier form of the retreived changeset. If the cooked changeset - /// was produced (as output of cooker) before migration of the client-side - /// history compartment to schema version 2, then \a server_version will be - /// set to zero instead, because the real value is unkown. Zero is not a - /// possible value in any other case. - virtual void get_cooked_changeset(std::int_fast64_t index, - util::AppendBuffer&, - version_type& server_version) const = 0; - - /// Persistently stores the point of progress of the consumer of cooked - /// changesets. - /// - /// The changeset index (CookedProgress::changeset_index) is the index (as - /// passed to get_cooked_changeset()) of the first unconsumed cooked - /// changset. Changesets at lower indexes will no longer be available. - /// - /// The intrachangeset progress field - /// (CookedProgress::intrachangeset_progress) will be faithfully persisted, - /// but will otherwise be treated as an opaque object by the history - /// internals. - /// - /// As well as allowing for later retrieval, the specification of the point - /// of progress of the consumer of cooked changesets also has the effect of - /// trimming obsolete cooked changesets from the Realm file (i.e., removal - /// of all changesets at indexes lower than - /// CookedProgress::intrachangeset_progress). Indeed, if this function is - /// never called, but cooked changesets are continually being produced, then - /// the Realm file will grow without bounds. - /// - /// It is an error if the specified index (CookedProgress::changeset_index) - /// is lower than the index returned by get_cooked_progress(), and if it is - /// higher that the value returned by get_num_cooked_changesets(). - /// - /// \return The snapshot number produced by the transaction performed - /// internally in set_cooked_progress(). This is also the client-side sync - /// version, and it should be passed to - /// sync::Session::nonsync_transact_notify() if a synchronization session is - /// in progress for the same file while set_cooked_progress() is - /// called. Doing so, ensures that the server will be notified about the - /// released server versions as soon as possible. - /// - /// \throw InconsistentUseOfCookedHistory If this file does not have a - /// cooked history and one can no longer be added because changesets of - /// remote origin has already been integrated. - virtual version_type set_cooked_progress(CookedProgress) = 0; - - /// \brief Get the number of cooked changesets so far produced for this - /// Realm. - /// - /// This is the same thing as is returned via \a num_changesets by - /// get_cooked_status(). - std::int_fast64_t get_num_cooked_changesets() const noexcept; - - /// \brief Returns the persisted progress that was last stored by - /// set_cooked_progress(). - /// - /// This is the same thing as is returned via \a progress by - /// get_cooked_status() when invoked with a server version of zero. - CookedProgress get_cooked_progress() const noexcept; - - /// Same as get_cooked_changeset(std::int_fast64_t, - /// util::AppendBuffer&, version_type&) but does not retreived the - /// server version. - void get_cooked_changeset(std::int_fast64_t index, util::AppendBuffer&) const; - - /// Return an upload cursor as it would be when the uploading process - /// reaches the snapshot to which the current transaction is bound. - /// - /// **CAUTION:** Must be called only while a transaction (read or write) is - /// in progress via the SharedGroup object associated with this history - /// object. - virtual UploadCursor get_upload_anchor_of_current_transact() const = 0; - - /// Return the synchronization changeset of the current transaction as it - /// would be if that transaction was committed at this time. - /// - /// The returned memory reference may be invalidated by subsequent - /// operations on the Realm state. - /// - /// **CAUTION:** Must be called only while a write transaction is in - /// progress via the SharedGroup object associated with this history object. - virtual util::StringView get_sync_changeset_of_current_transact() const noexcept = 0; - -protected: - ClientHistory(const std::string& realm_path); -}; - - -/// \brief Abstract interface for changeset cookers. -/// -/// Note, it is completely up to the application to decide what a cooked -/// changeset is. History objects (instances of ClientHistory) are required to -/// treat cooked changesets as opaque entities. For an example of a concrete -/// changeset cooker, see TrivialChangesetCooker which defines the cooked -/// changesets to be identical copies of the raw changesets. -class ClientHistory::ChangesetCooker { -public: - virtual ~ChangesetCooker() {} - - /// \brief An opportunity to produce a cooked changeset. - /// - /// When the implementation chooses to produce a cooked changeset, it must - /// write the cooked changeset to the specified buffer, and return - /// true. When the implementation chooses not to produce a cooked changeset, - /// it must return false. The implementation is allowed to write to the - /// buffer, and return false, and in that case, the written data will be - /// ignored. - /// - /// \param prior_state The state of the local Realm on which the specified - /// raw changeset is based. - /// - /// \param changeset, changeset_size The raw changeset. - /// - /// \param buffer The buffer to which the cooked changeset must be written. - /// - /// \return True if a cooked changeset was produced. Otherwise false. - virtual bool cook_changeset(const Group& prior_state, - const char* changeset, std::size_t changeset_size, - util::AppendBuffer& buffer) = 0; -}; - - -class ClientHistory::Config { -public: - Config() {} - - /// Must be set to true if, and only if the created history object - /// represents (is owned by) the sync agent of the specified Realm file. At - /// most one such instance is allowed to participate in a Realm file access - /// session at any point in time. Ordinarily the sync agent is encapsulated - /// by the sync::Client class, and the history instance representing the - /// agent is created transparently by sync::Client (one history instance per - /// sync::Session object). - bool owner_is_sync_agent = false; - - /// If a changeset cooker is specified, then the created history object will - /// allow for a cooked changeset to be produced for each changeset of remote - /// origin; that is, for each changeset that is integrated during the - /// execution of ClientHistory::integrate_remote_changesets(). If no - /// changeset cooker is specified, then no cooked changesets will be - /// produced on behalf of the created history object. - /// - /// ClientHistory::integrate_remote_changesets() will pass each incoming - /// changeset to the cooker after operational transformation; that is, when - /// the chageset is ready to be applied to the local Realm state. - std::shared_ptr changeset_cooker; -}; - -/// \brief Create a "sync history" implementation of the realm::Replication -/// interface. -/// -/// The intended role for such an object is as a plugin for new -/// realm::SharedGroup objects. -std::unique_ptr make_client_history(const std::string& realm_path, - ClientHistory::Config = {}); - - - -// Implementation - -inline timestamp_type generate_changeset_timestamp() noexcept -{ - namespace chrono = std::chrono; - // Unfortunately, C++11 does not specify what the epoch is for - // `chrono::system_clock` (or for any other clock). It is believed, however, - // that there is a de-facto standard, that the Epoch for - // `chrono::system_clock` is the Unix epoch, i.e., 1970-01-01T00:00:00Z. See - // http://stackoverflow.com/a/29800557/1698548. Additionally, it is assumed - // that leap seconds are not included in the value returned by - // time_since_epoch(), i.e., that it conforms to POSIX time. This is known - // to be true on Linux. - // - // FIXME: Investigate under which conditions OS X agrees with POSIX about - // not including leap seconds in the value returned by time_since_epoch(). - // - // FIXME: Investigate whether Microsoft Windows agrees with POSIX about - // about not including leap seconds in the value returned by - // time_since_epoch(). - auto time_since_epoch = chrono::system_clock::now().time_since_epoch(); - std::uint_fast64_t millis_since_epoch = - chrono::duration_cast(time_since_epoch).count(); - // `offset_in_millis` is the number of milliseconds between - // 1970-01-01T00:00:00Z and 2015-01-01T00:00:00Z not counting leap seconds. - std::uint_fast64_t offset_in_millis = 1420070400000ULL; - return timestamp_type(millis_since_epoch - offset_in_millis); -} - -inline void map_changeset_timestamp(timestamp_type timestamp, std::time_t& seconds_since_epoch, - long& nanoseconds) noexcept -{ - std::uint_fast64_t offset_in_millis = 1420070400000ULL; - std::uint_fast64_t millis_since_epoch = std::uint_fast64_t(offset_in_millis + timestamp); - seconds_since_epoch = std::time_t(millis_since_epoch / 1000); - nanoseconds = long(millis_since_epoch % 1000 * 1000000L); -} - -class InconsistentUseOfCookedHistory : public std::exception { -public: - InconsistentUseOfCookedHistory(const char* message) noexcept : - m_message{message} - { - } - const char* what() const noexcept override final - { - return m_message; - } -private: - const char* m_message; -}; - -class BadCookedServerVersion : public std::exception { -public: - BadCookedServerVersion(const char* message) noexcept : - m_message{message} - { - } - const char* what() const noexcept override final - { - return m_message; - } -private: - const char* m_message; -}; - -inline ClientHistoryBase::ClientHistoryBase(const std::string& realm_path) : - InstructionReplication{realm_path} // Throws -{ -} - -inline ClientHistory::ClientHistory(const std::string& realm_path) : - ClientHistoryBase{realm_path} // Throws -{ -} - -inline std::int_fast64_t ClientHistory::get_num_cooked_changesets() const noexcept -{ - version_type server_version = 0; // Skip nothing - std::int_fast64_t num_changesets = 0; - ClientHistory::CookedProgress progress; - std::int_fast64_t num_skipped_changesets = 0; - get_cooked_status(server_version, num_changesets, progress, num_skipped_changesets); - REALM_ASSERT(progress.changeset_index <= num_changesets); - REALM_ASSERT(num_skipped_changesets == 0); - return num_changesets; -} - -inline auto ClientHistory::get_cooked_progress() const noexcept -> CookedProgress -{ - version_type server_version = 0; // Skip nothing - std::int_fast64_t num_changesets = 0; - ClientHistory::CookedProgress progress; - std::int_fast64_t num_skipped_changesets = 0; - get_cooked_status(server_version, num_changesets, progress, num_skipped_changesets); - REALM_ASSERT(progress.changeset_index <= num_changesets); - REALM_ASSERT(num_skipped_changesets == 0); - return progress; -} - -inline void ClientHistory::get_cooked_changeset(std::int_fast64_t index, - util::AppendBuffer& buffer) const -{ - version_type server_version; // Dummy - get_cooked_changeset(index, buffer, server_version); // Throws -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_HISTORY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/instruction_applier.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/instruction_applier.hpp deleted file mode 100644 index 92bb573..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/instruction_applier.hpp +++ /dev/null @@ -1,147 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP -#define REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP - -#include -#include -#include -#include - - -namespace realm { -namespace sync { - -struct Changeset; - -struct InstructionApplier { - explicit InstructionApplier(Group&, TableInfoCache&) noexcept; - - /// Throws BadChangesetError if application fails due to a problem with the - /// changeset. - /// - /// FIXME: Consider using std::error_code instead of throwing - /// BadChangesetError. - void apply(const Changeset&, util::Logger*); - - void begin_apply(const Changeset&, util::Logger*) noexcept; - void end_apply() noexcept; - -protected: - StringData get_string(InternString) const; - StringData get_string(StringBufferRange) const; -#define REALM_DECLARE_INSTRUCTION_HANDLER(X) void operator()(const Instruction::X&); - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DECLARE_INSTRUCTION_HANDLER) -#undef REALM_DECLARE_INSTRUCTION_HANDLER - friend struct Instruction; // to allow visitor - - template static void apply(A& applier, const Changeset&, util::Logger*); - - // Allows for in-place modification of changeset while applying it - template static void apply(A& applier, Changeset&, util::Logger*); - - TableRef table_for_class_name(StringData) const; // Throws - REALM_NORETURN void bad_transaction_log(const char*) const; - - Group& m_group; - TableInfoCache& m_table_info_cache; - LinkViewRef m_selected_link_list; - TableRef m_selected_table; - TableRef m_selected_array; - TableRef m_link_target_table; - - template - void log(const char* fmt, Args&&... args) - { - if (m_logger) { - m_logger->trace(fmt, std::forward(args)...); // Throws - } - } - -private: - const Changeset* m_log = nullptr; - util::Logger* m_logger = nullptr; -}; - - - - -// Implementation - -inline InstructionApplier::InstructionApplier(Group& group, TableInfoCache& table_info_cache) noexcept: - m_group(group), - m_table_info_cache(table_info_cache) -{ -} - -inline void InstructionApplier::begin_apply(const Changeset& log, util::Logger* logger) noexcept -{ - m_log = &log; - m_logger = logger; -} - -inline void InstructionApplier::end_apply() noexcept -{ - m_log = nullptr; - m_logger = nullptr; - m_selected_table = TableRef{}; - m_selected_array = TableRef{}; - m_selected_link_list = LinkViewRef{}; - m_link_target_table = TableRef{}; -} - -template -inline void InstructionApplier::apply(A& applier, const Changeset& changeset, util::Logger* logger) -{ - applier.begin_apply(changeset, logger); - for (auto instr : changeset) { - if (!instr) - continue; - instr->visit(applier); // Throws -#if REALM_DEBUG - applier.m_table_info_cache.verify(); -#endif - } - applier.end_apply(); -} - -template -inline void InstructionApplier::apply(A& applier, Changeset& changeset, util::Logger* logger) -{ - applier.begin_apply(changeset, logger); - for (auto instr : changeset) { - if (!instr) - continue; - instr->visit(applier); // Throws -#if REALM_DEBUG - applier.m_table_info_cache.verify(); -#endif - } - applier.end_apply(); -} - -inline void InstructionApplier::apply(const Changeset& log, util::Logger* logger) -{ - apply(*this, log, logger); // Throws -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_IMPL_INSTRUCTION_APPLIER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/instruction_replication.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/instruction_replication.hpp deleted file mode 100644 index b66e332..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/instruction_replication.hpp +++ /dev/null @@ -1,238 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP -#define REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP - -#include -#include -#include -#include - -namespace realm { -namespace sync { - - -class InstructionReplication: public TrivialReplication, public ObjectIDProvider { -public: - enum class TableBehavior { - Class, - Array, - Ignore - }; - - explicit InstructionReplication(const std::string& realm_path); - void set_short_circuit(bool) noexcept; - bool is_short_circuited() const noexcept; - - // reset() resets the encoder, the selected tables and the cache. It is - // called by do_initiate_transact(), but can be called at the other times - // as well. - virtual void reset(); - - ChangesetEncoder& get_instruction_encoder() noexcept; - const ChangesetEncoder& get_instruction_encoder() const noexcept; - - //@{ - /// Generate instructions for Object Store tables. These must be called - /// prior to calling the equivalent functions in Core's API. When creating a - /// class-like table, `add_class()` must be called prior to - /// `Group::insert_group_level_table()`. Similarly, `create_object()` or - /// `create_object_with_primary_key()` must be called prior to - /// `Table::insert_empty_row()` and/or `Table::set_int_unique()` or - /// `Table::set_string_unique()` or `Table::set_null_unique()`. - /// - /// If a class-like table is added, or an object-like row is inserted, - /// without calling these methods first, an exception will be thrown. - /// - /// A "class-like table" is defined as a table whose name begins with - /// "class_" (this is the convention used by Object Store). Non-class-like - /// tables can be created and modified using Core's API without calling - /// these functions, because they do not result in instructions being - /// emitted. - void add_class(StringData table_name); - void add_class_with_primary_key(StringData table_name, DataType pk_type, StringData pk_field, bool nullable); - void create_object(const Table*, ObjectID); - void create_object_with_primary_key(const Table*, ObjectID, StringData); - void create_object_with_primary_key(const Table*, ObjectID, int_fast64_t); - void create_object_with_primary_key(const Table*, ObjectID, realm::util::None); - void prepare_erase_table(StringData table_name); - //@} - - // TrivialReplication interface: - void initialize(SharedGroup&) override; - - // TransactLogConvenientEncoder interface: - void insert_group_level_table(size_t table_ndx, size_t num_tables, StringData name) override; - void erase_group_level_table(size_t table_ndx, size_t num_tables) override; - void rename_group_level_table(size_t table_ndx, StringData new_name) override; - void insert_column(const Descriptor&, size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link, - bool nullable = false) override; - void erase_column(const Descriptor&, size_t col_ndx) override; - void rename_column(const Descriptor&, size_t col_ndx, StringData name) override; - - void set_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value, _impl::Instruction variant) override; - void add_int(const Table*, size_t col_ndx, size_t ndx, int_fast64_t value) override; - void set_bool(const Table*, size_t col_ndx, size_t ndx, bool value, _impl::Instruction variant) override; - void set_float(const Table*, size_t col_ndx, size_t ndx, float value, _impl::Instruction variant) override; - void set_double(const Table*, size_t col_ndx, size_t ndx, double value, _impl::Instruction variant) override; - void set_string(const Table*, size_t col_ndx, size_t ndx, StringData value, _impl::Instruction variant) override; - void set_binary(const Table*, size_t col_ndx, size_t ndx, BinaryData value, _impl::Instruction variant) override; - void set_olddatetime(const Table*, size_t col_ndx, size_t ndx, OldDateTime value, - _impl::Instruction variant) override; - void set_timestamp(const Table*, size_t col_ndx, size_t ndx, Timestamp value, _impl::Instruction variant) override; - void set_table(const Table*, size_t col_ndx, size_t ndx, _impl::Instruction variant) override; - void set_mixed(const Table*, size_t col_ndx, size_t ndx, const Mixed& value, _impl::Instruction variant) override; - void set_link(const Table*, size_t col_ndx, size_t ndx, size_t value, _impl::Instruction variant) override; - void set_null(const Table*, size_t col_ndx, size_t ndx, _impl::Instruction variant) override; - void set_link_list(const LinkView&, const IntegerColumn& values) override; - void insert_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, StringData) override; - void erase_substring(const Table*, size_t col_ndx, size_t row_ndx, size_t pos, size_t size) override; - void insert_empty_rows(const Table*, size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows) override; - void add_row_with_key(const Table*, size_t row_ndx, size_t prior_num_rows, size_t key_col_ndx, int64_t key) override; - void erase_rows(const Table*, size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rowsp, - bool is_move_last_over) override; - void swap_rows(const Table*, size_t row_ndx_1, size_t row_ndx_2) override; - void move_row(const Table*, size_t row_ndx_1, size_t row_ndx_2) override; - void merge_rows(const Table*, size_t row_ndx, size_t new_row_ndx) override; - void add_search_index(const Descriptor&, size_t col_ndx) override; - void remove_search_index(const Descriptor&, size_t col_ndx) override; - void set_link_type(const Table*, size_t col_ndx, LinkType) override; - void clear_table(const Table*, size_t prior_num_rows) override; - void optimize_table(const Table*) override; - void link_list_set(const LinkView&, size_t ndx, size_t value) override; - void link_list_insert(const LinkView&, size_t ndx, size_t value) override; - void link_list_move(const LinkView&, size_t from_ndx, size_t to_ndx) override; - void link_list_swap(const LinkView&, size_t ndx_1, size_t ndx_2) override; - void link_list_erase(const LinkView&, size_t ndx) override; - void link_list_clear(const LinkView&) override; - void nullify_link(const Table*, size_t col_ndx, size_t ndx) override; - void link_list_nullify(const LinkView&, size_t ndx) override; - - template - void emit(T instruction); - - TableBehavior select_table(const Table*); - const Table* selected_table() const noexcept; - -protected: - // Replication interface: - void do_initiate_transact(TransactionType, version_type current_version) override; -private: - bool m_short_circuit = false; - - ChangesetEncoder m_encoder; - SharedGroup* m_sg = nullptr; - std::unique_ptr m_cache; - - - // FIXME: The base class already caches this. - ConstTableRef m_selected_table; - TableBehavior m_selected_table_behavior; // cache - ConstLinkViewRef m_selected_link_list = nullptr; - - // Consistency checks: - std::string m_table_being_created; - std::string m_table_being_created_primary_key; - std::string m_table_being_erased; - util::Optional m_object_being_created; - - REALM_NORETURN void unsupported_instruction(); // Throws TransformError - TableBehavior select_table(const Descriptor&); - TableBehavior select_table_inner(const Table* table); - bool select_link_list(const LinkView&); // returns true if table behavior != ignored - - TableBehavior get_table_behavior(const Table*) const; - - template - void set(const Table*, size_t row_ndx, size_t col_ndx, T payload, - _impl::Instruction variant); - template - void set_pk(const Table*, size_t row_ndx, size_t col_ndx, T payload, - _impl::Instruction variant); - template - auto as_payload(T value); -}; - -inline void InstructionReplication::set_short_circuit(bool b) noexcept -{ - m_short_circuit = b; -} - -inline bool InstructionReplication::is_short_circuited() const noexcept -{ - return m_short_circuit; -} - -inline ChangesetEncoder& InstructionReplication::get_instruction_encoder() noexcept -{ - return m_encoder; -} - -inline const ChangesetEncoder& InstructionReplication::get_instruction_encoder() const noexcept -{ - return m_encoder; -} - -template -inline void InstructionReplication::emit(T instruction) -{ - REALM_ASSERT(!m_short_circuit); - m_encoder(instruction); -} - -inline auto InstructionReplication::select_table(const Table* table) -> TableBehavior -{ - if (m_selected_table == table) { - return m_selected_table_behavior; - } - return select_table_inner(table); -} - -inline const Table* InstructionReplication::selected_table() const noexcept -{ - return m_selected_table.get(); -} - -// Temporarily short-circuit replication -class TempShortCircuitReplication { -public: - TempShortCircuitReplication(InstructionReplication& bridge): m_bridge(bridge) - { - m_was_short_circuited = bridge.is_short_circuited(); - bridge.set_short_circuit(true); - } - - ~TempShortCircuitReplication() - { - m_bridge.set_short_circuit(m_was_short_circuited); - } - - bool was_short_circuited() const noexcept - { - return m_was_short_circuited; - } -private: - InstructionReplication& m_bridge; - bool m_was_short_circuited; -}; - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_IMPL_INSTRUCTION_REPLICATION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/instructions.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/instructions.hpp deleted file mode 100644 index 4c8051a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/instructions.hpp +++ /dev/null @@ -1,421 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_IMPL_INSTRUCTIONS_HPP -#define REALM_IMPL_INSTRUCTIONS_HPP - -#include -#include -#include // string conversion, debug prints -#include // shared_ptr -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { -namespace sync { - -// CAUTION: Any change to the order or number of instructions is a -// protocol-breaking change! -#define REALM_FOR_EACH_INSTRUCTION_TYPE(X) \ - X(SelectTable) \ - X(SelectField) \ - X(AddTable) \ - X(EraseTable) \ - X(CreateObject) \ - X(EraseObject) \ - X(Set) \ - X(AddInteger) \ - X(InsertSubstring) \ - X(EraseSubstring) \ - X(ClearTable) \ - X(AddColumn) \ - X(EraseColumn) \ - X(ArraySet) \ - X(ArrayInsert) \ - X(ArrayMove) \ - X(ArraySwap) \ - X(ArrayErase) \ - X(ArrayClear) \ - - -enum class ContainerType { - None = 0, - Reserved0 = 1, - Array = 2, - Set = 3, - Dictionary = 4, -}; - -struct Instruction { - // Base classes for instructions with common fields. They enable the merge - // algorithm to reuse some code without resorting to templates, and can be - // combined to allow optimal memory layout of instructions (size <= 64). - struct PayloadInstructionBase; - struct ObjectInstructionBase; - struct FieldInstructionBase; - -#define REALM_DECLARE_INSTRUCTION_STRUCT(X) struct X; - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DECLARE_INSTRUCTION_STRUCT) -#undef REALM_DECLARE_INSTRUCTION_STRUCT - - enum class Type: uint8_t { -#define REALM_DEFINE_INSTRUCTION_TYPE(X) X, - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_TYPE) -#undef REALM_DEFINE_INSTRUCTION_TYPE - }; - - struct Payload; - template struct GetType; - template struct GetInstructionType; - - Instruction() {} - template Instruction(T instr); - - static const size_t max_instruction_size = 64; - std::aligned_storage_t m_storage; - Type type; - - template auto visit(F&& lambda); - template auto visit(F&& lambda) const; - - template T& get_as() - { - REALM_ASSERT(type == GetInstructionType::value); - return *reinterpret_cast(&m_storage); - } - - template const T& get_as() const - { - return const_cast(this)->template get_as(); - } - - bool operator==(const Instruction& other) const noexcept; - - bool operator!=(const Instruction& other) const noexcept - { - return !(*this == other); - } -}; - -// 0x3f is the largest value that fits in a single byte in the variable-length -// encoded integer instruction format. -static constexpr uint8_t InstrTypeInternString = 0x3f; - -// This instruction code is only ever used internally by the Changeset class -// to allow insertion/removal while keeping iterators stable. Should never -// make it onto the wire. -static constexpr uint8_t InstrTypeMultiInstruction = 0xff; - -struct StringBufferRange { - uint32_t offset, size; -}; - -struct InternString { - static const InternString npos; - explicit constexpr InternString(uint32_t v = uint32_t(-1)) noexcept : value(v) {} - - uint32_t value; - - bool operator==(const InternString& other) const noexcept { return value == other.value; } - bool operator<(const InternString& other) const noexcept { return value < other.value; } - - explicit operator bool() const noexcept { return (value != npos.value); } -}; - -struct Instruction::Payload { - struct Link { - sync::ObjectID target; // can be nothing = null - InternString target_table; - }; - - union Data { - bool boolean; - int64_t integer; - float fnum; - double dnum; - StringBufferRange str; - Timestamp timestamp; - Link link; - - Data() noexcept {} - Data(const Data&) noexcept = default; - Data& operator=(const Data&) noexcept = default; - }; - Data data; - int8_t type; // -1 = null, -2 = implicit_nullify - - Payload(): Payload(realm::util::none) {} - explicit Payload(bool value) noexcept: type(type_Bool) { data.boolean = value; } - explicit Payload(int64_t value) noexcept: type(type_Int) { data.integer = value; } - explicit Payload(float value) noexcept: type(type_Float) { data.fnum = value; } - explicit Payload(double value) noexcept: type(type_Double) { data.dnum = value; } - explicit Payload(Link value) noexcept: type(type_Link) { data.link = value; } - explicit Payload(StringBufferRange value) noexcept: type(type_String) { data.str = value; } - explicit Payload(realm::util::None, bool implicit_null = false) noexcept { - type = (implicit_null ? -2 : -1); - } - explicit Payload(Timestamp value) noexcept: type(value.is_null() ? -1 : type_Timestamp) - { - data.timestamp = value; - } - - Payload(const Payload&) noexcept = default; - Payload& operator=(const Payload&) noexcept = default; - - bool is_null() const; - bool is_implicit_null() const; -}; - -struct Instruction::ObjectInstructionBase { - sync::ObjectID object; -}; - -struct Instruction::FieldInstructionBase - : Instruction::ObjectInstructionBase -{ - InternString field; -}; - -struct Instruction::PayloadInstructionBase { - Payload payload; -}; - - -struct Instruction::SelectTable { - InternString table; -}; - -struct Instruction::SelectField - : Instruction::FieldInstructionBase -{ - InternString link_target_table; -}; - -struct Instruction::AddTable { - InternString table; - InternString primary_key_field; - DataType primary_key_type; - bool has_primary_key; - bool primary_key_nullable; -}; - -struct Instruction::EraseTable { - InternString table; -}; - -struct Instruction::CreateObject - : Instruction::PayloadInstructionBase - , Instruction::ObjectInstructionBase -{ - bool has_primary_key; -}; - -struct Instruction::EraseObject - : Instruction::ObjectInstructionBase -{}; - -struct Instruction::Set - : Instruction::PayloadInstructionBase - , Instruction::FieldInstructionBase -{ - bool is_default; -}; - -struct Instruction::AddInteger - : Instruction::FieldInstructionBase -{ - int64_t value; -}; - -struct Instruction::InsertSubstring - : Instruction::FieldInstructionBase -{ - StringBufferRange value; - uint32_t pos; -}; - -struct Instruction::EraseSubstring - : Instruction::FieldInstructionBase -{ - uint32_t pos; - uint32_t size; -}; - -struct Instruction::ClearTable { -}; - -struct Instruction::ArraySet { - Instruction::Payload payload; - uint32_t ndx; - uint32_t prior_size; -}; - -struct Instruction::ArrayInsert { - // payload carries the value in case of LinkList - // payload is empty in case of Array, Dict or any other container type - Instruction::Payload payload; - uint32_t ndx; - uint32_t prior_size; -}; - -struct Instruction::ArrayMove { - uint32_t ndx_1; - uint32_t ndx_2; -}; - -struct Instruction::ArrayErase { - uint32_t ndx; - uint32_t prior_size; - bool implicit_nullify; -}; - -struct Instruction::ArraySwap { - uint32_t ndx_1; - uint32_t ndx_2; -}; - -struct Instruction::ArrayClear { - uint32_t prior_size; -}; - - -// If container_type != ContainerType::none, creates a subtable: -// +---+---+-------+ -// | a | b | c | -// +---+---+-------+ -// | | | +---+ | -// | | | | v | | -// | | | +---+ | -// | 1 | 2 | | 3 | | -// | | | | 4 | | -// | | | | 5 | | -// | | | +---+ | -// +---+---+-------+ -struct Instruction::AddColumn { - InternString field; - InternString link_target_table; - DataType type; - ContainerType container_type; - bool nullable; -}; - -struct Instruction::EraseColumn { - InternString field; -}; - -struct InstructionHandler { - /// Notify the handler that an InternString meta-instruction was found. - virtual void set_intern_string(uint32_t index, StringBufferRange) = 0; - - /// Notify the handler of the string value. The handler guarantees that the - /// returned string range is valid at least until the next invocation of - /// add_string_range(). - /// - /// Instances of `StringBufferRange` passed to operator() after invoking - /// this function are assumed to refer to ranges in this buffer. - virtual StringBufferRange add_string_range(StringData) = 0; - - /// Handle an instruction. - virtual void operator()(const Instruction&) = 0; -}; - - -/// Implementation: - -#define REALM_DEFINE_INSTRUCTION_GET_TYPE(X) \ - template <> struct Instruction::GetType { using Type = Instruction::X; }; \ - template <> struct Instruction::GetInstructionType { static const Instruction::Type value = Instruction::Type::X; }; - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_DEFINE_INSTRUCTION_GET_TYPE) -#undef REALM_DEFINE_INSTRUCTION_GET_TYPE - -template -Instruction::Instruction(T instr) : type(GetInstructionType::value) -{ - new(&m_storage) T(std::move(instr)); -} - -template -inline auto Instruction::visit(F&& lambda) -{ - switch (type) { -#define REALM_VISIT_INSTRUCTION(X) \ - case Type::X: \ - return lambda(get_as()); - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_VISIT_INSTRUCTION) -#undef REALM_VISIT_INSTRUCTION - } - REALM_UNREACHABLE(); -} - -template -inline auto Instruction::visit(F&& lambda) const -{ - switch (type) { -#define REALM_VISIT_INSTRUCTION(X) \ - case Type::X: \ - return lambda(get_as()); - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_VISIT_INSTRUCTION) -#undef REALM_VISIT_INSTRUCTION - } - REALM_UNREACHABLE(); -} - -inline bool Instruction::operator==(const Instruction& other) const noexcept -{ - if (type != other.type) - return false; - size_t valid_size; - switch (type) { -#define REALM_COMPARE_INSTRUCTION(X) \ - case Type::X: valid_size = sizeof(Instruction::X); break; - REALM_FOR_EACH_INSTRUCTION_TYPE(REALM_COMPARE_INSTRUCTION) -#undef REALM_COMPARE_INSTRUCTION - default: REALM_UNREACHABLE(); - } - - // This relies on all instruction types being PODs to work. - return std::memcmp(&m_storage, &other.m_storage, valid_size) == 0; -} - -inline bool Instruction::Payload::is_null() const -{ - return type < 0; -} - -inline bool Instruction::Payload::is_implicit_null() const -{ - return type == -2; -} - -std::ostream& operator<<(std::ostream&, Instruction::Type); - -} // namespace _impl -} // namespace realm - -#endif // REALM_IMPL_INSTRUCTIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/object.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/object.hpp deleted file mode 100644 index 8529fa0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/object.hpp +++ /dev/null @@ -1,262 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_SYNC_OBJECT_HPP -#define REALM_SYNC_OBJECT_HPP - -#include -#include -#include -#include - -#include - -#include - -/// This file presents a convenience API for making changes to a Realm file that -/// adhere to the conventions of assigning stable IDs to every object. - -namespace realm { - -class Group; -class ReadTransaction; -class WriteTransaction; - -namespace sync { - -class SyncHistory; - -extern const char object_id_column_name[]; // "!OID" -extern const char array_value_column_name[]; // "!ARRAY_VALUE" - -struct TableInfoCache; - -/// Determine whether the Group has a sync-type history, and therefore whether -/// it supports globally stable object IDs. -/// -/// The Group does not need to be in a transaction. -bool has_object_ids(const Group&); - -/// Determine whether object IDs for objects without primary keys are globally -/// stable. This is true if and only if the Group has been in touch with the -/// server (or is the server), and will remain true forever thereafter. -/// -/// It is an error to call this function for groups that do not have object IDs -/// (i.e. where `has_object_ids()` returns false). -/// -/// The Group is assumed to be in a read transaction. -bool is_object_id_stability_achieved(const Group&); - -/// Create a table with an object ID column. -/// -/// It is an error to add tables to Groups with a sync history type directly. -/// This function or related functions must be used instead. -/// -/// The resulting table will be born with 1 column, which is a column used -/// in the maintenance of object IDs. -/// -/// NOTE: The table name must begin with the prefix "class_" in accordance with -/// Object Store conventions. -/// -/// The Group must be in a write transaction. -TableRef create_table(Group&, StringData name); - -/// Create a table with an object ID column and a primary key column. -/// -/// It is an error to add tables to Groups with a sync history type directly. -/// This function or related functions must be used instead. -/// -/// The resulting table will be born with 2 columns, which is a column used -/// in the maintenance of object IDs and the requested primary key column. -/// The primary key column must have either integer or string type, and it -/// will be given the name provided in the argument \a pk_column_name. -/// -/// The 'pk' metadata table is updated with information about the primary key -/// column. If the 'pk' table does not yet exist, it is created. -/// -/// Please note: The 'pk' metadata table will not be synchronized directly, -/// so subsequent updates to it will be lost (as they constitute schema-breaking -/// changes). -/// -/// NOTE: The table name must begin with the prefix "class_" in accordance with -/// Object Store conventions. -/// -/// The Group must be in a write transaction. -TableRef create_table_with_primary_key(Group&, StringData name, DataType pk_type, - StringData pk_column_name, bool nullable = false); - - -//@{ -/// Erase table and update metadata. -/// -/// It is an error to erase tables via the Group API, because it does not -/// correctly update metadata tables (such as the `pk` table). -void erase_table(Group& g, TableInfoCache& table_info_cache, StringData name); -void erase_table(Group& g, TableInfoCache& table_info_cache, TableRef); -//@} - -/// Create an array column with the specified element type. -/// -/// The result will be a column of type type_Table with one subcolumn named -/// "!ARRAY_VALUE" of the specified element type and nullability. -/// -/// Return the column index of the inserted array column. -size_t add_array_column(Table&, DataType element_type, StringData column_name, bool is_nullable = false); - - -//@{ -/// Calculate the object ID from the argument, where the argument is a primary -/// key value. -ObjectID object_id_for_primary_key(StringData); -ObjectID object_id_for_primary_key(util::Optional); -//@} - -/// Determine whether it is safe to call `object_id_for_row()` on tables without -/// primary keys. If the table has a primary key, always returns true. -bool has_globally_stable_object_ids(const Table&); - -bool table_has_primary_key(const TableInfoCache&, const Table&); - -/// Get the globally unique object ID for the row. -/// -/// If the table has a primary key, this is guaranteed to succeed. Otherwise, if -/// the server has not been contacted yet (`has_globally_stable_object_ids()` -/// returns false), an exception is thrown. -ObjectID object_id_for_row(const TableInfoCache&, const Table&, size_t); - -/// Get the index of the row with the object ID. -/// -/// \returns realm::npos if the object does not exist in the table. -size_t row_for_object_id(const TableInfoCache&, const Table&, ObjectID); - -//@{ -/// Add a row to the table and populate the object ID with an appropriate value. -/// -/// In the variant which takes an ObjectID parameter, a check is performed to see -/// if the object already exists. If it does, the row index of the existing object -/// is returned. -/// -/// If the table has a primary key column, an exception is thrown. -/// -/// \returns the row index of the object. -size_t create_object(const TableInfoCache&, Table&); -size_t create_object(const TableInfoCache&, Table&, ObjectID); -//@} - -//@{ -/// Create an object with a primary key value and populate the object ID with an -/// appropriate value. -/// -/// If the table does not have a primary key column (as indicated by the Object -/// Store's metadata in the special "pk" table), or the type of the primary key -/// column does not match the argument provided, an exception is thrown. -/// -/// The primary key column's value is populated with the appropriate -/// `set_int_unique()`, `set_string_unique()`, or `set_null_unique()` method -/// called on \a table. -/// -/// If an object with the given primary key value already exists, its row number -/// is returned without creating any new objects. -/// -/// These are convenience functions, equivalent to the following: -/// - Add an empty row to the table. -/// - Obtain an `ObjectID` with `object_id_for_primary_key()`. -/// - Obtain a local object ID with `global_to_local_object_id()`. -/// - Store the local object ID in the object ID column. -/// - Call `set_int_unique()`,`set_string_unique()`, or `set_null_unique()` -/// to set the primary key value. -/// -/// \returns the row index of the created object. -size_t create_object_with_primary_key(const TableInfoCache&, Table&, util::Optional primary_key); -size_t create_object_with_primary_key(const TableInfoCache&, Table&, StringData primary_key); -//@} - -struct TableInfoCache { - const Group& m_group; - - explicit TableInfoCache(const ReadTransaction&); - explicit TableInfoCache(const WriteTransaction&); - - // Implicit conversion deliberately allowed for the purpose of calling the above - // functions without constructing a cache manually. - TableInfoCache(const Group&); - TableInfoCache(TableInfoCache&&) noexcept = default; - - struct TableInfo { - struct VTable; - - StringData name; - const VTable* vtable; - size_t object_id_index = size_t(-1); - size_t primary_key_index; - DataType primary_key_type = DataType(-1); - bool primary_key_nullable = false; - mutable size_t last_row_index = size_t(-1); - mutable ObjectID last_object_id; - - void clear_last_object() const - { - last_row_index = size_t(-1); - last_object_id = {}; - } - }; - - mutable std::vector> m_table_info; - - const TableInfo& get_table_info(const Table&) const; - const TableInfo& get_table_info(size_t table_index) const; - void clear(); - void clear_last_object(const Table&); - void verify(); -}; - - -/// Migrate a server-side Realm file whose history type is -/// `Replication::hist_SyncServer` and whose history schema version is 0 (i.e., -/// Realm files without stable identifiers). -void import_from_legacy_format(const Group& old_group, Group& new_group, util::Logger&); - -using TableNameBuffer = std::array; -StringData table_name_to_class_name(StringData); -StringData class_name_to_table_name(StringData, TableNameBuffer&); - - -// Implementation: - -inline StringData table_name_to_class_name(StringData table_name) -{ - REALM_ASSERT(table_name.begins_with("class_")); - return table_name.substr(6); -} - - -inline StringData class_name_to_table_name(StringData class_name, TableNameBuffer& buffer) -{ - constexpr const char class_prefix[] = "class_"; - constexpr size_t class_prefix_len = sizeof(class_prefix) - 1; - char* p = std::copy_n(class_prefix, class_prefix_len, buffer.data()); - size_t len = std::min(class_name.size(), buffer.size() - class_prefix_len); - std::copy_n(class_name.data(), len, p); - return StringData(buffer.data(), class_prefix_len + len); -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_OBJECT_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/object_id.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/object_id.hpp deleted file mode 100644 index e3e96e0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/object_id.hpp +++ /dev/null @@ -1,312 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_SYNC_OBJECT_ID_HPP -#define REALM_SYNC_OBJECT_ID_HPP - -#include // std::hash -#include -#include // operator<< -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -// Only set this to one when testing the code paths that exercise object ID -// hash collisions. It artificially limits the "optimistic" local ID to use -// only the lower 15 bits of the ID rather than the lower 63 bits, making it -// feasible to generate collisions within reasonable time. -#define REALM_EXERCISE_OBJECT_ID_COLLISION 0 - -namespace realm { - -class Group; - -namespace sync { - -/// ObjectIDs are globally unique for a given class (table), and up to 128 bits -/// wide. They are represented as two 64-bit integers, each of which may -/// frequently be small, for best on-wire compressibility. -struct ObjectID { - constexpr ObjectID(uint64_t hi, uint64_t lo); - static ObjectID from_string(StringData); - static bool from_string(StringData, ObjectID&) noexcept; - - // FIXME: Remove "empty" ObjectIDs, wrap in Optional instead. - constexpr ObjectID(realm::util::None = realm::util::none); - constexpr ObjectID(const ObjectID&) noexcept = default; - ObjectID& operator=(const ObjectID&) noexcept = default; - - constexpr uint64_t lo() const { return m_lo; } - constexpr uint64_t hi() const { return m_hi; } - - std::string to_string() const; - - constexpr bool operator<(const ObjectID& other) const; - constexpr bool operator==(const ObjectID& other) const; - constexpr bool operator!=(const ObjectID& other) const; - - explicit constexpr operator bool() const noexcept; - -private: - uint64_t m_lo; - uint64_t m_hi; -}; - -/// Implementors of this interface should define a way to map from 128-bit -/// on-write ObjectIDs to local 64-bit object IDs. -/// -/// The three object ID types are: -/// a. Object IDs for objects in tables without primary keys. -/// b. Object IDs for objects in tables with integer primary keys. -/// c. Object IDs for objects in tables with other primary key types. -/// -/// For integer primary keys (b), the Object ID is just the integer value. -/// -/// For objects without primary keys (a), a "squeezed" tuple of the -/// client_file_ident and a peer-local sequence number is used as the local -/// Object ID. The on-write Object ID is the "unsqueezed" format. The methods on -/// this interface ending in "_squeezed" aid in the creation and conversion of -/// these IDs. -/// -/// For objects with other types of primary keys (c), the ObjectID -/// is a 128-bit hash of the primary key value. However, the local object ID -/// must be a 64-bit integer, because that is the maximum size integer that -/// Realm is able to store. The solution is to optimistically use the lower 63 -/// bits of the on-wire Object ID, and use a local ID with the upper 64th bit -/// set when there is a collision in the lower 63 bits between two different -/// hash values. -class ObjectIDProvider { -public: - using LocalObjectID = int_fast64_t; - - /// Calculate optimistic local ID that may collide with others. It is up to - /// the caller to ensure that collisions are detected and that - /// allocate_local_id_after_collision() is called to obtain a non-colliding - /// ID. - static LocalObjectID get_optimistic_local_id_hashed(ObjectID global_id); - - /// Find the local 64-bit object ID for the provided global 128-bit ID. - virtual LocalObjectID global_to_local_object_id_hashed(size_t table_ndx, ObjectID global_id) const = 0; - - /// After a local ID collision has been detected, this function may be - /// called to obtain a non-colliding local ID in such a way that subsequence - /// calls to global_to_local_object_id() will return the correct local ID - /// for both \a incoming_id and \a colliding_id. - virtual LocalObjectID allocate_local_id_after_hash_collision(size_t table_ndx, - ObjectID incoming_id, - ObjectID colliding_id, - LocalObjectID colliding_local_id) = 0; - static LocalObjectID make_tagged_local_id_after_hash_collision(uint64_t sequence_number); - virtual void free_local_id_after_hash_collision(size_t table_ndx, ObjectID object_id) = 0; - - /// Some Object IDs are generated as a tuple of the client_file_ident and a - /// local sequence number. This function takes the next number in the - /// sequence for the given table and returns an appropriate globally unique - /// ObjectID. - virtual ObjectID allocate_object_id_squeezed(size_t table_ndx) = 0; - static LocalObjectID global_to_local_object_id_squeezed(ObjectID); - static ObjectID local_to_global_object_id_squeezed(LocalObjectID); - - virtual void table_erased(size_t table_ndx) = 0; - - virtual int_fast64_t get_client_file_ident() const = 0; -}; - -// ObjectIDSet is a set of (table name, object id) -class ObjectIDSet { -public: - - void insert(StringData table, ObjectID object_id); - void erase(StringData table, ObjectID object_id); - bool contains(StringData table, ObjectID object_id) const noexcept; - bool empty() const noexcept; - - // A map from table name to a set of object ids. - util::metered::map> m_objects; -}; - -// FieldSet is a set of fields in tables. A field is defined by a -// table name, a column in the table and an object id for the row. -class FieldSet { -public: - - void insert(StringData table, StringData column, ObjectID object_id); - void erase(StringData table, StringData column, ObjectID object_id); - bool contains(StringData table, ObjectID object_id) const noexcept; - bool contains(StringData table, StringData column, ObjectID object_id) const noexcept; - bool empty() const noexcept; - - // A map from table name to a map from column name to a set of - // object ids. - util::metered::map< - std::string, - util::metered::map> - > m_fields; -}; - -struct GlobalID { - StringData table_name; - ObjectID object_id; - - bool operator==(const GlobalID& other) const; - bool operator!=(const GlobalID& other) const; - bool operator<(const GlobalID& other) const; -}; - - - - -/// Implementation - -constexpr ObjectID::ObjectID(uint64_t hi, uint64_t lo) : m_lo(lo), m_hi(hi) -{ -} - -constexpr ObjectID::ObjectID(realm::util::None) : m_lo(-1), m_hi(-1) -{ -} - -constexpr bool ObjectID::operator<(const ObjectID& other) const -{ - return (m_hi == other.m_hi) ? (m_lo < other.m_lo) : (m_hi < other.m_hi); -} - -constexpr bool ObjectID::operator==(const ObjectID& other) const -{ - return m_hi == other.m_hi && m_lo == other.m_lo; -} - -constexpr bool ObjectID::operator!=(const ObjectID& other) const -{ - return !(*this == other); -} - -constexpr ObjectID::operator bool() const noexcept -{ - return (*this != ObjectID{}); -} - -inline bool GlobalID::operator==(const GlobalID& other) const -{ - return object_id == other.object_id && table_name == other.table_name; -} - -inline bool GlobalID::operator!=(const GlobalID& other) const -{ - return !(*this == other); -} - -inline bool GlobalID::operator<(const GlobalID& other) const -{ - if (table_name == other.table_name) - return object_id < other.object_id; - return table_name < other.table_name; -} - - -std::ostream& operator<<(std::ostream&, const realm::sync::ObjectID&); -std::istream& operator>>(std::istream&, realm::sync::ObjectID&); - -inline ObjectIDProvider::LocalObjectID -ObjectIDProvider::get_optimistic_local_id_hashed(ObjectID global_id) -{ -#if REALM_EXERCISE_OBJECT_ID_COLLISION - const uint64_t optimistic_mask = 0xff; -#else - const uint64_t optimistic_mask = 0x7fffffffffffffff; -#endif - static_assert(optimistic_mask < 0x8000000000000000, "optimistic Object ID mask must leave the 64th bit zero"); - return global_id.lo() & optimistic_mask; -} - -inline ObjectIDProvider::LocalObjectID -ObjectIDProvider::make_tagged_local_id_after_hash_collision(uint64_t sequence_number) -{ - REALM_ASSERT(sequence_number < 0x8000000000000000); - return 0x8000000000000000 | sequence_number; -} - -inline ObjectIDProvider::LocalObjectID -ObjectIDProvider::global_to_local_object_id_squeezed(ObjectID object_id) -{ - REALM_ASSERT(object_id.hi() <= std::numeric_limits::max()); - REALM_ASSERT(object_id.lo() <= std::numeric_limits::max()); - - uint64_t a = object_id.lo() & 0xff; - uint64_t b = (object_id.hi() & 0xff) << 8; - uint64_t c = (object_id.lo() & 0xffffff00) << 8; - uint64_t d = (object_id.hi() & 0xffffff00) << 32; - union { - uint64_t u; - int64_t s; - } bitcast; - bitcast.u = a | b | c | d; - return bitcast.s; -} - -inline ObjectID -ObjectIDProvider::local_to_global_object_id_squeezed(LocalObjectID squeezed) -{ - union { - uint64_t u; - int64_t s; - } bitcast; - bitcast.s = squeezed; - - uint64_t u = bitcast.u; - - uint64_t lo = (u & 0xff) | ((u & 0xffffff0000) >> 8); - uint64_t hi = ((u & 0xff00) >> 8) | ((u & 0xffffff0000000000) >> 32); - return ObjectID{hi, lo}; -} - -inline bool ObjectIDSet::empty() const noexcept -{ - return m_objects.empty(); -} - -inline bool FieldSet::empty() const noexcept -{ - return m_fields.empty(); -} - -} // namespace sync -} // namespace realm - -namespace std { - -template <> -struct hash { - size_t operator()(realm::sync::ObjectID oid) const - { - return std::hash{}(oid.lo()) ^ std::hash{}(oid.hi()); - } -}; - -} // namespace std - -#endif // REALM_SYNC_OBJECT_ID_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/permissions.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/permissions.hpp deleted file mode 100644 index 073f2d6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/permissions.hpp +++ /dev/null @@ -1,446 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_PERMISSIONS_HPP -#define REALM_SYNC_PERMISSIONS_HPP - -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace realm { -namespace sync { - -/// Permissions Schema: -/// -/// class___Role: -/// string name PRIMARY_KEY; -/// User[] members; -/// -/// class___Permission: -/// __Role role; -/// bool canRead; -/// bool canUpdate; -/// bool canDelete; -/// bool canSetPermissions; -/// bool canQuery; -/// bool canCreate; -/// bool canModifySchema; -/// -/// class___Realm: -/// int id PRIMARY_KEY = 0; // singleton object -/// __Permission[] permissions; -/// -/// class___User: -/// string id PRIMARY_KEY; -/// __Role role; -/// -/// class___Class: -/// string name PRIMARY_KEY; -/// __Permission[] permissions; -/// -/// class_: -/// __Permission[] ; -/// __Role ; -/// - -static constexpr char g_roles_table_name[] = "class___Role"; -static constexpr char g_permissions_table_name[] = "class___Permission"; -static constexpr char g_users_table_name[] = "class___User"; -static constexpr char g_classes_table_name[] = "class___Class"; -static constexpr char g_realms_table_name[] = "class___Realm"; - - -/// Create the permissions schema if it doesn't already exist. -void create_permissions_schema(Group&); - -/// Set up the basic "everyone" role and default permissions. The default is to -/// set up some very permissive defaults, where "everyone" can do everything. -void set_up_basic_permissions(Group& group, TableInfoCache& table_info_cache, bool permissive = true); -// Convenience function that creates a new TableInfoCache. -void set_up_basic_permissions(Group& group, bool permissive = true); - -/// Set up some basic permissions for the class. The default is to set up some -/// very permissive default, where "everyone" can do everything in the class. -void set_up_basic_permissions_for_class(Group&, StringData class_name, bool permissive = true); -// void set_up_basic_default_permissions_for_class(Group&, TableRef klass, bool permissive = true); - -/// Return the index of the ACL in the class, if one exists. If no ACL column is -/// defined in the class, returns `npos`. -size_t find_permissions_column(const Group&, ConstTableRef); - -//@{ -/// Convenience functions to check permisions data -/// The functions must be called inside a read (or write) transaction. -bool permissions_schema_exist(const Group&); - -bool user_exist(const Group&, StringData user_id); -//@} - - -/// Perform a query as user \a user_id, returning only the results that the -/// user has access to read. If the user is an admin, there is no need to call -/// this function, since admins can always read everything. -/// -/// If the target table of the query does not have object-level permissions, -/// the query results will be returned without any additional filtering. -/// -/// If the target table of the query has object-level permissions, but the -/// permissions schema of this Realm is invalid, an exception of type -/// `InvalidPermissionsSchema` is thrown. -/// -/// LIMIT and DISTINCT will be applied *after* permission filters. -/// -/// The resulting TableView can be used like any other query result. -/// -/// Note: Class-level and Realm-level permissions are not taken into account in -/// the resulting TableView, since there is no way to represent this in the -/// query engine. -ConstTableView query_with_permissions(Query query, StringData user_id, - const DescriptorOrdering* ordering = nullptr); - -struct InvalidPermissionsSchema : util::runtime_error { - using util::runtime_error::runtime_error; -}; - -//@{ -/// Convenience function to modify permission data. -/// -/// When a role or user has not already been defined in the Realm, these -/// functions create them on-demand. -void set_realm_permissions_for_role(Group&, StringData role_name, - uint_least32_t privileges); -void set_class_permissions_for_role(Group&, StringData class_name, - StringData role_name, uint_least32_t privileges); -// void set_default_object_permissions_for_role(Group&, StringData class_name, -// StringData role_name, -// uint_least32_t privileges); -void set_object_permissions_for_role(Group&, TableRef table, size_t row_ndx, - StringData role_name, uint_least32_t privileges); - -void add_user_to_role(Group&, StringData user_id, StringData role_name); -//@} - -/// The Privilege enum is intended to be used in a bitfield. -enum class Privilege : uint_least32_t { - None = 0, - - /// The user can read the object (i.e. it can participate in the user's - /// subscription. - /// - /// NOTE: On objects, it is a prerequisite that the object's class is also - /// readable by the user. - /// - /// FIXME: Until we get asynchronous links, any object that is reachable - /// through links from another readable/queryable object is also readable, - /// regardless of whether the user specifically does not have read access. - Read = 1, - - /// The user can modify the fields of the object. - /// - /// NOTE: On objects, it is a prerequisite that the object's class is also - /// updatable by the user. When applied to a Class object, it does not - /// imply that the user can modify the schema of the class, only the - /// objects of that class. - /// - /// NOTE: This does not imply the SetPermissions privilege. - Update = 2, - - /// The user can delete the object. - /// - /// NOTE: When applied to a Class object, it has no effect on whether - /// objects of that class can be deleted by the user. - /// - /// NOTE: This implies the ability to implicitly nullify links pointing - /// to the object from other objects, even if the user does not have - /// permission to modify those objects in the normal way. - Delete = 4, - - //@{ - /// The user can modify the object's permissions. - /// - /// NOTE: The user will only be allowed to assign permissions at or below - /// their own privilege level. - SetPermissions = 8, - Share = SetPermissions, - //@} - - /// When applied to a Class object, the user can query objects in that - /// class. - /// - /// Has no effect when applied to objects other than Class. - Query = 16, - - /// When applied to a Class object, the user may create objects in that - /// class. - /// - /// NOTE: The user implicitly has Update and SetPermissions - /// (but not necessarily Delete permission) within the same - /// transaction as the object was created. - /// - /// NOTE: Even when a user has CreateObject rights, a CreateObject - /// operation may still be rejected by the server, if the object has a - /// primary key and the object already exists, but is not accessible by the - /// user. - Create = 32, - - /// When applied as a "Realm" privilege, the user can add classes and add - /// columns to classes. - /// - /// NOTE: When applied to a class or object, this has no effect. - ModifySchema = 64, - - /// - /// Aggregate permissions for compatibility: - /// - Download = Read | Query, - Upload = Update | Delete | Create, - DeleteRealm = Upload, // FIXME: This seems overly permissive -}; - -inline constexpr uint_least32_t operator|(Privilege a, Privilege b) -{ - return static_cast(a) | static_cast(b); -} - -inline constexpr uint_least32_t operator|(uint_least32_t a, Privilege b) -{ - return a | static_cast(b); -} - -inline constexpr uint_least32_t operator&(Privilege a, Privilege b) -{ - return static_cast(a) & static_cast(b); -} - -inline constexpr uint_least32_t operator&(uint_least32_t a, Privilege b) -{ - return a & static_cast(b); -} - -inline uint_least32_t& operator|=(uint_least32_t& a, Privilege b) -{ - return a |= static_cast(b); -} - -inline constexpr uint_least32_t operator~(Privilege p) -{ - return ~static_cast(p); -} - -struct PermissionsCache { - /// Each element is the index of a row in the `class___Roles` table. - using RoleList = std::vector; - - PermissionsCache(const Group& g, TableInfoCache& table_info_cache, - StringData user_identity, bool is_admin = false); - - bool is_admin() const noexcept; - - /// Leaves out any role that has no permission objects linking to it. - RoleList get_users_list_of_roles(); - - /// Get Realm-level privileges for the current user. - /// - /// The user must have Read access at the Realm level to be able to see - /// anything in the file. - /// - /// The user must have Update access at the Realm level to be able to make - /// any changes at all in the Realm file. - /// - /// If no Realm-level permissions are defined, no access is granted for any - /// user. - uint_least32_t get_realm_privileges(); - - /// Get class-level privileges for the current user and the given class. - /// - /// If the class does not have any class-level privileges defined, no access - /// is granted to the class. - /// - /// Calling this function is equivalent to calling `get_object_privileges()` - /// with an object of the type `__Class`. - /// - /// NOTE: This function only considers class-level permissions. It does not - /// mask the returned value by the Realm-level permissions. See `can()`. - uint_least32_t get_class_privileges(StringData class_name); - - /// Get object-level privileges for the current user and the given object. - /// - /// If the object's class has an ACL property (a linklist to the - /// `__Permission` class), and it isn't empty, the user's privileges is the - /// OR'ed privileges for the intersection of roles that have a defined - /// permission on the object and the roles of which the user is a member. - /// - /// If the object's ACL property is empty (but the column exists), no access - /// is granted to anyone. - /// - /// If the object does not exist in the table, the returned value is - /// equivalent to that of an object with an empty ACL property, i.e. no - /// privileges are granted. Note that the existence of the column is checked - /// first, so an absent ACL property (granting all privileges) takes - /// precedence over an absent object (granting no privileges) in terms of - /// calculating permissions. - /// - /// NOTE: This function only considers object-level permissions (per-object - /// ACLs or default object permissions). It does not mask the returned value - /// by the object's class-level permissions, or by the Realm-level - /// permissions. See `can()`. - uint_least32_t get_object_privileges(GlobalID); - - /// Get object-level privileges without adding it to the cache. - uint_least32_t get_object_privileges_nocache(GlobalID); - - //@{ - /// Check permissions for the object, taking all levels of permission into - /// account. - /// - /// This method only returns `true` if the user has Realm-level access to - /// the object, class-level access to the object, and object-level access to - /// the object. - /// - /// In the version where the first argument is a mask of privileges, the - /// method only returns `true` when all privileges are satisfied. - bool can(Privilege privilege, GlobalID object_id); - bool can(uint_least32_t privileges, GlobalID object_id); - //@} - - /// Invalidate all cache entries pertaining to the object. - /// - /// The object may be an instance of `__Class`. - void object_permissions_modified(GlobalID); - - /// Register the object as created in this transaction, meaning that the - /// user gets full privileges until the end of the transaction. - void object_created(GlobalID); - - /// Invalidate all cache entries pertaining to the class. - // void default_object_permissions_modified(StringData class_name); - - /// Invalidate all cached permissions. - void clear(); - - /// Check that all cache permissions correspond to the current permission - /// state in the database. - void verify(); - -private: - const Group& group; - TableInfoCache& m_table_info_cache; - std::string user_id; - bool m_is_admin; - util::Optional realm_privileges; - util::metered::map object_privileges; - ObjectIDSet created_objects; - - // uint_least32_t get_default_object_privileges(ConstTableRef); - uint_least32_t get_privileges_for_permissions(ConstLinkViewRef); - friend struct InstructionApplierWithPermissionCheck; -}; - -inline bool PermissionsCache::is_admin() const noexcept -{ - return m_is_admin; -} - -/// PermissionCorrections is a struct that describes some changes that must be -/// sent to the client because the client tried to perform changes to a database -/// that it wasn't allowed to make. -struct PermissionCorrections { - using TableColumnSet = util::metered::map>; - using TableSet = util::metered::set; - - // Objects that a client tried to delete without being allowed. - ObjectIDSet recreate_objects; - - // Objects that a client tried to create without being allowed. - ObjectIDSet erase_objects; - - // Fields that were illegally modified by the client and must be reset. - // - // Objects mentioned in `recreate_objects` and `erase_objects` are not - // mentioned here. - FieldSet reset_fields; - - // Columns that were illegally added by the client. - TableColumnSet erase_columns; - - // Columns that were illegally removed by the client. - TableColumnSet recreate_columns; - - // Tables that were illegally added by the client. - // std::set erase_tables; - TableSet erase_tables; - - // Tables that were illegally removed by the client. - TableSet recreate_tables; - - bool empty() const noexcept; -}; - -// Function for printing out a permission correction object. Useful for debugging purposes. -std::ostream& operator<<(std::ostream&, const PermissionCorrections&); - - - -/// InstructionApplierWithPermissionCheck conditionally applies each -/// instruction, and builds a `PermissionCorrections` struct based on the -/// illicit changes. The member `m_corrections` can be used to synthesize a -/// changeset that can be sent to the client to revert the illicit changes that -/// were detected by the applier. -struct InstructionApplierWithPermissionCheck { - explicit InstructionApplierWithPermissionCheck(Group& reference_realm, - bool is_admin, - StringData user_identity); - ~InstructionApplierWithPermissionCheck(); - - /// Apply \a incoming_changeset, checking permissions in the process. - /// Populates `m_corrections`. - void apply(const Changeset& incoming_changeset, util::Logger*); - - PermissionCorrections m_corrections; - -private: - struct Impl; - std::unique_ptr m_impl; -}; - - -// Implementation: - -inline bool PermissionCorrections::empty() const noexcept -{ - return recreate_objects.empty() && erase_objects.empty() - && reset_fields.empty() && erase_columns.empty() - && recreate_columns.empty() && erase_tables.empty() - && recreate_tables.empty(); -} - -} // namespace sync -} // namespace realm - - -#endif // REALM_SYNC_PERMISSIONS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/protocol.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/protocol.hpp deleted file mode 100644 index 1178218..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/protocol.hpp +++ /dev/null @@ -1,439 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_SYNC_PROTOCOL_HPP -#define REALM_SYNC_PROTOCOL_HPP - -#include -#include - -#include - - - -// NOTE: The protocol specification is in `/doc/protocol.md` - - -namespace realm { -namespace sync { - -// Protocol versions: -// -// 1 Initial version. -// -// 2 Introduces the UNBOUND message (sent from server to client in -// response to a BIND message). -// -// 3 Introduces the ERROR message (sent from server to client before the -// server closes a connection). Introduces MARK message from client to -// server, and MARK response message from server to client as a way for the -// client to wait for download to complete. -// -// 4 User token and signature are now passed as a single string (see -// /doc/protocol.md for details). Also, `application_ident` parameter -// removed from IDENT message. -// -// 5 IDENT message renamed to CLIENT, and ALLOC message (client->server) -// renamed to IDENT. Also, parameter added to CLIENT -// message. Also, the protocol has been changed to make the clients -// acquisition of a server allocated file identifier pair be part of a -// session from the servers point of view. File identifier and version -// parameters moved from the BIND message to a new IDENT message sent by -// client when it has obtained the file identifier pair. Both the new IDENT -// message and the ALLOC message sent by the server are now properly -// associated with a session. -// -// 6 Server session IDs have been added to the IDENT, DOWNLOAD, and PROGRESS -// messages, and the "Divergent history" error code was added as an -// indication that a server version / session ID pair does not match the -// server's history. -// -// 7 FIXME: Who introduced version 7? Please describe what changed. -// -// 8 Error code (`bad_authentication`) moved from 200-range to 300-range -// because it is now session specific. Other error codes were renumbered. -// -// 9 New format of the DOWNLOAD message to support progress reporting on the -// client -// -// 10 Error codes reordered (now categorized as either connection or session -// level errors). -// -// 11 Bugfixes in Link List and ChangeLinkTargets merge rules, that -// make previous versions incompatible. -// -// 12 FIXME What was 12? -// -// 13 Bugfixes in Link List and ChangeLinkTargets merge rules, that -// make previous versions incompatible. -// -// 14 Further bugfixes related to primary keys and link lists. Add support for -// LinkListSwap. -// -// 15 Deleting an object with a primary key deletes all objects on other -// with the same primary key. -// -// 16 Downloadable bytes added to DOWNLOAD message. It is used for download progress -// by the client -// -// 17 Added PING and PONG messages. It is used for rtt monitoring and dead -// connection detection by both the client and the server. -// -// 18 Enhanced the session_ident to accept values of size up to at least 63 bits. -// -// 19 New instruction log format with stable object IDs and arrays of -// primitives (Generalized LinkList* commands to Container* commands) -// Message format is identical to version 18. -// -// 20 Added support for log compaction in DOWNLOAD message. -// -// 21 Removed "class_" prefix in instructions referencing tables. -// -// 22 Fixed a bug in the merge rule of MOVE vs SWAP. -// -// 23 Introduced full support for session specific ERROR messages. Removed the -// obsolete concept of a "server file identifier". Added support for relayed -// subtier client file identifier allocation. For this purpose, the message -// that was formerly known as ALLOC was renamed to IDENT, and a new ALLOC -// message was added in both directions. Added the ability for an UPLOAD -// message to carry a per-changeset origin client file identifier. Added -// `` parameter to DOWNLOAD message. Added new error -// codes 215 "Unsupported session-level feature" and 216 "Bad origin client -// file identifier (UPLOAD)". -// -// 24 Support schema-breaking instructions. Official support for partial sync. -// -// 25 Include "last server version" in the UPLOAD message for history trimming -// on the server. -// -// 26 Four new protocol error codes, 217, 218, 219, and 220. -// -// The downloadable_bytes field in the DOWNLOAD message denotes the byte -// size of the changesets following those in the DOWNLOAD -// message. Previously, downloadable_bytes denoted the total byte size of -// the entire history. -// -// Introduction of protocol version flexibility on client side (strictly -// speaking, this is a change that transcends the sync protocol). -// -// 27 STATE_REQUEST, STATE, CLIENT_VERSION_REQUEST and CLIENT_VERSION messages -// introduced. These messages are used for client reset and async open. -// -// 28 Introduction of TRANSACT message (serialized transactions). New session -// level error code 221 "Serialized transaction before upload completion". -// -// Also added new parameters ``, ``, ``, and `` to STATE_REQUEST message. -// -// 29 Addition of `` and `` -// to the UPLOAD message. Together, these constitute an upload cursor that -// marks the reached position in the client-side history of the uploading -// process. -// -// Removal of ``, and addition of ``. `` was replaced in part by `` as described above, and in part by the new ``. The purpose of `` is to allow -// the client to lock parts of the server-side history that precede -// ``. It is intended to be used in the future in -// conjunction with the cooked history. -// -// 30 New error code, 222 "Client file has expired", was added. New parameter -// `` added to BIND message. -// -constexpr int get_current_protocol_version() noexcept -{ - return 30; -} - - -/// Supported protocol envelopes: -/// -/// Alternative (*) -/// Name Envelope URL scheme Default port default port -/// ------------------------------------------------------------------------ -/// realm WebSocket realm: 7800 80 -/// realms WebSocket + SSL realms: 7801 443 -/// ws WebSocket ws: 80 -/// wss WebSocket + SSL wss: 443 -/// -/// *) When Client::Config::enable_default_port_hack is true -/// -enum class ProtocolEnvelope { realm, realms, ws, wss }; - -inline bool is_ssl(ProtocolEnvelope protocol) noexcept -{ - switch (protocol) { - case ProtocolEnvelope::realm: - case ProtocolEnvelope::ws: - break; - case ProtocolEnvelope::realms: - case ProtocolEnvelope::wss: - return true; - } - return false; -} - - -// These integer types are selected so that they accomodate the requirements of -// the protocol specification (`/doc/protocol.md`). -using file_ident_type = std::uint_fast64_t; -using version_type = Replication::version_type; -using salt_type = std::int_fast64_t; -using timestamp_type = std::uint_fast64_t; -using session_ident_type = std::uint_fast64_t; -using request_ident_type = std::uint_fast64_t; -using milliseconds_type = std::int_fast64_t; - -constexpr file_ident_type get_max_file_ident() -{ - return 0x0'7FFF'FFFF'FFFF'FFFF; -} - - -struct SaltedFileIdent { - file_ident_type ident; - /// History divergence and identity spoofing protection. - salt_type salt; -}; - -struct SaltedVersion { - version_type version; - /// History divergence protection. - salt_type salt; -}; - - -/// \brief A client's reference to a position in the server-side history. -/// -/// A download cursor refers to a position in the server-side history. If -/// `server_version` is zero, the position is at the beginning of the history, -/// otherwise the position is after the entry whose changeset produced that -/// version. In general, positions are to be understood as places between two -/// adjacent history entries. -/// -/// `last_integrated_client_version` is the version produced on the client by -/// the last changeset that was sent to the server and integrated into the -/// server-side Realm state at the time indicated by the history position -/// specified by `server_version`, or zero if no changesets from the client were -/// integrated by the server at that point in time. -struct DownloadCursor { - version_type server_version; - version_type last_integrated_client_version; -}; - -/// Checks that `dc.last_integrated_client_version` is zero if -/// `dc.server_version` is zero. -bool is_consistent(DownloadCursor dc) noexcept; - -/// Checks that `a.last_integrated_client_version` and -/// `b.last_integrated_client_version` are equal, if `a.server_version` and -/// `b.server_version` are equal. Otherwise checks that -/// `a.last_integrated_client_version` is less than, or equal to -/// `b.last_integrated_client_version`, if `a.server_version` is less than -/// `b.server_version`. Otherwise checks that `a.last_integrated_client_version` -/// is greater than, or equal to `b.last_integrated_client_version`. -bool are_mutually_consistent(DownloadCursor a, DownloadCursor b) noexcept; - - -/// \brief The server's reference to a position in the client-side history. -/// -/// An upload cursor refers to a position in the client-side history. If -/// `client_version` is zero, the position is at the beginning of the history, -/// otherwise the position is after the entry whose changeset produced that -/// version. In general, positions are to be understood as places between two -/// adjacent history entries. -/// -/// `last_integrated_server_version` is the version produced on the server by -/// the last changeset that was sent to the client and integrated into the -/// client-side Realm state at the time indicated by the history position -/// specified by `client_version`, or zero if no changesets from the server were -/// integrated by the client at that point in time. -struct UploadCursor { - version_type client_version; - version_type last_integrated_server_version; -}; - -/// Checks that `uc.last_integrated_server_version` is zero if -/// `uc.client_version` is zero. -bool is_consistent(UploadCursor uc) noexcept; - -/// Checks that `a.last_integrated_server_version` and -/// `b.last_integrated_server_version` are equal, if `a.client_version` and -/// `b.client_version` are equal. Otherwise checks that -/// `a.last_integrated_server_version` is less than, or equal to -/// `b.last_integrated_server_version`, if `a.client_version` is less than -/// `b.client_version`. Otherwise checks that `a.last_integrated_server_version` -/// is greater than, or equal to `b.last_integrated_server_version`. -bool are_mutually_consistent(UploadCursor a, UploadCursor b) noexcept; - - -/// A client's record of the current point of progress of the synchronization -/// process. The client must store this persistently in the local Realm file. -struct SyncProgress { - /// The last server version that the client has heard about. - SaltedVersion latest_server_version = {0, 0}; - - /// The last server version integrated, or about to be integrated by the - /// client. - DownloadCursor download = {0, 0}; - - /// The last client version integrated by the server. - UploadCursor upload = {0, 0}; -}; - - -/// An indication of the final status of an attempt at performing a serialized -/// transaction. -enum class SerialTransactStatus { - /// The transaction was accepted and successful. - accepted = 1, - - /// The transaction was rejected because the servers history contained - /// causally unrelated changes. I.e., the requesting client lost a race to - /// be served first. The client should try again. - rejected = 2, - - /// The server did not support serialized transactions at all, or did not - /// support it on the targeted Realm in particular. - not_supported = 3, -}; - - - -/// \brief Protocol errors discovered by the server, and reported to the client -/// by way of ERROR messages. -/// -/// These errors will be reported to the client-side application via the error -/// handlers of the affected sessions. -/// -/// ATTENTION: Please remember to update is_session_level_error() when -/// adding/removing error codes. -enum class ProtocolError { - // Connection level and protocol errors - connection_closed = 100, // Connection closed (no error) - other_error = 101, // Other connection level error - unknown_message = 102, // Unknown type of input message - bad_syntax = 103, // Bad syntax in input message head - limits_exceeded = 104, // Limits exceeded in input message - wrong_protocol_version = 105, // Wrong protocol version (CLIENT) (obsolete) - bad_session_ident = 106, // Bad session identifier in input message - reuse_of_session_ident = 107, // Overlapping reuse of session identifier (BIND) - bound_in_other_session = 108, // Client file bound in other session (IDENT) - bad_message_order = 109, // Bad input message order - bad_decompression = 110, // Error in decompression (UPLOAD) - bad_changeset_header_syntax = 111, // Bad syntax in a changeset header (UPLOAD) - bad_changeset_size = 112, // Bad size specified in changeset header (UPLOAD) - bad_changesets = 113, // Bad changesets (UPLOAD) - - // Session level errors - session_closed = 200, // Session closed (no error) - other_session_error = 201, // Other session level error - token_expired = 202, // Access token expired - bad_authentication = 203, // Bad user authentication (BIND, REFRESH) - illegal_realm_path = 204, // Illegal Realm path (BIND) - no_such_realm = 205, // No such Realm (BIND) - permission_denied = 206, // Permission denied (STATE_REQUEST, BIND, REFRESH) - bad_server_file_ident = 207, // Bad server file identifier (IDENT) (obsolete!) - bad_client_file_ident = 208, // Bad client file identifier (IDENT) - bad_server_version = 209, // Bad server version (IDENT, UPLOAD, TRANSACT) - bad_client_version = 210, // Bad client version (IDENT, UPLOAD) - diverging_histories = 211, // Diverging histories (IDENT) - bad_changeset = 212, // Bad changeset (UPLOAD) - superseded = 213, // Superseded by new session for same client-side file (deprecated) - disabled_session = 213, // Alias for `superseded` (deprecated) - partial_sync_disabled = 214, // Partial sync disabled (BIND, STATE_REQUEST) - unsupported_session_feature = 215, // Unsupported session-level feature - bad_origin_file_ident = 216, // Bad origin file identifier (UPLOAD) - bad_client_file = 217, // Synchronization no longer possible for client-side file - server_file_deleted = 218, // Server file was deleted while session was bound to it - client_file_blacklisted = 219, // Client file has been blacklisted (IDENT) - user_blacklisted = 220, // User has been blacklisted (BIND) - transact_before_upload = 221, // Serialized transaction before upload completion - client_file_expired = 222, // Client file has expired -}; - -constexpr bool is_session_level_error(ProtocolError); - -/// Returns null if the specified protocol error code is not defined by -/// ProtocolError. -const char* get_protocol_error_message(int error_code) noexcept; - -const std::error_category& protocol_error_category() noexcept; - -std::error_code make_error_code(ProtocolError) noexcept; - -} // namespace sync -} // namespace realm - -namespace std { - -template<> struct is_error_code_enum { - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace sync { - - - - - -// Implementation - -inline bool is_consistent(DownloadCursor dc) noexcept -{ - return (dc.server_version != 0 || dc.last_integrated_client_version == 0); -} - -inline bool are_mutually_consistent(DownloadCursor a, DownloadCursor b) noexcept -{ - if (a.server_version < b.server_version) - return (a.last_integrated_client_version <= b.last_integrated_client_version); - if (a.server_version > b.server_version) - return (a.last_integrated_client_version >= b.last_integrated_client_version); - return (a.last_integrated_client_version == b.last_integrated_client_version); -} - -inline bool is_consistent(UploadCursor uc) noexcept -{ - return (uc.client_version != 0 || uc.last_integrated_server_version == 0); -} - -inline bool are_mutually_consistent(UploadCursor a, UploadCursor b) noexcept -{ - if (a.client_version < b.client_version) - return (a.last_integrated_server_version <= b.last_integrated_server_version); - if (a.client_version > b.client_version) - return (a.last_integrated_server_version >= b.last_integrated_server_version); - return (a.last_integrated_server_version == b.last_integrated_server_version); -} - -constexpr bool is_session_level_error(ProtocolError error) -{ - return int(error) >= 200 && int(error) <= 299; -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_PROTOCOL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/transform.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/transform.hpp deleted file mode 100644 index e1b42bb..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/transform.hpp +++ /dev/null @@ -1,353 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_SYNC_TRANSFORM_HPP -#define REALM_SYNC_TRANSFORM_HPP - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace realm { -namespace sync { - -struct Changeset; - -/// Represents an entry in the history of changes in a sync-enabled Realm -/// file. Server and client use different history formats, but this class is -/// used both on the server and the client side. Each history entry corresponds -/// to a version of the Realm state. For server and client-side histories, these -/// versions are referred to as *server versions* and *client versions* -/// respectively. These versions may, or may not correspond to Realm snapshot -/// numbers (on the server-side they currently do not). -/// -/// FIXME: Move this class into a separate header -/// (``). -class HistoryEntry { -public: - /// The time of origination of the changes referenced by this history entry, - /// meassured as the number of milliseconds since 2015-01-01T00:00:00Z, not - /// including leap seconds. For changes of local origin, this is the local - /// time at the point when the local transaction was committed. For changes - /// of remote origin, it is the remote time of origin at the peer (client or - /// server) identified by `origin_file_ident`. - timestamp_type origin_timestamp; - - /// The identifier of the file in the context of which the initial - /// untransformed changeset originated, or zero if the changeset originated - /// on the local peer (client or server). - /// - /// For example, when a changeset "travels" from a file with identifier 2 on - /// client A, through a file with identifier 1 on the server, to a file with - /// identifier 3 on client B, then `origin_file_ident` will be 0 on client - /// A, 2 on the server, and 2 on client B. On the other hand, if the server - /// was the originator of the changeset, then `origin_file_ident` would be - /// zero on the server, and 1 on both clients. - file_ident_type origin_file_ident; - - /// For changes of local origin on the client side, this is the last server - /// version integrated locally prior to this history entry. In other words, - /// it is a copy of `remote_version` of the last preceding history entry - /// that carries changes of remote origin, or zero if there is no such - /// preceding history entry. - /// - /// For changes of local origin on the server-side, this is always zero. - /// - /// For changes of remote origin, this is the version produced within the - /// remote-side Realm file by the change that gave rise to this history - /// entry. The remote-side Realm file is not always the same Realm file from - /// which the change originated. On the client side, the remote side is - /// always the server side, and `remote_version` is always a server version - /// (since clients do not speak directly to each other). On the server side, - /// the remote side is always a client side, and `remote_version` is always - /// a client version. - version_type remote_version; - - /// Referenced memory is not owned by this class. - ChunkedBinaryData changeset; -}; - - - -/// The interface between the sync history and the operational transformer -/// (Transformer) for the purpose of transforming changesets received from a -/// particular *remote peer*. -class TransformHistory { -public: - /// Get the first history entry where the produced version is greater than - /// `begin_version` and less than or equal to `end_version`, and whose - /// changeset is neither empty, nor produced by integration of a changeset - /// received from the remote peer associated with this history. - /// - /// If \a buffer is non-null, memory will be allocated and transferred to - /// \a buffer. The changeset will be copied into the newly allocated memory. - /// - /// If \a buffer is null, the changeset is not copied out of the Realm, - /// and entry.changeset.data() does not point to the changeset. - /// The changeset in the Realm could be chunked, hence it is not possible - /// to point to it with BinaryData. entry.changeset.size() always gives the - /// size of the changeset. - /// - /// \param begin_version, end_version The range of versions to consider. If - /// `begin_version` is equal to `end_version`, it is the empty range. If - /// `begin_version` is zero, it means that everything preceeding - /// `end_version` is to be considered, which is again the empty range if - /// `end_version` is also zero. Zero is a special value in that no changeset - /// produces that version. It is an error if `end_version` precedes - /// `begin_version`, or if `end_version` is zero and `begin_version` is not. - /// - /// \return The version produced by the changeset of the located history - /// entry, or zero if no history entry exists matching the specified and - /// implied criteria. - virtual version_type find_history_entry(version_type begin_version, version_type end_version, - HistoryEntry& entry) const noexcept = 0; - - /// Get the specified reciprocal changeset. The targeted history entry is - /// the one whose untransformed changeset produced the specified version. - virtual ChunkedBinaryData get_reciprocal_transform(version_type version) const = 0; - - /// Replace the specified reciprocally transformed changeset. The targeted - /// history entry is the one whose untransformed changeset produced the - /// specified version. - /// - /// \param encoded_changeset The new reciprocally transformed changeset. - virtual void set_reciprocal_transform(version_type version, BinaryData encoded_changeset) = 0; - - virtual ~TransformHistory() noexcept {} -}; - - - -class TransformError; // Exception - -class Transformer { -public: - class RemoteChangeset; - class Reporter; - - /// Produce operationally transformed versions of the specified changesets, - /// which are assumed to be received from a particular remote peer, P, - /// represented by the specified transform history. Note that P is not - /// necessarily the peer on which the changes originated. - /// - /// Operational transformation is carried out between the specified - /// changesets and all causally unrelated changesets in the local history. A - /// changeset in the local history is causally unrelated if, and only if it - /// occurs after the local changeset that produced - /// `remote_changeset.last_integrated_local_version` and is not a produced - /// by integration of a changeset received from P. This assumes that - /// `remote_changeset.last_integrated_local_version` is set to the local - /// version produced by the last local changeset, that was integrated by P - /// before P produced the specified changeset. - /// - /// The operational transformation is reciprocal (two-way), so it also - /// transforms the causally unrelated local changesets. This process does - /// not modify the history itself (the changesets available through - /// TransformHistory::get_history_entry()), instead the reciprocally - /// transformed changesets are stored separately, and individually for each - /// remote peer, such that they can participate in transformation of the - /// next incoming changeset from P. - /// - /// In general, if A and B are two causally unrelated (alternative) - /// changesets based on the same version V, then the operational - /// transformation between A and B produces changesets A' and B' such that - /// both of the concatenated changesets A + B' and B + A' produce the same - /// final state when applied to V. Operational transformation is meaningful - /// only when carried out between alternative changesets based on the same - /// version. - /// - /// \param local_file_ident The identifier of the local Realm file. The - /// transformer uses this as the actual origin file identifier for - /// changesets where HistoryEntry::origin_file_ident is zero, i.e., when the - /// changeset is of local origin. The specified identifier must never be - /// zero. - /// - /// \return The size of the transformed version of the specified - /// changesets. Upon return, the transformed changesets are concatenated - /// and placed in \a output_buffer. - /// - /// \throw TransformError Thrown if operational transformation fails due to - /// a problem with the specified changeset. - /// - /// FIXME: Consider using std::error_code instead of throwing - /// TransformError. - virtual void transform_remote_changesets(TransformHistory&, - file_ident_type local_file_ident, - version_type current_local_version, - Changeset* changesets, - std::size_t num_changesets, - Reporter* = nullptr, - util::Logger* = nullptr) = 0; - - virtual ~Transformer() noexcept {} -}; - -std::unique_ptr make_transformer(); - -} // namespace sync - - -namespace _impl { - -class TransformerImpl : public sync::Transformer { -public: - using Changeset = sync::Changeset; - using file_ident_type = sync::file_ident_type; - using HistoryEntry = sync::HistoryEntry; - using Instruction = sync::Instruction; - using TransformHistory = sync::TransformHistory; - using version_type = sync::version_type; - - TransformerImpl(); - - void transform_remote_changesets(TransformHistory&, file_ident_type, version_type, Changeset*, - std::size_t, Reporter*, util::Logger*) override; - - struct Side; - struct MajorSide; - struct MinorSide; - -protected: - virtual void merge_changesets(file_ident_type local_file_ident, - Changeset* their_changesets, - std::size_t their_size, - // our_changesets is a pointer-pointer because these changesets - // are held by the reciprocal transform cache. - Changeset** our_changesets, - std::size_t our_size, - Reporter* reporter, - util::Logger* logger); - -private: - util::metered::map> m_reciprocal_transform_cache; - - TransactLogParser m_changeset_parser; - - Changeset& get_reciprocal_transform(TransformHistory&, file_ident_type local_file_ident, - version_type version, const HistoryEntry&); - void flush_reciprocal_transform_cache(TransformHistory&); - - static size_t emit_changesets(const Changeset*, - size_t num_changesets, - util::Buffer& output_buffer); - - struct Discriminant; - struct Transformer; - struct MergeTracer; - - template - void merge_instructions(LeftSide&, RightSide&); -}; - -} // namespace _impl - - -namespace sync { - -class Transformer::RemoteChangeset { -public: - /// The version produced on the remote peer by this changeset. - /// - /// On the server, the remote peer is the client from which the changeset - /// originated, and `remote_version` is the client version produced by the - /// changeset on that client. - /// - /// On a client, the remote peer is the server, and `remote_version` is the - /// server version produced by this changeset on the server. Since the - /// server is never the originator of changes, this changeset must in turn - /// have been produced on the server by integration of a changeset uploaded - /// by some other client. - version_type remote_version = 0; - - /// The last local version that has been integrated into `remote_version`. - /// - /// A local version, L, has been integrated into a remote version, R, when, - /// and only when L is the latest local version such that all preceeding - /// changesets in the local history have been integrated by the remote peer - /// prior to R. - /// - /// On the server, this is the last server version integrated into the - /// client version `remote_version`. On a client, it is the last client - /// version integrated into the server version `remote_version`. - version_type last_integrated_local_version = 0; - - /// The changeset itself. - ChunkedBinaryData data; - - /// Same meaning as `HistoryEntry::origin_timestamp`. - timestamp_type origin_timestamp = 0; - - /// Same meaning as `HistoryEntry::origin_file_ident`. - file_ident_type origin_file_ident = 0; - - /// If the changeset was compacted during download, the size of the original - /// changeset. - std::size_t original_changeset_size = 0; - - RemoteChangeset() {} - RemoteChangeset(version_type rv, version_type lv, ChunkedBinaryData d, timestamp_type ot, - file_ident_type fi); -}; - - - -class Transformer::Reporter { -public: - virtual void on_changesets_merged(long num_merges) = 0; -}; - - - -void parse_remote_changeset(const Transformer::RemoteChangeset&, Changeset&); - - - - -// Implementation - -class TransformError: public std::runtime_error { -public: - TransformError(const std::string& message): - std::runtime_error(message) - { - } -}; - -inline Transformer::RemoteChangeset::RemoteChangeset(version_type rv, version_type lv, - ChunkedBinaryData d, timestamp_type ot, - file_ident_type fi): - remote_version(rv), - last_integrated_local_version(lv), - data(d), - origin_timestamp(ot), - origin_file_ident(fi) -{ -} - -} // namespace sync -} // namespace realm - -#endif // REALM_SYNC_TRANSFORM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/sync/version.hpp b/Lesson14/Pods/Realm/include/core/realm/sync/version.hpp deleted file mode 100644 index 688bfe4..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/sync/version.hpp +++ /dev/null @@ -1,34 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2013] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_SYNC_VERSION_HPP -#define REALM_SYNC_VERSION_HPP - -#include - -#define REALM_SYNC_VER_MAJOR 4 -#define REALM_SYNC_VER_MINOR 9 -#define REALM_SYNC_VER_PATCH 4 -#define REALM_SYNC_PRODUCT_NAME "realm-sync" - -#define REALM_SYNC_VER_STRING REALM_QUOTE(REALM_SYNC_VER_MAJOR) "." \ - REALM_QUOTE(REALM_SYNC_VER_MINOR) "." REALM_QUOTE(REALM_SYNC_VER_PATCH) -#define REALM_SYNC_VER_CHUNK "[" REALM_SYNC_PRODUCT_NAME "-" REALM_SYNC_VER_STRING "]" - -#endif // REALM_SYNC_VERSION_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/table.hpp b/Lesson14/Pods/Realm/include/core/realm/table.hpp deleted file mode 100644 index 1535b57..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/table.hpp +++ /dev/null @@ -1,2807 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_TABLE_HPP -#define REALM_TABLE_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace realm { - -class BacklinkColumn; -template -class BacklinkCount; -class BinaryColumy; -class ConstTableView; -class Group; -class LinkColumn; -class LinkColumnBase; -class LinkListColumn; -class LinkView; -class SortDescriptor; -class StringIndex; -class TableView; -class TableViewBase; -class TimestampColumn; -template -class Columns; -template -class SubQuery; -struct LinkTargetInfo; - -struct SubTable { -}; -struct Link { -}; -typedef Link LinkList; -typedef Link BackLink; - -namespace _impl { -class TableFriend; -} -namespace metrics { -class QueryInfo; -} - -class Replication; - - -/// FIXME: Table assignment (from any group to any group) could be made aliasing -/// safe as follows: Start by cloning source table into target allocator. On -/// success, assign, and then deallocate any previous structure at the target. -/// -/// FIXME: It might be desirable to have a 'table move' feature between two -/// places inside the same group (say from a subtable or a mixed column to group -/// level). This could be done in a very efficient manner. -/// -/// FIXME: When compiling in debug mode, all public non-static table functions -/// should REALM_ASSERT(is_attached()). -class Table { -public: - /// Construct a new freestanding top-level table with static - /// lifetime. - /// - /// This constructor should be used only when placing a table - /// instance on the stack, and it is then the responsibility of - /// the application that there are no objects of type TableRef or - /// ConstTableRef that refer to it, or to any of its subtables, - /// when it goes out of scope. To create a top-level table with - /// dynamic lifetime, use Table::create() instead. - Table(Allocator& = Allocator::get_default()); - - /// Construct a copy of the specified table as a new freestanding - /// top-level table with static lifetime. - /// - /// This constructor should be used only when placing a table - /// instance on the stack, and it is then the responsibility of - /// the application that there are no objects of type TableRef or - /// ConstTableRef that refer to it, or to any of its subtables, - /// when it goes out of scope. To create a top-level table with - /// dynamic lifetime, use Table::copy() instead. - Table(const Table&, Allocator& = Allocator::get_default()); - - ~Table() noexcept; - - Allocator& get_alloc() const; - - /// Construct a new freestanding top-level table with dynamic lifetime. - static TableRef create(Allocator& = Allocator::get_default()); - - /// Construct a copy of the specified table as a new freestanding top-level - /// table with dynamic lifetime. - TableRef copy(Allocator& = Allocator::get_default()) const; - - /// Returns true if, and only if this accessor is currently attached to an - /// underlying table. - /// - /// A table accessor may get detached from the underlying row for various - /// reasons (see below). When it does, it no longer refers to anything, and - /// can no longer be used, except for calling is_attached(). The - /// consequences of calling other non-static functions on a detached table - /// accessor are unspecified. Table accessors obtained by calling functions in - /// the Realm API are always in the 'attached' state immediately upon - /// return from those functions. - /// - /// A table accessor of a free-standing table never becomes detached (except - /// during its eventual destruction). A group-level table accessor becomes - /// detached if the underlying table is removed from the group, or when the - /// group accessor is destroyed. A subtable accessor becomes detached if the - /// underlying subtable is removed, or if the parent table accessor is - /// detached. A table accessor does not become detached for any other reason - /// than those mentioned here. - /// - /// FIXME: High level language bindings will probably want to be able to - /// explicitely detach a group and all tables of that group if any modifying - /// operation fails (e.g. memory allocation failure) (and something similar - /// for freestanding tables) since that leaves the group in state where any - /// further access is disallowed. This way they will be able to reliably - /// intercept any attempt at accessing such a failed group. - /// - /// FIXME: The C++ documentation must state that if any modifying operation - /// on a group (incl. tables, subtables, and specs) or on a free standing - /// table (incl. subtables and specs) fails, then any further access to that - /// group (except ~Group()) or freestanding table (except ~Table()) has - /// undefined behaviour and is considered an error on behalf of the - /// application. Note that even Table::is_attached() is disallowed in this - /// case. - bool is_attached() const noexcept; - - /// Get the name of this table, if it has one. Only group-level tables have - /// names. For a table of any other kind, this function returns the empty - /// string. - StringData get_name() const noexcept; - - // Whether or not elements can be null. - bool is_nullable(size_t col_ndx) const; - - // Returns the link type for the given column. - // Throws an LogicError if target column is not a link column. - LinkType get_link_type(size_t col_ndx) const; - - //@{ - /// Conventience functions for inspecting the dynamic table type. - /// - /// These functions behave as if they were called on the descriptor returned - /// by get_descriptor(). - size_t get_column_count() const noexcept; - DataType get_column_type(size_t column_ndx) const noexcept; - StringData get_column_name(size_t column_ndx) const noexcept; - size_t get_column_index(StringData name) const noexcept; - typedef util::Optional> BacklinkOrigin; - BacklinkOrigin find_backlink_origin(StringData origin_table_name, StringData origin_col_name) const noexcept; - //@} - - //@{ - /// Convenience functions for manipulating the dynamic table type. - /// - /// These function must be called only for tables with independent dynamic - /// type. A table has independent dynamic type if the function - /// has_shared_type() returns false. A table that is a direct member of a - /// group has independent dynamic type. So does a free-standing table, and a - /// subtable in a column of type 'mixed'. All other tables have shared - /// dynamic type. The consequences of calling any of these functions for a - /// table with shared dynamic type are undefined. - /// - /// Apart from that, these functions behave as if they were called on the - /// descriptor returned by get_descriptor(). Note especially that the - /// `_link` suffixed functions must be used when inserting link-type - /// columns. - /// - /// If you need to change the shared dynamic type of the subtables in a - /// subtable column, consider using the API offered by the Descriptor class. - /// - /// \sa has_shared_type() - /// \sa get_descriptor() - - size_t add_column(DataType type, StringData name, bool nullable = false, DescriptorRef* subdesc = nullptr); - void insert_column(size_t column_ndx, DataType type, StringData name, bool nullable = false, - DescriptorRef* subdesc = nullptr); - - // Todo, these prototypes only exist for backwards compatibility. We should remove them because they are error - // prone (optional arguments and implicit bool to null-ptr conversion) - size_t add_column(DataType type, StringData name, DescriptorRef* subdesc) - { - return add_column(type, name, false, subdesc); - } - void insert_column(size_t column_ndx, DataType type, StringData name, DescriptorRef* subdesc) - { - insert_column(column_ndx, type, name, false, subdesc); - } - - size_t add_column_link(DataType type, StringData name, Table& target, LinkType link_type = link_Weak); - void insert_column_link(size_t column_ndx, DataType type, StringData name, Table& target, - LinkType link_type = link_Weak); - void remove_column(size_t column_ndx); - void rename_column(size_t column_ndx, StringData new_name); - //@} - //@{ - - /// has_search_index() returns true if, and only if a search index has been - /// added to the specified column. Rather than throwing, it returns false if - /// the table accessor is detached or the specified index is out of range. - /// - /// add_search_index() adds a search index to the specified column of the - /// table. It has no effect if a search index has already been added to the - /// specified column (idempotency). - /// - /// remove_search_index() removes the search index from the specified column - /// of the table. It has no effect if the specified column has no search - /// index. The search index cannot be removed from the primary key of a - /// table. - /// - /// This table must be a root table; that is, it must have an independent - /// descriptor. Freestanding tables, group-level tables, and subtables in a - /// column of type 'mixed' are all examples of root tables. See add_column() - /// for more on this. If you want to manipulate subtable indexes, you must use - /// the Descriptor interface. - /// - /// \param column_ndx The index of a column of the table. - - bool has_search_index(size_t column_ndx) const noexcept; - void add_search_index(size_t column_ndx); - void remove_search_index(size_t column_ndx); - - //@} - - //@{ - /// Get the dynamic type descriptor for this table. - /// - /// Every table has an associated descriptor that specifies its dynamic - /// type. For simple tables, that is, tables without subtable columns, the - /// dynamic type can be inspected and modified directly using member - /// functions such as get_column_count() and add_column(). For more complex - /// tables, the type is best managed through the associated descriptor - /// object which is returned by this function. - /// - /// \sa has_shared_type() - DescriptorRef get_descriptor(); - ConstDescriptorRef get_descriptor() const; - //@} - - //@{ - /// Get the dynamic type descriptor for the column with the - /// specified index. That column must have type 'table'. - /// - /// This is merely a shorthand for calling `get_subdescriptor(column_ndx)` - /// on the descriptor returned by `get_descriptor()`. - DescriptorRef get_subdescriptor(size_t column_ndx); - ConstDescriptorRef get_subdescriptor(size_t column_ndx) const; - //@} - - //@{ - /// Get access to an arbitrarily nested dynamic type descriptor. - /// - /// The returned descriptor is the one you would get by calling - /// Descriptor::get_subdescriptor() once for each entry in the specified - /// path, starting with the descriptor returned by get_descriptor(). The - /// path is allowed to be empty. - typedef std::vector path_vec; - DescriptorRef get_subdescriptor(const path_vec& path); - ConstDescriptorRef get_subdescriptor(const path_vec& path) const; - //@} - - //@{ - /// Convenience functions for manipulating nested table types. - /// - /// These functions behave as if they were called on the descriptor returned - /// by `get_subdescriptor(path)`. These function must be called only on - /// tables with independent dynamic type. - /// - /// \return The value returned by add_subcolumn(), is the index of - /// the added column within the descriptor referenced by the - /// specified path. - /// - /// \sa Descriptor::add_column() - /// \sa has_shared_type() - size_t add_subcolumn(const path_vec& path, DataType type, StringData name); - void insert_subcolumn(const path_vec& path, size_t column_ndx, DataType type, StringData name); - void remove_subcolumn(const path_vec& path, size_t column_ndx); - void rename_subcolumn(const path_vec& path, size_t column_ndx, StringData new_name); - //@} - - /// Does this table share its type with other tables? - /// - /// Tables that are direct members of groups have independent - /// dynamic types. The same is true for free-standing tables and - /// subtables in coulmns of type 'mixed'. For such tables, this - /// function returns false. - /// - /// When a table has a column of type 'table', the cells in that - /// column contain subtables. All those subtables have the same - /// dynamic type, and they share a single type descriptor. For all - /// such subtables, this function returns true. See - /// Descriptor::is_root() for more on this. - /// - /// Please note that Table functions that modify the dynamic type - /// directly, such as add_column(), are only allowed to be used on - /// tables with non-shared type. If you need to modify a shared - /// type, you will have to do that through the descriptor returned - /// by get_descriptor(), but note that it will then affect all the - /// tables sharing that descriptor. - /// - /// \sa get_descriptor() - /// \sa Descriptor::is_root() - bool has_shared_type() const noexcept; - - - template - Columns column(size_t column); // FIXME: Should this one have been declared noexcept? - template - Columns column(const Table& origin, size_t origin_column_ndx); - // BacklinkCount is a total count per row and therefore not attached to a specific column - template - BacklinkCount get_backlink_count(); - - template - SubQuery column(size_t column, Query subquery); - template - SubQuery column(const Table& origin, size_t origin_column_ndx, Query subquery); - - // Table size and deletion - bool is_empty() const noexcept; - size_t size() const noexcept; - - typedef BasicRowExpr
RowExpr; - typedef BasicRowExpr ConstRowExpr; - - RowExpr get(size_t row_ndx) noexcept; - ConstRowExpr get(size_t row_ndx) const noexcept; - - RowExpr front() noexcept; - ConstRowExpr front() const noexcept; - - RowExpr back() noexcept; - ConstRowExpr back() const noexcept; - - RowExpr operator[](size_t row_ndx) noexcept; - ConstRowExpr operator[](size_t row_ndx) const noexcept; - - - //@{ - - /// Row handling. - /// - /// remove() removes the specified row from the table and shifts all rows at - /// higher index to fill the vacated slot. This operation assumes that the - /// table is ordered, and it is therefore allowed only on tables **without** - /// link columns, as link columns are only allowed in unordered tables. - /// - /// move_last_over() removes the specified row from the table, and if it is - /// not the last row in the table, it then moves the last row into the - /// vacated slot. This operation assumes that the table is unordered, and it - /// may therfore be used on tables with link columns. - /// - /// remove_recursive() will delete linked rows if the removed link was the - /// last one holding on to the row in question. This will be done recursively. - /// - /// The removal of a row from an unordered table (move_last_over()) may - /// cause other linked rows to be cascade-removed. The clearing of a table - /// may also cause linked rows to be cascade-removed, but in this respect, - /// the effect is exactly as if each row had been removed individually. See - /// Descriptor::set_link_type() for details. - - size_t add_empty_row(size_t num_rows = 1); - void insert_empty_row(size_t row_ndx, size_t num_rows = 1); - size_t add_row_with_key(size_t col_ndx, util::Optional key); - size_t add_row_with_keys(size_t col_1_ndx, int64_t key1, size_t col_2_ndx, StringData key2); - void remove(size_t row_ndx); - void remove_recursive(size_t row_ndx); - void remove_last(); - void move_last_over(size_t row_ndx); - void clear(); - void swap_rows(size_t row_ndx_1, size_t row_ndx_2); - void move_row(size_t from_ndx, size_t to_ndx); - //@} - - /// Replaces all links to \a row_ndx with links to \a new_row_ndx. - /// - /// This operation is usually followed by Table::move_last_over() - /// as part of Table::set_int_unique() or Table::set_string_unique() - /// or Table::set_null_unique() detecting a collision. - /// - /// \sa Table::move_last_over() - /// \sa Table::set_int_unique() - /// \sa Table::set_string_unique() - /// \sa Table::set_null_unique() - void merge_rows(size_t row_ndx, size_t new_row_ndx); - - //@{ - - /// Get cell values. - /// Will assert if the requested type does not match the column type. - /// - /// When fetching from a nullable column and the value is null, a default - /// value will be returned, except for object like types (StringData, - /// BinaryData, Timestamp) which have support for storing nulls. In that - /// case, call the `is_null()` method on the returned object to check - /// whether the stored value was null. If nullability matters and returning - /// a default value is unacceptable, check Table::is_null() before getting a - /// cell value. - /// - /// \sa Table::is_nullable(size_t col_ndx) - /// \sa Table::is_null(size_t col_ndx, size_t row_ndx) - /// \sa StringData::is_null() - int64_t get_int(size_t column_ndx, size_t row_ndx) const noexcept; - bool get_bool(size_t column_ndx, size_t row_ndx) const noexcept; - OldDateTime get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept; - float get_float(size_t column_ndx, size_t row_ndx) const noexcept; - double get_double(size_t column_ndx, size_t row_ndx) const noexcept; - StringData get_string(size_t column_ndx, size_t row_ndx) const noexcept; - BinaryData get_binary(size_t column_ndx, size_t row_ndx) const noexcept; - BinaryIterator get_binary_iterator(size_t column_ndx, size_t row_ndx) const noexcept; - Mixed get_mixed(size_t column_ndx, size_t row_ndx) const noexcept; - DataType get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept; - Timestamp get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept; - - //@} - - /// Return data from position 'pos' and onwards. If the blob is distributed - /// across multiple arrays, you will only get data from one array. 'pos' - /// will be updated to be an index to next available data. It will be 0 - /// if no more data. - BinaryData get_binary_at(size_t col_ndx, size_t ndx, size_t& pos) const noexcept; - - template - T get(size_t c, size_t r) const noexcept; - - size_t get_link(size_t column_ndx, size_t row_ndx) const noexcept; - bool is_null_link(size_t column_ndx, size_t row_ndx) const noexcept; - LinkViewRef get_linklist(size_t column_ndx, size_t row_ndx); - ConstLinkViewRef get_linklist(size_t column_ndx, size_t row_ndx) const; - size_t get_link_count(size_t column_ndx, size_t row_ndx) const noexcept; - bool linklist_is_empty(size_t column_ndx, size_t row_ndx) const noexcept; - bool is_null(size_t column_ndx, size_t row_ndx) const noexcept; - - TableRef get_link_target(size_t column_ndx) noexcept; - ConstTableRef get_link_target(size_t column_ndx) const noexcept; - - //@{ - - /// Set cell values. - /// - /// It is an error to specify a column index, row index, or string position - /// that is out of range. - /// - /// The number of bytes in a string value must not exceed `max_string_size`, - /// and the number of bytes in a binary data value must not exceed - /// `max_binary_size`. String must also contain valid UTF-8 encodings. These - /// requirements also apply when modifying a string with insert_substring() - /// and remove_substring(), and for strings in a mixed columnt. Passing, or - /// producing an oversized string or binary data value will cause an - /// exception to be thrown. - /// - /// The "unique" variants (set_int_unique(), set_string_unique(), set_null_unique()) - /// are intended to be used in the implementation of primary key support. They - /// check if the given column already contains one or more values that are - /// equal to \a value, and if there are conflicts, it calls - /// Table::merge_rows() for the row_ndx to be replaced by the - /// existing row, followed by a Table::move_last_over() of row_ndx. The - /// return value is always a row index of a row that contains \a value in - /// the specified column, possibly different from \a row_ndx if a conflict - /// occurred. Users intending to implement primary keys must therefore - /// manually check for duplicates if they want to raise an error instead. - /// - /// NOTE: It is an error to call either function after adding elements to a - /// linklist in the object. In general, calling set_int_unique() or - /// set_string_unique() or set_null_unique() should be the first thing that - /// happens after creating a row. These limitations are imposed by limitations - /// in the Realm Object Server and may be relaxed in the future. A violation of - /// these rules results in a LogicError being thrown. - /// - /// add_int() adds a 64-bit signed integer to the current value of the - /// cell. If the addition would cause signed integer overflow or - /// underflow, the addition "wraps around" with semantics similar to - /// unsigned integer arithmetic, such that Table::max_integer + 1 == - /// Table::min_integer and Table::min_integer - 1 == Table::max_integer. - /// Note that the wrapping is platform-independent (all platforms wrap in - /// the same way regardless of integer representation). If the existing - /// value in the cell is null, a LogicError exception is thrown. - /// - /// insert_substring() inserts the specified string into the currently - /// stored string at the specified position. The position must be less than - /// or equal to the size of the currently stored string. - /// - /// remove_substring() removes the specified byte range from the currently - /// stored string. The beginning of the range (\a pos) must be less than or - /// equal to the size of the currently stored string. If the specified range - /// extends beyond the end of the currently stored string, it will be - /// silently clamped. - /// - /// String level modifications performed via insert_substring() and - /// remove_substring() are mergable and subject to operational - /// transformation. That is, the effect of two causally unrelated - /// modifications will in general both be retained during synchronization. - - static const size_t max_string_size = 0xFFFFF8 - Array::header_size - 1; - static const size_t max_binary_size = 0xFFFFF8 - Array::header_size; - - // FIXME: These limits should be chosen independently of the underlying - // platform's choice to define int64_t and independent of the integer - // representation. The current values only work for 2's complement, which is - // not guaranteed by the standard. - static constexpr int_fast64_t max_integer = std::numeric_limits::max(); - static constexpr int_fast64_t min_integer = std::numeric_limits::min(); - - template - void set(size_t c, size_t r, T value, bool is_default = false); - - template - size_t set_unique(size_t c, size_t r, T value); - - void set_int(size_t column_ndx, size_t row_ndx, int_fast64_t value, bool is_default = false); - size_t set_int_unique(size_t column_ndx, size_t row_ndx, int_fast64_t value); - void set_bool(size_t column_ndx, size_t row_ndx, bool value, bool is_default = false); - void set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value, bool is_default = false); - void set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value, bool is_default = false); - template - void set_enum(size_t column_ndx, size_t row_ndx, E value); - void set_float(size_t column_ndx, size_t row_ndx, float value, bool is_default = false); - void set_double(size_t column_ndx, size_t row_ndx, double value, bool is_default = false); - void set_string(size_t column_ndx, size_t row_ndx, StringData value, bool is_default = false); - size_t set_string_unique(size_t column_ndx, size_t row_ndx, StringData value); - void set_binary(size_t column_ndx, size_t row_ndx, BinaryData value, bool is_default = false); - void set_mixed(size_t column_ndx, size_t row_ndx, Mixed value, bool is_default = false); - void set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx, bool is_default = false); - void nullify_link(size_t column_ndx, size_t row_ndx); - void set_null(size_t column_ndx, size_t row_ndx, bool is_default = false); - void set_null_unique(size_t col_ndx, size_t row_ndx); - - // Sync needs to store blobs bigger than 16 M. This function can be used for that. Data should be read - // out again using the get_binary_at() function. Should not be used for user data as normal get_binary() - // will just return null if the data is bigger than the limit. - void set_binary_big(size_t column_ndx, size_t row_ndx, BinaryData value, bool is_default = false); - - void add_int(size_t column_ndx, size_t row_ndx, int_fast64_t value); - - void insert_substring(size_t col_ndx, size_t row_ndx, size_t pos, StringData); - void remove_substring(size_t col_ndx, size_t row_ndx, size_t pos, size_t substring_size = realm::npos); - - //@} - - /// Assumes that the specified column is a subtable column (in - /// particular, not a mixed column) and that the specified table - /// has a spec that is compatible with that column, that is, the - /// number of columns must be the same, and corresponding columns - /// must have identical data types (as returned by - /// get_column_type()). - void set_subtable(size_t col_ndx, size_t row_ndx, const Table*); - void set_mixed_subtable(size_t col_ndx, size_t row_ndx, const Table*); - - - // Sub-tables (works on columns whose type is either 'subtable' or - // 'mixed', for a value in a mixed column that is not a subtable, - // get_subtable() returns null, get_subtable_size() returns zero, - // and clear_subtable() replaces the value with an empty table.) - // Currently, subtables of subtables are not supported. - TableRef get_subtable(size_t column_ndx, size_t row_ndx); - ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; - size_t get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept; - void clear_subtable(size_t column_ndx, size_t row_ndx); - - // Backlinks - size_t get_backlink_count(size_t row_ndx, bool only_strong_links = false) const noexcept; - size_t get_backlink_count(size_t row_ndx, const Table& origin, size_t origin_col_ndx) const noexcept; - size_t get_backlink(size_t row_ndx, const Table& origin, size_t origin_col_ndx, size_t backlink_ndx) const - noexcept; - - - //@{ - - /// If this accessor is attached to a subtable, then that subtable has a - /// parent table, and the subtable either resides in a column of type - /// `table` or of type `mixed` in that parent. In that case - /// get_parent_table() returns a reference to the accessor associated with - /// the parent, and get_parent_row_index() returns the index of the row in - /// which the subtable resides. In all other cases (free-standing and - /// group-level tables), get_parent_table() returns null and - /// get_parent_row_index() returns realm::npos. - /// - /// If this accessor is attached to a subtable, and \a column_ndx_out is - /// specified, then `*column_ndx_out` is set to the index of the column of - /// the parent table in which the subtable resides. If this accessor is not - /// attached to a subtable, then `*column_ndx_out` will retain its original - /// value upon return. - - TableRef get_parent_table(size_t* column_ndx_out = nullptr) noexcept; - ConstTableRef get_parent_table(size_t* column_ndx_out = nullptr) const noexcept; - size_t get_parent_row_index() const noexcept; - - //@} - - - /// Only group-level unordered tables can be used as origins or targets of - /// links. - bool is_group_level() const noexcept; - - /// If this table is a group-level table, then this function returns the - /// index of this table within the group. Otherwise it returns realm::npos. - size_t get_index_in_group() const noexcept; - - // Aggregate functions - size_t count_int(size_t column_ndx, int64_t value) const; - size_t count_string(size_t column_ndx, StringData value) const; - size_t count_float(size_t column_ndx, float value) const; - size_t count_double(size_t column_ndx, double value) const; - - int64_t sum_int(size_t column_ndx) const; - double sum_float(size_t column_ndx) const; - double sum_double(size_t column_ndx) const; - int64_t maximum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; - float maximum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; - double maximum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; - OldDateTime maximum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; - Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; - int64_t minimum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; - float minimum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; - double minimum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; - OldDateTime minimum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; - Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; - double average_int(size_t column_ndx, size_t* value_count = nullptr) const; - double average_float(size_t column_ndx, size_t* value_count = nullptr) const; - double average_double(size_t column_ndx, size_t* value_count = nullptr) const; - - // Searching - template - size_t find_first(size_t column_ndx, T value) const; - - size_t find_first_link(size_t target_row_index) const; - size_t find_first_int(size_t column_ndx, int64_t value) const; - size_t find_first_bool(size_t column_ndx, bool value) const; - size_t find_first_olddatetime(size_t column_ndx, OldDateTime value) const; - size_t find_first_timestamp(size_t column_ndx, Timestamp value) const; - size_t find_first_float(size_t column_ndx, float value) const; - size_t find_first_double(size_t column_ndx, double value) const; - size_t find_first_string(size_t column_ndx, StringData value) const; - size_t find_first_binary(size_t column_ndx, BinaryData value) const; - size_t find_first_null(size_t column_ndx) const; - - TableView find_all_link(size_t target_row_index); - ConstTableView find_all_link(size_t target_row_index) const; - TableView find_all_int(size_t column_ndx, int64_t value); - ConstTableView find_all_int(size_t column_ndx, int64_t value) const; - TableView find_all_bool(size_t column_ndx, bool value); - ConstTableView find_all_bool(size_t column_ndx, bool value) const; - TableView find_all_olddatetime(size_t column_ndx, OldDateTime value); - ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; - TableView find_all_float(size_t column_ndx, float value); - ConstTableView find_all_float(size_t column_ndx, float value) const; - TableView find_all_double(size_t column_ndx, double value); - ConstTableView find_all_double(size_t column_ndx, double value) const; - TableView find_all_string(size_t column_ndx, StringData value); - ConstTableView find_all_string(size_t column_ndx, StringData value) const; - TableView find_all_binary(size_t column_ndx, BinaryData value); - ConstTableView find_all_binary(size_t column_ndx, BinaryData value) const; - TableView find_all_null(size_t column_ndx); - ConstTableView find_all_null(size_t column_ndx) const; - - /// The following column types are supported: String, Integer, OldDateTime, Bool - TableView get_distinct_view(size_t column_ndx); - ConstTableView get_distinct_view(size_t column_ndx) const; - - TableView get_sorted_view(size_t column_ndx, bool ascending = true); - ConstTableView get_sorted_view(size_t column_ndx, bool ascending = true) const; - - TableView get_sorted_view(SortDescriptor order); - ConstTableView get_sorted_view(SortDescriptor order) const; - - TableView get_range_view(size_t begin, size_t end); - ConstTableView get_range_view(size_t begin, size_t end) const; - - TableView get_backlink_view(size_t row_ndx, Table* src_table, size_t src_col_ndx); - - - // Pivot / aggregate operation types. Experimental! Please do not document method publicly. - enum AggrType { - aggr_count, - aggr_sum, - aggr_avg, - aggr_min, - aggr_max, - }; - - // Simple pivot aggregate method. Experimental! Please do not document method publicly. - void aggregate(size_t group_by_column, size_t aggr_column, AggrType op, Table& result, - const IntegerColumn* viewrefs = nullptr) const; - - /// Report the current versioning counter for the table. The versioning counter is guaranteed to - /// change when the contents of the table changes after advance_read() or promote_to_write(), or - /// immediately after calls to methods which change the table. The term "change" means "change of - /// value": The storage layout of the table may change, for example due to optimization, but this - /// is not considered a change of a value. This means that you *cannot* use a non-changing version - /// count to indicate that object addresses (e.g. strings, binary data) remain the same. - /// The versioning counter *may* change (but is not required to do so) when another table linked - /// from this table, or linking to this table, is changed. The version counter *may* also change - /// without any apparent reason. - uint_fast64_t get_version_counter() const noexcept; - -private: - template - TableView find_all(size_t column_ndx, T value); - -public: - //@{ - /// Find the lower/upper bound according to a column that is - /// already sorted in ascending order. - /// - /// For an integer column at index 0, and an integer value '`v`', - /// lower_bound_int(0,v) returns the index '`l`' of the first row - /// such that `get_int(0,l) ≥ v`, and upper_bound_int(0,v) - /// returns the index '`u`' of the first row such that - /// `get_int(0,u) > v`. In both cases, if no such row is found, - /// the returned value is the number of rows in the table. - /// - /// 3 3 3 4 4 4 5 6 7 9 9 9 - /// ^ ^ ^ ^ ^ - /// | | | | | - /// | | | | -- Lower and upper bound of 15 - /// | | | | - /// | | | -- Lower and upper bound of 8 - /// | | | - /// | | -- Upper bound of 4 - /// | | - /// | -- Lower bound of 4 - /// | - /// -- Lower and upper bound of 1 - /// - /// These functions are similar to std::lower_bound() and - /// std::upper_bound(). - /// - /// The string versions assume that the column is sorted according - /// to StringData::operator<(). - size_t lower_bound_int(size_t column_ndx, int64_t value) const noexcept; - size_t upper_bound_int(size_t column_ndx, int64_t value) const noexcept; - size_t lower_bound_bool(size_t column_ndx, bool value) const noexcept; - size_t upper_bound_bool(size_t column_ndx, bool value) const noexcept; - size_t lower_bound_float(size_t column_ndx, float value) const noexcept; - size_t upper_bound_float(size_t column_ndx, float value) const noexcept; - size_t lower_bound_double(size_t column_ndx, double value) const noexcept; - size_t upper_bound_double(size_t column_ndx, double value) const noexcept; - size_t lower_bound_string(size_t column_ndx, StringData value) const noexcept; - size_t upper_bound_string(size_t column_ndx, StringData value) const noexcept; - //@} - - // Queries - // Using where(tv) is the new method to perform queries on TableView. The 'tv' can have any order; it does not - // need to be sorted, and, resulting view retains its order. - Query where(TableViewBase* tv = nullptr) - { - return Query(*this, tv); - } - - // FIXME: We need a ConstQuery class or runtime check against modifications in read transaction. - Query where(TableViewBase* tv = nullptr) const - { - return Query(*this, tv); - } - - // Perform queries on a LinkView. The returned Query holds a reference to lv. - Query where(const LinkViewRef& lv) - { - return Query(*this, lv); - } - - //@{ - /// WARNING: The link() and backlink() methods will alter a state on the Table object and return a reference to itself. - /// Be aware if assigning the return value of link() to a variable; this might be an error! - - /// This is an error: - - /// Table& cats = owners->link(1); - /// auto& dogs = owners->link(2); - - /// Query q = person_table->where() - /// .and_query(cats.column(5).equal("Fido")) - /// .Or() - /// .and_query(dogs.column(6).equal("Meowth")); - - /// Instead, do this: - - /// Query q = owners->where() - /// .and_query(person_table->link(1).column(5).equal("Fido")) - /// .Or() - /// .and_query(person_table->link(2).column(6).equal("Meowth")); - - /// The two calls to link() in the errorneous example will append the two values 0 and 1 to an internal vector in the - /// owners table, and we end up with three references to that same table: owners, cats and dogs. They are all the same - /// table, its vector has the values {0, 1}, so a query would not make any sense. - Table& link(size_t link_column); - Table& backlink(const Table& origin, size_t origin_col_ndx); - //@} - - // Optimizing. enforce == true will enforce enumeration of all string columns; - // enforce == false will auto-evaluate if they should be enumerated or not - void optimize(bool enforce = false); - - /// Write this table (or a slice of this table) to the specified - /// output stream. - /// - /// The output will have the same format as any other Realm - /// database file, such as those produced by Group::write(). In - /// this case, however, the resulting database file will contain - /// exactly one table, and that table will contain only the - /// specified slice of the source table (this table). - /// - /// The new table will always have the same dynamic type (see - /// Descriptor) as the source table (this table), and unless it is - /// overridden (\a override_table_name), the new table will have - /// the same name as the source table (see get_name()). Indexes - /// (see add_search_index()) will not be carried over to the new - /// table. - /// - /// \param out The destination output stream buffer. - /// - /// \param offset Index of first row to include (if `slice_size > - /// 0`). Must be less than, or equal to size(). - /// - /// \param slice_size Number of rows to include. May be zero. If - /// `slice_size > size() - offset`, then the effective size of - /// the written slice will be `size() - offset`. - /// - /// \param override_table_name Custom name to write out instead of - /// the actual table name. - /// - /// \throw std::out_of_range If `offset > size()`. - /// - /// FIXME: While this function does provided a maximally efficient - /// way of serializing part of a table, it offers little in terms - /// of general utility. This is unfortunate, because it pulls - /// quite a large amount of code into the core library to support - /// it. - void write(std::ostream& out, size_t offset = 0, size_t slice_size = npos, - StringData override_table_name = StringData()) const; - - // Conversion - void to_json(std::ostream& out, size_t link_depth = 0, - std::map* renames = nullptr) const; - void to_string(std::ostream& out, size_t limit = 500) const; - void row_to_string(size_t row_ndx, std::ostream& out) const; - - // Get a reference to this table - TableRef get_table_ref() - { - return TableRef(this); - } - ConstTableRef get_table_ref() const - { - return ConstTableRef(this); - } - - /// \brief Compare two tables for equality. - /// - /// Two tables are equal if they have equal descriptors - /// (`Descriptor::operator==()`) and equal contents. Equal descriptors imply - /// that the two tables have the same columns in the same order. Equal - /// contents means that the two tables must have the same number of rows, - /// and that for each row index, the two rows must have the same values in - /// each column. - /// - /// In mixed columns, both the value types and the values are required to be - /// equal. - /// - /// For a particular row and column, if the two values are themselves tables - /// (subtable and mixed columns) value equality implies a recursive - /// invocation of `Table::operator==()`. - bool operator==(const Table&) const; - - /// \brief Compare two tables for inequality. - /// - /// See operator==(). - bool operator!=(const Table& t) const; - - /// A subtable in a column of type 'table' (which shares descriptor with - /// other subtables in the same column) is initially in a degenerate state - /// where it takes up a minimal amout of space. This function returns true - /// if, and only if the table accessor is attached to such a subtable. This - /// function is mainly intended for debugging purposes. - bool is_degenerate() const; - - /// Compute the sum of the sizes in number of bytes of all the array nodes - /// that currently make up this table. See also - /// Group::compute_aggregate_byte_size(). - /// - /// If this table accessor is the detached state, this function returns - /// zero. - size_t compute_aggregated_byte_size() const noexcept; - - // Debug - void verify() const; -#ifdef REALM_DEBUG - void to_dot(std::ostream&, StringData title = StringData()) const; - void print() const; - MemStats stats() const; - void dump_node_structure() const; // To std::cerr (for GDB) - void dump_node_structure(std::ostream&, int level) const; -#endif - - class Parent; - using HandoverPatch = TableHandoverPatch; - static void generate_patch(const Table* ref, std::unique_ptr& patch); - static TableRef create_from_and_consume_patch(std::unique_ptr& patch, Group& group); - -protected: - /// Get a pointer to the accessor of the specified subtable. The - /// accessor will be created if it does not already exist. - /// - /// The returned table pointer must **always** end up being - /// wrapped in some instantiation of BasicTableRef<>. - TableRef get_subtable_tableref(size_t col_ndx, size_t row_ndx); - - /// See non-const get_subtable_tableref(). - ConstTableRef get_subtable_tableref(size_t col_ndx, size_t row_ndx) const; - - /// Compare the rows of two tables under the assumption that the two tables - /// have the same number of columns, and the same data type at each column - /// index (as expressed through the DataType enum). - bool compare_rows(const Table&) const; - - void set_into_mixed(Table* parent, size_t col_ndx, size_t row_ndx) const; - - void check_lists_are_empty(size_t row_ndx) const; - -private: - class SliceWriter; - - // Number of rows in this table - size_t m_size; - - // Underlying array structure. `m_top` is in use only for root tables; that - // is, for tables with independent descriptor. `m_columns` contains a ref - // for each column and search index in order of the columns. A search index - // ref always occurs immediately after the ref of the column to which the - // search index belongs. - // - // A subtable column (a column of type `type_table`) is essentially just a - // column of 'refs' pointing to the root node of each subtable. - // - // To save space in the database file, a subtable in such a column always - // starts out in a degenerate form where nothing is allocated on its behalf, - // and a null 'ref' is stored in the corresponding slot of the column. A - // subtable remains in this degenerate state until the first row is added to - // the subtable. - // - // For this scheme to work, it must be (and is) possible to create a table - // accessor that refers to a degenerate subtable. A table accessor (instance - // of `Table`) refers to a degenerate subtable if, and only if `m_columns` - // is unattached. - // - // FIXME: The fact that `m_columns` may be detached means that many - // functions (even non-modifying functions) need to check for that before - // accessing the contents of the table. This incurs a runtime - // overhead. Consider whether this overhead can be eliminated by having - // `Table::m_columns` always attached to something, and then detect the - // degenerate state in a different way. - Array m_top; - Array m_columns; // 2nd slot in m_top (for root tables) - - // Management class for the spec object. Only if the table has an independent - // spec, the spec object should be deleted when the table object is deleted. - // If the table has a shared spec, the spec object is managed by the spec object - // of the containing table. - class SpecPtr { - public: - ~SpecPtr() - { - optionally_delete(); - } - void manage(Spec* ptr) - { - optionally_delete(); - m_p = ptr; - m_is_managed = true; - } - void detach() - { - if (m_is_managed) { - m_p->detach(); - } - } - SpecPtr& operator=(Spec* ptr) - { - optionally_delete(); - m_p = ptr; - m_is_managed = false; - return *this; - } - Spec* operator->() const - { - return m_p; - } - Spec* get() const - { - return m_p; - } - Spec& operator*() const - { - return *m_p; - } - operator bool() const - { - return m_p != nullptr; - } - bool is_managed() const - { - return m_is_managed; - } - - private: - Spec* m_p = nullptr; - bool m_is_managed = false; - - void optionally_delete() - { - if (m_is_managed) { - delete m_p; - } - } - }; - - SpecPtr m_spec; // 1st slot in m_top (for root tables) - - // Is guaranteed to be empty for a detached accessor. Otherwise it is empty - // when the table accessor is attached to a degenerate subtable (unattached - // `m_columns`), otherwise it contains precisely one column accessor for - // each column in the table, in order. - // - // In some cases an entry may be null. This is currently possible only in - // connection with Group::advance_transact(), but it means that several - // member functions must be prepared to handle these null entries; in - // particular, detach(), ~Table(), functions called on behalf of detach() - // and ~Table(), and functiones called on behalf of - // Group::advance_transact(). - typedef std::vector column_accessors; - column_accessors m_cols; - - mutable std::atomic m_ref_count; - - // If this table is a root table (has independent descriptor), - // then Table::m_descriptor refers to the accessor of its - // descriptor when, and only when the descriptor accessor - // exists. This is used to ensure that at most one descriptor - // accessor exists for each underlying descriptor at any given - // point in time. Subdescriptors are kept unique by means of a - // registry in the parent descriptor. Table::m_descriptor is - // always null for tables with shared descriptor. - mutable std::weak_ptr m_descriptor; - - // Table view instances - // Access needs to be protected by m_accessor_mutex - typedef std::vector views; - mutable views m_views; - - // Points to first bound row accessor, or is null if there are none. - mutable RowBase* m_row_accessors = nullptr; - - // Mutex which must be locked any time the row accessor chain or m_views is used - mutable util::Mutex m_accessor_mutex; - - // Used for queries: Items are added with link() method during buildup of query - mutable std::vector m_link_chain; - - /// Used only in connection with Group::advance_transact() and - /// Table::refresh_accessor_tree(). - mutable bool m_mark; - - mutable uint_fast64_t m_version; - - void erase_row(size_t row_ndx, bool is_move_last_over); - void batch_erase_rows(const IntegerColumn& row_indexes, bool is_move_last_over); - void do_remove(size_t row_ndx, bool broken_reciprocal_backlinks); - void do_move_last_over(size_t row_ndx, bool broken_reciprocal_backlinks); - void do_swap_rows(size_t row_ndx_1, size_t row_ndx_2); - void do_move_row(size_t from_ndx, size_t to_ndx); - void do_merge_rows(size_t row_ndx, size_t new_row_ndx); - void do_clear(bool broken_reciprocal_backlinks); - size_t do_set_link(size_t col_ndx, size_t row_ndx, size_t target_row_ndx); - template - size_t do_find_unique(ColType& col, size_t ndx, T&& value, bool& conflict); - template - size_t do_set_unique_null(ColType& col, size_t ndx, bool& conflict); - template - size_t do_set_unique(ColType& column, size_t row_ndx, T&& value, bool& conflict); - - void _add_search_index(size_t column_ndx); - void _remove_search_index(size_t column_ndx); - - void rebuild_search_index(size_t current_file_format_version); - - // Upgrades OldDateTime columns to Timestamp columns - void upgrade_olddatetime(); - - // Indicate that the current global state version has been "observed". Until this - // happens, bumping of the global version counter can be bypassed, as any query - // checking for a version change will see the older version change anyways. - // Also returns the table-local version. - uint64_t observe_version() const noexcept; - - /// Update the version of this table and all tables which have links to it. - /// This causes all views referring to those tables to go out of sync, so that - /// calls to sync_if_needed() will bring the view up to date by reexecuting the - /// query. - /// - /// \param bump_global chooses whether the global versioning counter must be - /// bumped first as part of the update. This is the normal mode of operation, - /// when a change is made to the table. When calling recursively (following links - /// or going to the parent table), the parameter should be set to false to correctly - /// prune traversal. - void bump_version(bool bump_global = true) const noexcept; - - /// Disable copying assignment. - /// - /// It could easily be implemented by calling assign(), but the - /// non-checking nature of the low-level dynamically typed API - /// makes it too risky to offer this feature as an - /// operator. - /// - /// FIXME: assign() has not yet been implemented, but the - /// intention is that it will copy the rows of the argument table - /// into this table after clearing the original contents, and for - /// target tables without a shared spec, it would also copy the - /// spec. For target tables with shared spec, it would be an error - /// to pass an argument table with an incompatible spec, but - /// assign() would not check for spec compatibility. This would - /// make it ideal as a basis for implementing operator=() for - /// typed tables. - Table& operator=(const Table&) = delete; - - /// Used when constructing an accessor whose lifetime is going to be managed - /// by reference counting. The lifetime of accessors of free-standing tables - /// allocated on the stack by the application is not managed by reference - /// counting, so that is a case where this tag must **not** be specified. - class ref_count_tag { - }; - - /// Create an uninitialized accessor whose lifetime is managed by reference - /// counting. - Table(ref_count_tag, Allocator&); - - void init(ref_type top_ref, ArrayParent*, size_t ndx_in_parent, bool skip_create_column_accessors = false); - void init(Spec* shared_spec, ArrayParent* parent_column, size_t parent_row_ndx); - - static void do_insert_column(Descriptor&, size_t col_ndx, DataType type, StringData name, - LinkTargetInfo& link_target_info, bool nullable = false); - static void do_insert_column_unless_exists(Descriptor&, size_t col_ndx, DataType type, StringData name, - LinkTargetInfo& link, bool nullable = false, - bool* was_inserted = nullptr); - static void do_erase_column(Descriptor&, size_t col_ndx); - static void do_rename_column(Descriptor&, size_t col_ndx, StringData name); - - static void do_add_search_index(Descriptor&, size_t col_ndx); - static void do_remove_search_index(Descriptor&, size_t col_ndx); - - struct InsertSubtableColumns; - struct EraseSubtableColumns; - struct RenameSubtableColumns; - - void insert_root_column(size_t col_ndx, DataType type, StringData name, LinkTargetInfo& link_target, - bool nullable = false); - void erase_root_column(size_t col_ndx); - void do_insert_root_column(size_t col_ndx, ColumnType, StringData name, bool nullable = false); - void do_erase_root_column(size_t col_ndx); - void do_set_link_type(size_t col_ndx, LinkType); - void insert_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx, size_t backlink_col_ndx); - void erase_backlink_column(size_t origin_table_ndx, size_t origin_col_ndx); - void update_link_target_tables(size_t old_col_ndx_begin, size_t new_col_ndx_begin); - void update_link_target_tables_after_column_move(size_t moved_from, size_t moved_to); - - struct SubtableUpdater { - virtual void update(const SubtableColumn&, Array& subcolumns) = 0; - virtual void update_accessor(Table&) = 0; - virtual ~SubtableUpdater() - { - } - }; - static void update_subtables(Descriptor&, SubtableUpdater*); - void update_subtables(const size_t* col_path_begin, const size_t* col_path_end, SubtableUpdater*); - - struct AccessorUpdater { - virtual void update(Table&) = 0; - virtual void update_parent(Table&) = 0; - virtual ~AccessorUpdater() - { - } - }; - void update_accessors(const size_t* col_path_begin, const size_t* col_path_end, AccessorUpdater&); - - void create_degen_subtab_columns(); - ColumnBase* create_column_accessor(ColumnType, size_t col_ndx, size_t ndx_in_parent); - void destroy_column_accessors() noexcept; - - /// Called in the context of Group::commit() to ensure that - /// attached table accessors stay valid across a commit. Please - /// note that this works only for non-transactional commits. Table - /// accessors obtained during a transaction are always detached - /// when the transaction ends. - void update_from_parent(size_t old_baseline) noexcept; - - // Support function for conversions - void to_string_header(std::ostream& out, std::vector& widths) const; - void to_string_row(size_t row_ndx, std::ostream& out, const std::vector& widths) const; - - // recursive methods called by to_json, to follow links - void to_json(std::ostream& out, size_t link_depth, std::map& renames, - std::vector& followed) const; - void to_json_row(size_t row_ndx, std::ostream& out, size_t link_depth, - std::map& renames, std::vector& followed) const; - void to_json_row(size_t row_ndx, std::ostream& out, size_t link_depth = 0, - std::map* renames = nullptr) const; - - // Detach accessor from underlying table. Caller must ensure that - // a reference count exists upon return, for example by obtaining - // an extra reference count before the call. - // - // This function puts this table accessor into the detached - // state. This detaches it from the underlying structure of array - // nodes. It also recursively detaches accessors for subtables, - // and the type descriptor accessor. When this function returns, - // is_attached() will return false. - // - // This function may be called for a table accessor that is - // already in the detached state (idempotency). - // - // It is also valid to call this function for a table accessor - // that has not yet been detached, but whose underlying structure - // of arrays have changed in an unpredictable/unknown way. This - // kind of change generally happens when a modifying table - // operation fails, and also when one transaction is ended and a - // new one is started. - void detach() noexcept; - - /// Detach and remove all attached row, link list, and subtable - /// accessors. This function does not discard the descriptor accessor, if - /// any, and it does not discard column accessors either. - void discard_child_accessors() noexcept; - - void discard_row_accessors() noexcept; - - // Detach the type descriptor accessor if it exists. - void discard_desc_accessor() noexcept; - - void bind_ptr() const noexcept; - void unbind_ptr() const noexcept; - bool has_references() const noexcept; - - void register_view(const TableViewBase* view); - void unregister_view(const TableViewBase* view) noexcept; - void move_registered_view(const TableViewBase* old_addr, const TableViewBase* new_addr) noexcept; - void discard_views() noexcept; - - void register_row_accessor(RowBase*) const noexcept; - void unregister_row_accessor(RowBase*) const noexcept; - void do_unregister_row_accessor(RowBase*) const noexcept; - - class UnbindGuard; - - ColumnType get_real_column_type(size_t column_ndx) const noexcept; - - /// If this table is a group-level table, the parent group is returned, - /// otherwise null is returned. - Group* get_parent_group() const noexcept; - - const ColumnBase& get_column_base(size_t column_ndx) const noexcept; - ColumnBase& get_column_base(size_t column_ndx); - - const ColumnBaseWithIndex& get_column_base_indexed(size_t ndx) const noexcept; - ColumnBaseWithIndex& get_column_base_indexed(size_t ndx); - - template - T& get_column(size_t ndx); - - template - const T& get_column(size_t ndx) const noexcept; - - IntegerColumn& get_column(size_t column_ndx); - const IntegerColumn& get_column(size_t column_ndx) const noexcept; - IntNullColumn& get_column_int_null(size_t column_ndx); - const IntNullColumn& get_column_int_null(size_t column_ndx) const noexcept; - FloatColumn& get_column_float(size_t column_ndx); - const FloatColumn& get_column_float(size_t column_ndx) const noexcept; - DoubleColumn& get_column_double(size_t column_ndx); - const DoubleColumn& get_column_double(size_t column_ndx) const noexcept; - StringColumn& get_column_string(size_t column_ndx); - const StringColumn& get_column_string(size_t column_ndx) const noexcept; - BinaryColumn& get_column_binary(size_t column_ndx); - const BinaryColumn& get_column_binary(size_t column_ndx) const noexcept; - StringEnumColumn& get_column_string_enum(size_t column_ndx); - const StringEnumColumn& get_column_string_enum(size_t column_ndx) const noexcept; - SubtableColumn& get_column_table(size_t column_ndx); - const SubtableColumn& get_column_table(size_t column_ndx) const noexcept; - MixedColumn& get_column_mixed(size_t column_ndx); - const MixedColumn& get_column_mixed(size_t column_ndx) const noexcept; - TimestampColumn& get_column_timestamp(size_t column_ndx); - const TimestampColumn& get_column_timestamp(size_t column_ndx) const noexcept; - const LinkColumnBase& get_column_link_base(size_t ndx) const noexcept; - LinkColumnBase& get_column_link_base(size_t ndx); - const LinkColumn& get_column_link(size_t ndx) const noexcept; - LinkColumn& get_column_link(size_t ndx); - const LinkListColumn& get_column_link_list(size_t ndx) const noexcept; - LinkListColumn& get_column_link_list(size_t ndx); - const BacklinkColumn& get_column_backlink(size_t ndx) const noexcept; - BacklinkColumn& get_column_backlink(size_t ndx); - - void verify_column(size_t col_ndx, const ColumnBase* col) const; - - void instantiate_before_change(); - void validate_column_type(const ColumnBase& col, ColumnType expected_type, size_t ndx) const; - - static size_t get_size_from_ref(ref_type top_ref, Allocator&) noexcept; - static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator&) noexcept; - - const Table* get_parent_table_ptr(size_t* column_ndx_out = nullptr) const noexcept; - Table* get_parent_table_ptr(size_t* column_ndx_out = nullptr) noexcept; - - /// Create an empty table with independent spec and return just - /// the reference to the underlying memory. - static ref_type create_empty_table(Allocator&); - - /// Create a column of the specified type, fill it with the - /// specified number of default values, and return just the - /// reference to the underlying memory. - static ref_type create_column(ColumnType column_type, size_t num_default_values, bool nullable, Allocator&); - - /// Construct a copy of the columns array of this table using the - /// specified allocator and return just the ref to that array. - /// - /// In the clone, no string column will be of the enumeration - /// type. - ref_type clone_columns(Allocator&) const; - - /// Construct a complete copy of this table (including its spec) - /// using the specified allocator and return just the ref to the - /// new top array. - ref_type clone(Allocator&) const; - - /// True for `col_type_Link` and `col_type_LinkList`. - static bool is_link_type(ColumnType) noexcept; - - void connect_opposite_link_columns(size_t link_col_ndx, Table& target_table, size_t backlink_col_ndx) noexcept; - - //@{ - - /// Cascading removal of strong links. - /// - /// cascade_break_backlinks_to() removes all backlinks pointing to the row - /// at \a row_ndx. Additionally, if this causes the number of **strong** - /// backlinks originating from a particular opposite row (target row of - /// corresponding forward link) to drop to zero, and that row is not already - /// in \a state.rows, then that row is added to \a state.rows, and - /// cascade_break_backlinks_to() is called recursively for it. This - /// operation is the first half of the cascading row removal operation. The - /// second half is performed by passing the resulting contents of \a - /// state.rows to remove_backlink_broken_rows(). - /// - /// Operations that trigger cascading row removal due to explicit removal of - /// one or more rows (the *initiating rows*), should add those rows to \a - /// rows initially, and then call cascade_break_backlinks_to() once for each - /// of them in turn. This is opposed to carrying out the explicit row - /// removals independently, which is also possible, but does require that - /// any initiating rows, that end up in \a state.rows due to link cycles, - /// are removed before passing \a state.rows to - /// remove_backlink_broken_rows(). In the case of clear(), where all rows of - /// a table are explicitly removed, it is better to use - /// cascade_break_backlinks_to_all_rows(), and then carry out the table - /// clearing as an independent step. For operations that trigger cascading - /// row removal for other reasons than explicit row removal, \a state.rows - /// must be empty initially, but cascade_break_backlinks_to() must still be - /// called for each of the initiating rows. - /// - /// When the last non-recursive invocation of cascade_break_backlinks_to() - /// returns, all forward links originating from a row in \a state.rows have - /// had their reciprocal backlinks removed, so remove_backlink_broken_rows() - /// does not perform reciprocal backlink removal at all. Additionally, all - /// remaining backlinks originating from rows in \a state.rows are - /// guaranteed to point to rows that are **not** in \a state.rows. This is - /// true because any backlink that was pointing to a row in \a state.rows - /// has been removed by one of the invocations of - /// cascade_break_backlinks_to(). The set of forward links, that correspond - /// to these remaining backlinks, is precisely the set of forward links that - /// need to be removed/nullified by remove_backlink_broken_rows(), which it - /// does by way of reciprocal forward link removal. Note also, that while - /// all the rows in \a state.rows can have remaining **weak** backlinks - /// originating from them, only the initiating rows in \a state.rows can - /// have remaining **strong** backlinks originating from them. This is true - /// because a non-initiating row is added to \a state.rows only when the - /// last backlink originating from it is lost. - /// - /// Each row removal is replicated individually (as opposed to one - /// replication instruction for the entire cascading operation). This is - /// done because it provides an easy way for Group::advance_transact() to - /// know which tables are affected by the cascade. Note that this has - /// several important consequences: First of all, the replication log - /// receiver must execute the row removal instructions in a non-cascading - /// fashion, meaning that there will be an asymmetry between the two sides - /// in how the effect of the cascade is brought about. While this is fine - /// for simple 1-to-1 replication, it may end up interfering badly with - /// *transaction merging*, when that feature is introduced. Imagine for - /// example that the cascade initiating operation gets canceled during - /// conflict resolution, but some, or all of the induced row removals get to - /// stay. That would break causal consistency. It is important, however, for - /// transaction merging that the cascaded row removals are explicitly - /// mentioned in the replication log, such that they can be used to adjust - /// row indexes during the *operational transform*. - /// - /// cascade_break_backlinks_to_all_rows() has the same affect as calling - /// cascade_break_backlinks_to() once for each row in the table. When - /// calling this function, \a state.stop_on_table must be set to the origin - /// table (origin table of corresponding forward links), and \a - /// state.stop_on_link_list_column must be null. - /// - /// It is immaterial which table remove_backlink_broken_rows() is called on, - /// as long it that table is in the same group as the removed rows. - - void cascade_break_backlinks_to(size_t row_ndx, CascadeState& state); - void cascade_break_backlinks_to_all_rows(CascadeState& state); - void remove_backlink_broken_rows(const CascadeState&); - - //@} - - /// Used by query. Follows chain of link columns and returns final target table - const Table* get_link_chain_target(const std::vector& link_chain) const; - - /// Remove the specified row by the 'move last over' method. - void do_move_last_over(size_t row_ndx); - - // Precondition: 1 <= end - begin - size_t* record_subtable_path(size_t* begin, size_t* end) const noexcept; - - /// Check if an accessor exists for the specified subtable. If it does, - /// return a pointer to it, otherwise return null. This function assumes - /// that the specified column index in a valid index into `m_cols` but does - /// not otherwise assume more than minimal accessor consistency (see - /// AccessorConsistencyLevels.) - TableRef get_subtable_accessor(size_t col_ndx, size_t row_ndx) noexcept; - - /// Unless the column accessor is missing, this function returns the - /// accessor for the target table of the specified link-type column. The - /// column accessor is said to be missing if `m_cols[col_ndx]` is null, and - /// this can happen only during certain operations such as the updating of - /// the accessor tree when a read transaction is advanced. Note that for - /// link type columns, the target table accessor exists when, and only when - /// the origin table accessor exists. This function assumes that the - /// specified column index in a valid index into `m_cols` and that the - /// column is a link-type column. Beyond that, it assume nothing more than - /// minimal accessor consistency (see AccessorConsistencyLevels.) - Table* get_link_target_table_accessor(size_t col_ndx) noexcept; - - void discard_subtable_accessor(size_t col_ndx, size_t row_ndx) noexcept; - - void adj_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; - void adj_acc_erase_row(size_t row_ndx) noexcept; - void adj_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; - void adj_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; - void adj_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; - - /// Adjust this table accessor and its subordinates after move_last_over() - /// (or its inverse). - /// - /// First, any row, subtable, or link list accessors registered as being at - /// \a to_row_ndx will be detached, as that row is assumed to have been - /// replaced. Next, any row, subtable, or link list accessors registered as - /// being at \a from_row_ndx, will be reregistered as being at \a - /// to_row_ndx, as the row at \a from_row_ndx is assumed to have been moved - /// to \a to_row_ndx. - /// - /// Crucially, if \a to_row_ndx is equal to \a from_row_ndx, then row, - /// subtable, or link list accessors at that row are **still detached**. - /// - /// Additionally, this function causes all link-adjacent tables to be marked - /// (dirty). Two tables are link-adjacent if one is the target table of a - /// link column of the other table. Note that this marking follows these - /// relations in both directions, but only to a depth of one. - /// - /// When this function is used in connection with move_last_over(), set \a - /// to_row_ndx to the index of the row to be removed, and set \a - /// from_row_ndx to the index of the last row in the table. As mentioned - /// earlier, this function can also be used in connection with the **inverse - /// of** move_last_over(), which is an operation that vacates a row by - /// moving its contents into a new last row of the table. In that case, set - /// \a to_row_ndx to one plus the index of the last row in the table, and - /// set \a from_row_ndx to the index of the row to be vacated. - /// - /// This function is used as part of Table::refresh_accessor_tree() to - /// promote the state of the accessors from Minimal Consistency into - /// Structural Correspondence, so it must be able to execute without - /// accessing the underlying array nodes. - void adj_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - - void adj_acc_clear_root_table() noexcept; - void adj_acc_clear_nonroot_table() noexcept; - void adj_row_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; - void adj_row_acc_erase_row(size_t row_ndx) noexcept; - void adj_row_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; - void adj_row_acc_move_row(size_t from_ndx, size_t to_ndx) noexcept; - void adj_row_acc_merge_rows(size_t old_row_ndx, size_t new_row_ndx) noexcept; - - /// Called by adj_acc_move_over() to adjust row accessors. - void adj_row_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - - void adj_insert_column(size_t col_ndx); - void adj_erase_column(size_t col_ndx) noexcept; - - bool is_marked() const noexcept; - void mark() noexcept; - void unmark() noexcept; - void recursive_mark() noexcept; - void mark_link_target_tables(size_t col_ndx_begin) noexcept; - void mark_opposite_link_tables() noexcept; - - Replication* get_repl() noexcept; - - void set_ndx_in_parent(size_t ndx_in_parent) noexcept; - - /// Refresh the part of the accessor tree that is rooted at this - /// table. Subtable accessors will be refreshed only if they are marked - /// (Table::m_mark), and this applies recursively to subtables of - /// subtables. All refreshed table accessors (including this one) will be - /// unmarked upon return. - /// - /// The following conditions are necessary and sufficient for the proper - /// operation of this function: - /// - /// - This table must be a group-level table, or a subtable. It must not be - /// a free-standing table (because a free-standing table has no parent). - /// - /// - The `index in parent` property is correct. The `index in parent` - /// property of the table is the `index in parent` property of - /// `m_columns` for subtables with shared descriptor, and the `index in - /// parent` property of `m_top` for all other tables. - /// - /// - If this table has shared descriptor, then the `index in parent` - /// property of the contained spec accessor is correct. - /// - /// - The parent accessor is in a valid state (already refreshed). If the - /// parent is a group, then the group accessor (excluding its table - /// accessors) must be in a valid state. If the parent is a table, then - /// the table accessor (excluding its subtable accessors) must be in a - /// valid state. - /// - /// - Every descendant subtable accessor is marked if it needs to be - /// refreshed, or if it has a descendant accessor that needs to be - /// refreshed. - /// - /// - This table accessor, as well as all its descendant accessors, are in - /// structural correspondence with the underlying node hierarchy whose - /// root ref is stored in the parent (see AccessorConsistencyLevels). - void refresh_accessor_tree(); - - void refresh_spec_accessor(); - - void refresh_column_accessors(size_t col_ndx_begin = 0); - - // Look for link columns starting from col_ndx_begin. - // If a link column is found, follow the link and update it's - // backlink column accessor if it is in different table. - void refresh_link_target_accessors(size_t col_ndx_begin = 0); - - bool is_cross_table_link_target() const noexcept; - std::recursive_mutex* get_parent_accessor_management_lock() const; -#ifdef REALM_DEBUG - void to_dot_internal(std::ostream&) const; -#endif - - friend class SubtableNode; - friend class _impl::TableFriend; - friend class Query; - friend class metrics::QueryInfo; - template - friend class util::bind_ptr; - template - friend class SimpleQuerySupport; - friend class LangBindHelper; - friend class TableViewBase; - template - friend class Columns; - friend class Columns; - friend class ParentNode; - template - friend class SequentialGetter; - friend struct util::serializer::SerialisationState; - friend class RowBase; - friend class LinksToNode; - friend class LinkMap; - friend class LinkView; - friend class Group; -}; - -class Table::Parent : public ArrayParent { -public: - ~Parent() noexcept override - { - } - -protected: - virtual StringData get_child_name(size_t child_ndx) const noexcept; - - /// If children are group-level tables, then this function returns the - /// group. Otherwise it returns null. - virtual Group* get_parent_group() noexcept; - - /// If children are subtables, then this function returns the - /// parent table. Otherwise it returns null. - /// - /// If \a column_ndx_out is not null, this function must assign the index of - /// the column within the parent table to `*column_ndx_out` when , and only - /// when this table parent is a column in a parent table. - virtual Table* get_parent_table(size_t* column_ndx_out = nullptr) noexcept; - - virtual Spec* get_subtable_spec() noexcept; - - /// Must be called whenever a child table accessor is about to be destroyed. - /// - /// Note that the argument is a pointer to the child Table rather than its - /// `ndx_in_parent` property. This is because only minimal accessor - /// consistency can be assumed by this function. - virtual void child_accessor_destroyed(Table* child) noexcept = 0; - - - virtual size_t* record_subtable_path(size_t* begin, size_t* end) noexcept; - virtual std::recursive_mutex* get_accessor_management_lock() noexcept = 0; - - friend class Table; -}; - - -// Implementation: - - -inline uint_fast64_t Table::get_version_counter() const noexcept -{ - return observe_version(); -} - -inline uint64_t Table::observe_version() const noexcept -{ - m_top.get_alloc().observe_version(); - return m_version; -} - -inline void Table::bump_version(bool bump_global) const noexcept -{ - if (bump_global) { - // This is only set on initial entry through an operation on the same - // table. recursive calls (via parent or via backlinks) must be done - // with bump_global=false. - m_top.get_alloc().bump_global_version(); - } - if (m_top.get_alloc().should_propagate_version(m_version)) { - if (const Table* parent = get_parent_table_ptr()) - parent->bump_version(false); - // Recurse through linked tables, use m_mark to avoid infinite recursion - for (auto& column_ptr : m_cols) { - // We may meet a null pointer in place of a backlink column, pending - // replacement with a new one. This can happen ONLY when creation of - // the corresponding forward link column in the origin table is - // pending as well. In this case it is ok to just ignore the zeroed - // backlink column, because the origin table is guaranteed to also - // be refreshed/marked dirty and hence have it's version bumped. - if (column_ptr != nullptr) - column_ptr->bump_link_origin_table_version(); - } - } -} - -inline void Table::remove(size_t row_ndx) -{ - bool is_move_last_over = false; - erase_row(row_ndx, is_move_last_over); // Throws -} - -inline void Table::move_last_over(size_t row_ndx) -{ - bool is_move_last_over = true; - erase_row(row_ndx, is_move_last_over); // Throws -} - -inline void Table::remove_last() -{ - if (!is_empty()) - remove(size() - 1); -} - -// A good place to start if you want to understand the memory ordering -// chosen for the operations below is http://preshing.com/20130922/acquire-and-release-fences/ -inline void Table::bind_ptr() const noexcept -{ - m_ref_count.fetch_add(1, std::memory_order_relaxed); -} - -inline void Table::unbind_ptr() const noexcept -{ - // The delete operation runs the destructor, and the destructor - // must always see all changes to the object being deleted. - // Within each thread, we know that unbind_ptr will always happen after - // any changes, so it is a convenient place to do a release. - // The release will then be observed by the acquire fence in - // the case where delete is actually called (the count reaches 0) - if (m_ref_count.fetch_sub(1, std::memory_order_release) != 1) { - return; - } - - std::atomic_thread_fence(std::memory_order_acquire); - - std::recursive_mutex* lock = get_parent_accessor_management_lock(); - if (lock) { - std::lock_guard lg(*lock); - if (m_ref_count == 0) - delete this; - } - else { - delete this; - } -} - -inline bool Table::has_references() const noexcept -{ - return m_ref_count.load() > 0; -} - -inline void Table::register_view(const TableViewBase* view) -{ - util::LockGuard lock(m_accessor_mutex); - // Casting away constness here - operations done on tableviews - // through m_views are all internal and preserving "some" kind - // of logical constness. - m_views.push_back(const_cast(view)); -} - -inline bool Table::is_attached() const noexcept -{ - // Note that it is not possible to tie the state of attachment of a table to - // the state of attachment of m_top, because tables with shared spec do not - // have a 'top' array. Neither is it possible to tie it to the state of - // attachment of m_columns, because subtables with shared spec start out in - // a degenerate form where they do not have a 'columns' array. For these - // reasons, it is neccessary to define the notion of attachment for a table - // as follows: A table is attached if, and ony if m_column stores a non-null - // parent pointer. This works because even for degenerate subtables, - // m_columns is initialized with the correct parent pointer. - return m_columns.has_parent(); -} - -inline StringData Table::get_name() const noexcept -{ - REALM_ASSERT(is_attached()); - const Array& real_top = m_top.is_attached() ? m_top : m_columns; - ArrayParent* parent = real_top.get_parent(); - if (!parent) - return StringData(""); - size_t index_in_parent = real_top.get_ndx_in_parent(); - REALM_ASSERT(dynamic_cast(parent)); - return static_cast(parent)->get_child_name(index_in_parent); -} - -inline size_t Table::get_column_count() const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_public_column_count(); -} - -inline StringData Table::get_column_name(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, get_column_count()); - return m_spec->get_column_name(ndx); -} - -inline size_t Table::get_column_index(StringData name) const noexcept -{ - REALM_ASSERT(is_attached()); - return m_spec->get_column_index(name); -} - -inline ColumnType Table::get_real_column_type(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_spec->get_column_count()); - return m_spec->get_column_type(ndx); -} - -inline DataType Table::get_column_type(size_t ndx) const noexcept -{ - REALM_ASSERT_3(ndx, <, m_spec->get_column_count()); - return m_spec->get_public_column_type(ndx); -} - -template -inline Col& Table::get_column(size_t ndx) -{ - ColumnBase& col = get_column_base(ndx); -#ifdef REALM_DEBUG - validate_column_type(col, col_type, ndx); -#endif - REALM_ASSERT(typeid(Col) == typeid(col)); - return static_cast(col); -} - -template -inline const Col& Table::get_column(size_t ndx) const noexcept -{ - const ColumnBase& col = get_column_base(ndx); -#ifdef REALM_DEBUG - validate_column_type(col, col_type, ndx); -#endif - REALM_ASSERT(typeid(Col) == typeid(col)); - return static_cast(col); -} - -inline bool Table::has_shared_type() const noexcept -{ - REALM_ASSERT(is_attached()); - return !m_top.is_attached(); -} - -inline void Table::verify_column(size_t col_ndx, const ColumnBase* col) const -{ - // Check if the column exists at the expected location - if (REALM_LIKELY(col_ndx < m_cols.size() && m_cols[col_ndx] == col)) - return; - // The column might be elsewhere in the list - for (auto c : m_cols) { - if (c == col) - return; - } - throw LogicError(LogicError::column_does_not_exist); -} - -class Table::UnbindGuard { -public: - UnbindGuard(Table* table) noexcept - : m_table(table) - { - } - - ~UnbindGuard() noexcept - { - if (m_table) - m_table->unbind_ptr(); - } - - Table& operator*() const noexcept - { - return *m_table; - } - - Table* operator->() const noexcept - { - return m_table; - } - - Table* get() const noexcept - { - return m_table; - } - - Table* release() noexcept - { - Table* table = m_table; - m_table = nullptr; - return table; - } - -private: - Table* m_table; -}; - - -inline Table::Table(Allocator& alloc) - : m_top(alloc) - , m_columns(alloc) -{ - m_ref_count = 1; // Explicitly managed lifetime - - ref_type ref = create_empty_table(alloc); // Throws - Parent* parent = nullptr; - size_t ndx_in_parent = 0; - init(ref, parent, ndx_in_parent); -} - -inline Table::Table(const Table& t, Allocator& alloc) - : m_top(alloc) - , m_columns(alloc) -{ - m_ref_count = 1; // Explicitly managed lifetime - - ref_type ref = t.clone(alloc); // Throws - Parent* parent = nullptr; - size_t ndx_in_parent = 0; - init(ref, parent, ndx_in_parent); -} - -inline Table::Table(ref_count_tag, Allocator& alloc) - : m_top(alloc) - , m_columns(alloc) -{ - m_ref_count = 0; // Lifetime managed by reference counting -} - -inline Allocator& Table::get_alloc() const -{ - return m_top.get_alloc(); -} - -inline TableRef Table::create(Allocator& alloc) -{ - std::unique_ptr
table(new Table(ref_count_tag(), alloc)); // Throws - ref_type ref = create_empty_table(alloc); // Throws - Parent* parent = nullptr; - size_t ndx_in_parent = 0; - table->init(ref, parent, ndx_in_parent); // Throws - return table.release()->get_table_ref(); -} - -inline TableRef Table::copy(Allocator& alloc) const -{ - std::unique_ptr
table(new Table(ref_count_tag(), alloc)); // Throws - ref_type ref = clone(alloc); // Throws - Parent* parent = nullptr; - size_t ndx_in_parent = 0; - table->init(ref, parent, ndx_in_parent); // Throws - return table.release()->get_table_ref(); -} - -// For use by queries -template -inline Columns Table::column(size_t column_ndx) -{ - std::vector link_chain = std::move(m_link_chain); - m_link_chain.clear(); - - // Check if user-given template type equals Realm type. Todo, we should clean up and reuse all our - // type traits (all the is_same() cases below). - const Table* table = get_link_chain_target(link_chain); - - realm::DataType ct = table->get_column_type(column_ndx); - if (std::is_same::value && ct != type_Int) - throw LogicError(LogicError::type_mismatch); - else if (std::is_same::value && ct != type_Bool) - throw LogicError(LogicError::type_mismatch); - else if (std::is_same::value && ct != type_OldDateTime) - throw LogicError(LogicError::type_mismatch); - else if (std::is_same::value && ct != type_Float) - throw LogicError(LogicError::type_mismatch); - else if (std::is_same::value && ct != type_Double) - throw LogicError(LogicError::type_mismatch); - - if (std::is_same::value || std::is_same::value || std::is_same::value) { - link_chain.push_back(column_ndx); - } - - return Columns(column_ndx, this, std::move(link_chain)); -} - -template -inline Columns Table::column(const Table& origin, size_t origin_col_ndx) -{ - static_assert(std::is_same::value, ""); - - size_t origin_table_ndx = origin.get_index_in_group(); - const Table& current_target_table = *get_link_chain_target(m_link_chain); - size_t backlink_col_ndx = current_target_table.m_spec->find_backlink_column(origin_table_ndx, origin_col_ndx); - - std::vector link_chain = std::move(m_link_chain); - m_link_chain.clear(); - link_chain.push_back(backlink_col_ndx); - - return Columns(backlink_col_ndx, this, std::move(link_chain)); -} - -template -inline BacklinkCount Table::get_backlink_count() -{ - std::vector link_chain = std::move(m_link_chain); - m_link_chain.clear(); - return BacklinkCount(this, std::move(link_chain)); -} - -template -SubQuery Table::column(size_t column_ndx, Query subquery) -{ - static_assert(std::is_same::value, "A subquery must involve a link list or backlink column"); - return SubQuery(column(column_ndx), std::move(subquery)); -} - -template -SubQuery Table::column(const Table& origin, size_t origin_col_ndx, Query subquery) -{ - static_assert(std::is_same::value, "A subquery must involve a link list or backlink column"); - return SubQuery(column(origin, origin_col_ndx), std::move(subquery)); -} - -inline Table& Table::link(size_t link_column) -{ - m_link_chain.push_back(link_column); - return *this; -} - -inline Table& Table::backlink(const Table& origin, size_t origin_col_ndx) -{ - size_t origin_table_ndx = origin.get_index_in_group(); - const Table& current_target_table = *get_link_chain_target(m_link_chain); - size_t backlink_col_ndx = current_target_table.m_spec->find_backlink_column(origin_table_ndx, origin_col_ndx); - return link(backlink_col_ndx); -} - -inline bool Table::is_empty() const noexcept -{ - return m_size == 0; -} - -inline size_t Table::size() const noexcept -{ - return m_size; -} - -inline Table::RowExpr Table::get(size_t row_ndx) noexcept -{ - REALM_ASSERT_3(row_ndx, <, size()); - return RowExpr(this, row_ndx); -} - -inline Table::ConstRowExpr Table::get(size_t row_ndx) const noexcept -{ - REALM_ASSERT_3(row_ndx, <, size()); - return ConstRowExpr(this, row_ndx); -} - -inline Table::RowExpr Table::front() noexcept -{ - return get(0); -} - -inline Table::ConstRowExpr Table::front() const noexcept -{ - return get(0); -} - -inline Table::RowExpr Table::back() noexcept -{ - return get(m_size - 1); -} - -inline Table::ConstRowExpr Table::back() const noexcept -{ - return get(m_size - 1); -} - -inline Table::RowExpr Table::operator[](size_t row_ndx) noexcept -{ - return get(row_ndx); -} - -inline Table::ConstRowExpr Table::operator[](size_t row_ndx) const noexcept -{ - return get(row_ndx); -} - -inline size_t Table::add_empty_row(size_t num_rows) -{ - size_t row_ndx = m_size; - insert_empty_row(row_ndx, num_rows); // Throws - return row_ndx; // Return index of first new row -} - -inline ConstTableRef Table::get_subtable_tableref(size_t col_ndx, size_t row_ndx) const -{ - return const_cast(this)->get_subtable_tableref(col_ndx, row_ndx); // Throws -} - -inline bool Table::is_null_link(size_t col_ndx, size_t row_ndx) const noexcept -{ - return get_link(col_ndx, row_ndx) == realm::npos; -} - -inline ConstTableRef Table::get_link_target(size_t col_ndx) const noexcept -{ - return const_cast(this)->get_link_target(col_ndx); -} - -template -inline void Table::set_enum(size_t column_ndx, size_t row_ndx, E value) -{ - set_int(column_ndx, row_ndx, value); -} - -inline void Table::nullify_link(size_t col_ndx, size_t row_ndx) -{ - set_link(col_ndx, row_ndx, realm::npos); -} - -inline TableRef Table::get_subtable(size_t column_ndx, size_t row_ndx) -{ - return get_subtable_tableref(column_ndx, row_ndx); -} - -inline ConstTableRef Table::get_subtable(size_t column_ndx, size_t row_ndx) const -{ - return get_subtable_tableref(column_ndx, row_ndx); -} - -inline ConstTableRef Table::get_parent_table(size_t* column_ndx_out) const noexcept -{ - return ConstTableRef(get_parent_table_ptr(column_ndx_out)); -} - -inline TableRef Table::get_parent_table(size_t* column_ndx_out) noexcept -{ - return TableRef(get_parent_table_ptr(column_ndx_out)); -} - -inline bool Table::is_group_level() const noexcept -{ - return bool(get_parent_group()); -} - -inline bool Table::operator==(const Table& t) const -{ - return *m_spec == *t.m_spec && compare_rows(t); // Throws -} - -inline bool Table::operator!=(const Table& t) const -{ - return !(*this == t); // Throws -} - -inline bool Table::is_degenerate() const -{ - if (!is_attached()) { - throw LogicError{LogicError::detached_accessor}; - } - - return !m_columns.is_attached(); -} - -inline void Table::set_into_mixed(Table* parent, size_t col_ndx, size_t row_ndx) const -{ - parent->set_mixed_subtable(col_ndx, row_ndx, this); -} - -inline size_t Table::get_size_from_ref(ref_type top_ref, Allocator& alloc) noexcept -{ - const char* top_header = alloc.translate(top_ref); - std::pair p = Array::get_two(top_header, 0); - ref_type spec_ref = to_ref(p.first), columns_ref = to_ref(p.second); - return get_size_from_ref(spec_ref, columns_ref, alloc); -} - -inline Table* Table::get_parent_table_ptr(size_t* column_ndx_out) noexcept -{ - const Table* parent = const_cast(this)->get_parent_table_ptr(column_ndx_out); - return const_cast(parent); -} - -inline bool Table::is_link_type(ColumnType col_type) noexcept -{ - return col_type == col_type_Link || col_type == col_type_LinkList; -} - -inline size_t* Table::record_subtable_path(size_t* begin, size_t* end) const noexcept -{ - const Array& real_top = m_top.is_attached() ? m_top : m_columns; - size_t index_in_parent = real_top.get_ndx_in_parent(); - REALM_ASSERT_3(begin, <, end); - *begin++ = index_in_parent; - ArrayParent* parent = real_top.get_parent(); - REALM_ASSERT(parent); - REALM_ASSERT(dynamic_cast(parent)); - return static_cast(parent)->record_subtable_path(begin, end); -} - -inline size_t* Table::Parent::record_subtable_path(size_t* begin, size_t*) noexcept -{ - return begin; -} - -inline bool Table::is_marked() const noexcept -{ - return m_mark; -} - -inline void Table::mark() noexcept -{ - m_mark = true; -} - -inline void Table::unmark() noexcept -{ - m_mark = false; -} - -inline Replication* Table::get_repl() noexcept -{ - return m_top.get_alloc().get_replication(); -} - -inline void Table::set_ndx_in_parent(size_t ndx_in_parent) noexcept -{ - if (m_top.is_attached()) { - // Root table (independent descriptor) - m_top.set_ndx_in_parent(ndx_in_parent); - } - else { - // Subtable with shared descriptor - m_columns.set_ndx_in_parent(ndx_in_parent); - } -} - -// Declare our explicit specializations so that the inline wrappers don't try -// to instantiate them -template<> int64_t Table::get(size_t, size_t) const noexcept; -template<> util::Optional Table::get>(size_t, size_t) const noexcept; -template<> bool Table::get(size_t, size_t) const noexcept; -template<> Optional Table::get>(size_t, size_t) const noexcept; -template<> float Table::get(size_t, size_t) const noexcept; -template<> util::Optional Table::get>(size_t, size_t) const noexcept; -template<> double Table::get(size_t, size_t) const noexcept; -template<> util::Optional Table::get>(size_t, size_t) const noexcept; -template<> OldDateTime Table::get(size_t, size_t) const noexcept; -template<> Timestamp Table::get(size_t, size_t) const noexcept; -template<> StringData Table::get(size_t, size_t) const noexcept; -template<> BinaryData Table::get(size_t, size_t) const noexcept; -template<> BinaryIterator Table::get(size_t, size_t) const noexcept; -template<> Mixed Table::get(size_t, size_t) const noexcept; - -template<> void Table::set(size_t, size_t, int64_t, bool); -template<> void Table::set(size_t, size_t, bool, bool); -template<> void Table::set(size_t, size_t, float, bool); -template<> void Table::set(size_t, size_t, double, bool); -template<> void Table::set(size_t, size_t, OldDateTime, bool); -template<> void Table::set(size_t, size_t, Timestamp, bool); -template<> void Table::set(size_t, size_t, StringData, bool); -template<> void Table::set(size_t, size_t, BinaryData, bool); -template<> void Table::set(size_t, size_t, Mixed, bool); -template<> void Table::set(size_t, size_t, null, bool); - -template<> size_t Table::set_unique(size_t, size_t, int64_t); -template<> size_t Table::set_unique(size_t, size_t, StringData); -template<> size_t Table::set_unique(size_t, size_t, null); - - -inline int64_t Table::get_int(size_t col_ndx, size_t ndx) const noexcept -{ - if (is_nullable(col_ndx)) - return get>(col_ndx, ndx).value_or(0); - else - return get(col_ndx, ndx); -} - -inline size_t Table::set_int_unique(size_t col_ndx, size_t ndx, int_fast64_t value) -{ - return set_unique(col_ndx, ndx, value); -} - -inline void Table::set_int(size_t col_ndx, size_t ndx, int_fast64_t value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline Timestamp Table::get_timestamp(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline void Table::set_timestamp(size_t col_ndx, size_t ndx, Timestamp value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline bool Table::get_bool(size_t col_ndx, size_t ndx) const noexcept -{ - if (is_nullable(col_ndx)) - return get>(col_ndx, ndx).value_or(false); - else - return get(col_ndx, ndx); -} - -inline void Table::set_bool(size_t col_ndx, size_t ndx, bool value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline OldDateTime Table::get_olddatetime(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline void Table::set_olddatetime(size_t col_ndx, size_t ndx, OldDateTime value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline float Table::get_float(size_t col_ndx, size_t ndx) const noexcept -{ - float f = get(col_ndx, ndx); - return null::is_null_float(f) ? 0.0f : f; -} - -inline void Table::set_float(size_t col_ndx, size_t ndx, float value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline double Table::get_double(size_t col_ndx, size_t ndx) const noexcept -{ - double d = get(col_ndx, ndx); - return null::is_null_float(d) ? 0.0 : d; -} - -inline void Table::set_double(size_t col_ndx, size_t ndx, double value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline StringData Table::get_string(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline void Table::set_string(size_t col_ndx, size_t ndx, StringData value, bool is_default) -{ - return set(col_ndx, ndx, value, is_default); -} - -inline size_t Table::set_string_unique(size_t col_ndx, size_t ndx, StringData value) -{ - return set_unique(col_ndx, ndx, value); -} - -inline BinaryData Table::get_binary(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline BinaryIterator Table::get_binary_iterator(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline void Table::set_binary(size_t col_ndx, size_t ndx, BinaryData value, bool is_default) -{ - set(col_ndx, ndx, value, is_default); -} - -inline Mixed Table::get_mixed(size_t col_ndx, size_t ndx) const noexcept -{ - return get(col_ndx, ndx); -} - -inline void Table::set_mixed(size_t col_ndx, size_t ndx, Mixed value, bool is_default) -{ - set(col_ndx, ndx, value, is_default); -} - -inline void Table::set_null(size_t col_ndx, size_t ndx, bool is_default) -{ - set(col_ndx, ndx, null(), is_default); -} - -inline void Table::set_null_unique(size_t col_ndx, size_t ndx) -{ - set_unique(col_ndx, ndx, null()); -} - - -// This class groups together information about the target of a link column -// This is not a valid link if the target table == nullptr -struct LinkTargetInfo { - LinkTargetInfo(Table* target = nullptr, size_t backlink_ndx = realm::npos) - : m_target_table(target) - , m_backlink_col_ndx(backlink_ndx) - { - } - bool is_valid() const - { - return (m_target_table != nullptr); - } - Table* m_target_table; - size_t m_backlink_col_ndx; // a value of npos indicates the backlink should be appended -}; - -// The purpose of this class is to give internal access to some, but -// not all of the non-public parts of the Table class. -class _impl::TableFriend { -public: - typedef Table::UnbindGuard UnbindGuard; - - static ref_type create_empty_table(Allocator& alloc) - { - return Table::create_empty_table(alloc); // Throws - } - - static ref_type clone(const Table& table, Allocator& alloc) - { - return table.clone(alloc); // Throws - } - - static ref_type clone_columns(const Table& table, Allocator& alloc) - { - return table.clone_columns(alloc); // Throws - } - - static Table* create_accessor(Allocator& alloc, ref_type top_ref, Table::Parent* parent, size_t ndx_in_parent) - { - std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws - table->init(top_ref, parent, ndx_in_parent); // Throws - return table.release(); - } - - static Table* create_accessor(Spec* shared_spec, Table::Parent* parent_column, size_t parent_row_ndx) - { - Allocator& alloc = shared_spec->get_alloc(); - std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws - table->init(shared_spec, parent_column, parent_row_ndx); // Throws - return table.release(); - } - - // Intended to be used only by Group::create_table_accessor() - static Table* create_incomplete_accessor(Allocator& alloc, ref_type top_ref, Table::Parent* parent, - size_t ndx_in_parent) - { - std::unique_ptr
table(new Table(Table::ref_count_tag(), alloc)); // Throws - bool skip_create_column_accessors = true; - table->init(top_ref, parent, ndx_in_parent, skip_create_column_accessors); // Throws - return table.release(); - } - - // Intended to be used only by Group::create_table_accessor() - static void complete_accessor(Table& table) - { - table.refresh_column_accessors(); // Throws - } - - static void set_top_parent(Table& table, ArrayParent* parent, size_t ndx_in_parent) noexcept - { - table.m_top.set_parent(parent, ndx_in_parent); - } - - static void update_from_parent(Table& table, size_t old_baseline) noexcept - { - table.update_from_parent(old_baseline); - } - - static void detach(Table& table) noexcept - { - table.detach(); - } - - static void discard_row_accessors(Table& table) noexcept - { - table.discard_row_accessors(); - } - - static void discard_child_accessors(Table& table) noexcept - { - table.discard_child_accessors(); - } - - static void discard_subtable_accessor(Table& table, size_t col_ndx, size_t row_ndx) noexcept - { - table.discard_subtable_accessor(col_ndx, row_ndx); - } - - static void bind_ptr(Table& table) noexcept - { - table.bind_ptr(); - } - - static void unbind_ptr(Table& table) noexcept - { - table.unbind_ptr(); - } - - static bool compare_rows(const Table& a, const Table& b) - { - return a.compare_rows(b); // Throws - } - - static size_t get_size_from_ref(ref_type ref, Allocator& alloc) noexcept - { - return Table::get_size_from_ref(ref, alloc); - } - - static size_t get_size_from_ref(ref_type spec_ref, ref_type columns_ref, Allocator& alloc) noexcept - { - return Table::get_size_from_ref(spec_ref, columns_ref, alloc); - } - - static Spec& get_spec(Table& table) noexcept - { - return *table.m_spec; - } - - static const Spec& get_spec(const Table& table) noexcept - { - return *table.m_spec; - } - - static ColumnBase& get_column(const Table& table, size_t col_ndx) - { - return *table.m_cols[col_ndx]; - } - - static void do_remove(Table& table, size_t row_ndx) - { - bool broken_reciprocal_backlinks = false; - table.do_remove(row_ndx, broken_reciprocal_backlinks); // Throws - } - - static void do_move_last_over(Table& table, size_t row_ndx) - { - bool broken_reciprocal_backlinks = false; - table.do_move_last_over(row_ndx, broken_reciprocal_backlinks); // Throws - } - - static void do_swap_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) - { - table.do_swap_rows(row_ndx_1, row_ndx_2); // Throws - } - - static void do_move_row(Table& table, size_t from_ndx, size_t to_ndx) - { - table.do_move_row(from_ndx, to_ndx); // Throws - } - - static void do_merge_rows(Table& table, size_t row_ndx, size_t new_row_ndx) - { - table.do_merge_rows(row_ndx, new_row_ndx); // Throws - } - - static void do_clear(Table& table) - { - bool broken_reciprocal_backlinks = false; - table.do_clear(broken_reciprocal_backlinks); // Throws - } - - static void do_set_link(Table& table, size_t col_ndx, size_t row_ndx, size_t target_row_ndx) - { - table.do_set_link(col_ndx, row_ndx, target_row_ndx); // Throws - } - - static size_t get_backlink_count(const Table& table, size_t row_ndx, bool only_strong_links) noexcept - { - return table.get_backlink_count(row_ndx, only_strong_links); - } - - static void cascade_break_backlinks_to(Table& table, size_t row_ndx, CascadeState& state) - { - table.cascade_break_backlinks_to(row_ndx, state); // Throws - } - - static void remove_backlink_broken_rows(Table& table, const CascadeState& rows) - { - table.remove_backlink_broken_rows(rows); // Throws - } - - static size_t* record_subtable_path(const Table& table, size_t* begin, size_t* end) noexcept - { - return table.record_subtable_path(begin, end); - } - - static void insert_column(Descriptor& desc, size_t column_ndx, DataType type, StringData name, - LinkTargetInfo& link, bool nullable = false) - { - Table::do_insert_column(desc, column_ndx, type, name, link, nullable); // Throws - } - - static void insert_column_unless_exists(Descriptor& desc, size_t column_ndx, DataType type, StringData name, - LinkTargetInfo link, bool nullable = false, bool* was_inserted = nullptr) - { - Table::do_insert_column_unless_exists(desc, column_ndx, type, name, link, nullable, was_inserted); // Throws - } - - static void erase_column(Descriptor& desc, size_t column_ndx) - { - Table::do_erase_column(desc, column_ndx); // Throws - } - - static void rename_column(Descriptor& desc, size_t column_ndx, StringData name) - { - Table::do_rename_column(desc, column_ndx, name); // Throws - } - - static void add_search_index(Descriptor& desc, size_t column_ndx) - { - Table::do_add_search_index(desc, column_ndx); // Throws - } - - static void remove_search_index(Descriptor& desc, size_t column_ndx) - { - Table::do_remove_search_index(desc, column_ndx); // Throws - } - - static void set_link_type(Table& table, size_t column_ndx, LinkType link_type) - { - table.do_set_link_type(column_ndx, link_type); // Throws - } - - static void erase_row(Table& table, size_t row_ndx, bool is_move_last_over) - { - table.erase_row(row_ndx, is_move_last_over); // Throws - } - - static void batch_erase_rows(Table& table, const IntegerColumn& row_indexes, bool is_move_last_over) - { - table.batch_erase_rows(row_indexes, is_move_last_over); // Throws - } - - static TableRef get_subtable_accessor(Table& table, size_t col_ndx, size_t row_ndx) noexcept - { - return table.get_subtable_accessor(col_ndx, row_ndx); - } - - static const Table* get_link_target_table_accessor(const Table& table, size_t col_ndx) noexcept - { - return const_cast(table).get_link_target_table_accessor(col_ndx); - } - - static Table* get_link_target_table_accessor(Table& table, size_t col_ndx) noexcept - { - return table.get_link_target_table_accessor(col_ndx); - } - - static void adj_acc_insert_rows(Table& table, size_t row_ndx, size_t num_rows) noexcept - { - table.adj_acc_insert_rows(row_ndx, num_rows); - } - - static void adj_acc_erase_row(Table& table, size_t row_ndx) noexcept - { - table.adj_acc_erase_row(row_ndx); - } - - static void adj_acc_swap_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) noexcept - { - table.adj_acc_swap_rows(row_ndx_1, row_ndx_2); - } - - static void adj_acc_move_row(Table& table, size_t from_ndx, size_t to_ndx) noexcept - { - table.adj_acc_move_row(from_ndx, to_ndx); - } - - static void adj_acc_merge_rows(Table& table, size_t row_ndx_1, size_t row_ndx_2) noexcept - { - table.adj_acc_merge_rows(row_ndx_1, row_ndx_2); - } - - static void adj_acc_move_over(Table& table, size_t from_row_ndx, size_t to_row_ndx) noexcept - { - table.adj_acc_move_over(from_row_ndx, to_row_ndx); - } - - static void adj_acc_clear_root_table(Table& table) noexcept - { - table.adj_acc_clear_root_table(); - } - - static void adj_acc_clear_nonroot_table(Table& table) noexcept - { - table.adj_acc_clear_nonroot_table(); - } - - static void adj_insert_column(Table& table, size_t col_ndx) - { - table.adj_insert_column(col_ndx); // Throws - } - - static void adj_add_column(Table& table) - { - size_t num_cols = table.m_cols.size(); - table.adj_insert_column(num_cols); // Throws - } - - static void adj_erase_column(Table& table, size_t col_ndx) noexcept - { - table.adj_erase_column(col_ndx); - } - - static bool is_marked(const Table& table) noexcept - { - return table.is_marked(); - } - - static void mark(Table& table) noexcept - { - table.mark(); - } - - static void unmark(Table& table) noexcept - { - table.unmark(); - } - - static void recursive_mark(Table& table) noexcept - { - table.recursive_mark(); - } - - static void mark_link_target_tables(Table& table, size_t col_ndx_begin) noexcept - { - table.mark_link_target_tables(col_ndx_begin); - } - - static void mark_opposite_link_tables(Table& table) noexcept - { - table.mark_opposite_link_tables(); - } - - static DescriptorRef get_root_table_desc_accessor(Table& root_table) noexcept - { - return root_table.m_descriptor.lock(); - } - - typedef Table::AccessorUpdater AccessorUpdater; - static void update_accessors(Table& table, const size_t* col_path_begin, const size_t* col_path_end, - AccessorUpdater& updater) - { - table.update_accessors(col_path_begin, col_path_end, updater); // Throws - } - - static void refresh_accessor_tree(Table& table) - { - table.refresh_accessor_tree(); // Throws - } - - static void refresh_spec_accessor(Table& table) - { - table.refresh_spec_accessor(); // Throws - } - - static void set_ndx_in_parent(Table& table, size_t ndx_in_parent) noexcept - { - table.set_ndx_in_parent(ndx_in_parent); - } - - static bool is_link_type(ColumnType type) noexcept - { - return Table::is_link_type(type); - } - - static void bump_version(Table& table, bool bump_global = true) noexcept - { - table.bump_version(bump_global); - } - - static bool is_cross_table_link_target(const Table& table) - { - return table.is_cross_table_link_target(); - } - - static Group* get_parent_group(const Table& table) noexcept - { - return table.get_parent_group(); - } - - static Replication* get_repl(Table& table) noexcept - { - return table.get_repl(); - } - - static void register_view(Table& table, const TableViewBase* view) - { - table.register_view(view); // Throws - } - - static void unregister_view(Table& table, const TableViewBase* view) noexcept - { - table.unregister_view(view); - } - - static bool has_references(const Table& table) noexcept - { - return table.has_references(); - } -}; - - -} // namespace realm - -#endif // REALM_TABLE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/table_ref.hpp b/Lesson14/Pods/Realm/include/core/realm/table_ref.hpp deleted file mode 100644 index 6e5c02b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/table_ref.hpp +++ /dev/null @@ -1,481 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_TABLE_REF_HPP -#define REALM_TABLE_REF_HPP - -#include -#include - -#include - -namespace realm { - - -class Table; - - -/// A reference-counting "smart pointer" for referring to table -/// accessors. -/// -/// The purpose of this smart pointer is to keep the referenced table -/// accessor alive for as long as anybody is referring to it, however, -/// for stack allocated table accessors, the lifetime is necessarily -/// determined by scope (see below). -/// -/// Please take note of the distinction between a "table" and a "table -/// accessor" here. A table accessor is an instance of `Table`, -/// and it may, or may not be attached to an -/// actual table at any specific point in time, but this state of -/// attachment of the accessor has nothing to do with the function of -/// the smart pointer. Also, in the rest of the documentation of this -/// class, whenever you see `Table::%foo`, you are supposed to read it -/// as, `Table::%foo`. -/// -/// -/// Table accessors are either created directly by an application via -/// a call to one of the public table constructors, or they are -/// created internally by the Realm library, such as when the -/// application calls Group::get_table(), Table::get_subtable(), or -/// Table::create(). -/// -/// Applications can safely assume that all table accessors, created -/// internally by the Realm library, have a lifetime that is managed -/// by reference counting. This means that the application can prolong -/// the lifetime of *such* table accessors indefinitely by holding on -/// to at least one smart pointer, but note that the guarantee of the -/// continued existence of the accessor, does not imply that the -/// accessor remains attached to the underlying table (see -/// Table::is_attached() for details). Accessors whose lifetime are -/// controlled by reference counting are destroyed exactly when the -/// reference count drops to zero. -/// -/// When an application creates a new table accessor by a direct call -/// to one of the public constructors, the lifetime of that table -/// accessor is *not*, and cannot be managed by reference -/// counting. This is true regardless of the way the accessor is -/// created (i.e., regardless of whether it is an automatic variable -/// on the stack, or created on the heap using `new`). However, for -/// convenience, but with one important caveat, it is still possible -/// to use smart pointers to refer to such accessors. The caveat is -/// that no smart pointers are allowed to refer to the accessor at the -/// point in time when its destructor is called. It is entirely the -/// responsibility of the application to ensure that this requirement -/// is met. Failing to do so, will result in undefined -/// behavior. Finally, please note that an application is always free -/// to use Table::create() as an alternative to creating free-standing -/// top-level tables on the stack, and that this is indeed neccessary -/// when fully reference counted lifetimes are required. -/// -/// So, at any time, and for any table accessor, an application can -/// call Table::get_table_ref() to obtain a smart pointer that refers -/// to that table, however, while that is always possible and safe, it -/// is not always possible to extend the lifetime of an accessor by -/// holding on to a smart pointer. The question of whether that is -/// possible, depends directly on the way the accessor was created. -/// -/// -/// Apart from keeping track of the number of references, these smart -/// pointers behaves almost exactly like regular pointers. In -/// particular, it is possible to dereference a TableRef and get a -/// `Table&` out of it, however, if you are not careful, this can -/// easily lead to dangling references: -/// -/// \code{.cpp} -/// -/// Table& sub_1 = *(table.get_subtable(0,0)); -/// sub_1.add_empty_row(); // Oops, sub_1 may be dangling! -/// -/// \endcode -/// -/// Whether `sub_1` is actually dangling in the example above will -/// depend on whether other references to the same subtable accessor -/// already exist, but it is never wise to rely in this. Here is a -/// safe and proper alternative: -/// -/// \code{.cpp} -/// -/// TableRef sub_2 = table.get_subtable(0,0); -/// sub_2.add_empty_row(); // Safe! -/// -/// void do_something(Table&); -/// do_something(*(table.get_subtable(0,0))); // Also safe! -/// -/// \endcode -/// -/// -/// \sa Table -/// \sa TableRef -template -class BasicTableRef : util::bind_ptr { -public: - constexpr BasicTableRef() noexcept - { - } - ~BasicTableRef() noexcept - { - } - - // Copy construct - BasicTableRef(const BasicTableRef& r) noexcept - : util::bind_ptr(r) - { - } - template - BasicTableRef(const BasicTableRef& r) noexcept - : util::bind_ptr(r) - { - } - - // Copy assign - BasicTableRef& operator=(const BasicTableRef&) noexcept; - template - BasicTableRef& operator=(const BasicTableRef&) noexcept; - - // Move construct - BasicTableRef(BasicTableRef&& r) noexcept - : util::bind_ptr(std::move(r)) - { - } - template - BasicTableRef(BasicTableRef&& r) noexcept - : util::bind_ptr(std::move(r)) - { - } - - // Move assign - BasicTableRef& operator=(BasicTableRef&&) noexcept; - template - BasicTableRef& operator=(BasicTableRef&&) noexcept; - - //@{ - /// Comparison - template - bool operator==(const BasicTableRef&) const noexcept; - - template - bool operator==(U*) const noexcept; - - template - bool operator!=(const BasicTableRef&) const noexcept; - - template - bool operator!=(U*) const noexcept; - - template - bool operator<(const BasicTableRef&) const noexcept; - - template - bool operator<(U*) const noexcept; - - template - bool operator>(const BasicTableRef&) const noexcept; - - template - bool operator>(U*) const noexcept; - - template - bool operator<=(const BasicTableRef&) const noexcept; - - template - bool operator<=(U*) const noexcept; - - template - bool operator>=(const BasicTableRef&) const noexcept; - - template - bool operator>=(U*) const noexcept; -//@} - -// Dereference -#ifdef __clang__ - // Clang has a bug that causes it to effectively ignore the 'using' declaration. - T& operator*() const noexcept - { - return util::bind_ptr::operator*(); - } -#else - using util::bind_ptr::operator*; -#endif - using util::bind_ptr::operator->; - - using util::bind_ptr::operator bool; - - T* get() const noexcept - { - return util::bind_ptr::get(); - } - void reset() noexcept - { - util::bind_ptr::reset(); - } - void reset(T* t) noexcept - { - util::bind_ptr::reset(t); - } - - void swap(BasicTableRef& r) noexcept - { - this->util::bind_ptr::swap(r); - } - friend void swap(BasicTableRef& a, BasicTableRef& b) noexcept - { - a.swap(b); - } - - template - friend BasicTableRef unchecked_cast(BasicTableRef
) noexcept; - - template - friend BasicTableRef unchecked_cast(BasicTableRef) noexcept; - -private: - template - struct GetRowAccType { - typedef void type; - }; - - typedef typename GetRowAccType::type RowAccessor; - -public: - /// Same as 'table[i]' where 'table' is the referenced table. - RowAccessor operator[](size_t i) const noexcept - { - return (*this->get())[i]; - } - - explicit BasicTableRef(T* t) noexcept - : util::bind_ptr(t) - { - } - - T* release() { return util::bind_ptr::release(); } -private: - friend class SubtableColumnBase; - friend class Table; - friend class Group; - - template - friend class BasicTableRef; - - typedef typename util::bind_ptr::casting_move_tag casting_move_tag; - template - BasicTableRef(BasicTableRef* r, casting_move_tag) noexcept - : util::bind_ptr(r, casting_move_tag()) - { - } -}; - - -typedef BasicTableRef
TableRef; -typedef BasicTableRef ConstTableRef; - - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const BasicTableRef& p) -{ - out << static_cast(&*p); - return out; -} - -template -inline BasicTableRef unchecked_cast(TableRef t) noexcept -{ - return BasicTableRef(&t, typename BasicTableRef::casting_move_tag()); -} - -template -inline BasicTableRef unchecked_cast(ConstTableRef t) noexcept -{ - return BasicTableRef(&t, typename BasicTableRef::casting_move_tag()); -} - - -//@{ -/// Comparison -template -bool operator==(T*, const BasicTableRef&) noexcept; -template -bool operator!=(T*, const BasicTableRef&) noexcept; -template -bool operator<(T*, const BasicTableRef&) noexcept; -template -bool operator>(T*, const BasicTableRef&) noexcept; -template -bool operator<=(T*, const BasicTableRef&) noexcept; -template -bool operator>=(T*, const BasicTableRef&) noexcept; -//@} - - -// Implementation: - -template -inline BasicTableRef& BasicTableRef::operator=(const BasicTableRef& r) noexcept -{ - this->util::bind_ptr::operator=(r); - return *this; -} - -template -template -inline BasicTableRef& BasicTableRef::operator=(const BasicTableRef& r) noexcept -{ - this->util::bind_ptr::operator=(r); - return *this; -} - -template -inline BasicTableRef& BasicTableRef::operator=(BasicTableRef&& r) noexcept -{ - this->util::bind_ptr::operator=(std::move(r)); - return *this; -} - -template -template -inline BasicTableRef& BasicTableRef::operator=(BasicTableRef&& r) noexcept -{ - this->util::bind_ptr::operator=(std::move(r)); - return *this; -} - -template -template -bool BasicTableRef::operator==(const BasicTableRef& p) const noexcept -{ - return get() == p.get(); -} - -template -template -bool BasicTableRef::operator==(U* p) const noexcept -{ - return get() == p; -} - -template -template -bool BasicTableRef::operator!=(const BasicTableRef& p) const noexcept -{ - return get() != p.get(); -} - -template -template -bool BasicTableRef::operator!=(U* p) const noexcept -{ - return get() != p; -} - -template -template -bool BasicTableRef::operator<(const BasicTableRef& p) const noexcept -{ - return get() < p.get(); -} - -template -template -bool BasicTableRef::operator<(U* p) const noexcept -{ - return get() < p; -} - -template -template -bool BasicTableRef::operator>(const BasicTableRef& p) const noexcept -{ - return get() > p.get(); -} - -template -template -bool BasicTableRef::operator>(U* p) const noexcept -{ - return get() > p; -} - -template -template -bool BasicTableRef::operator<=(const BasicTableRef& p) const noexcept -{ - return get() <= p.get(); -} - -template -template -bool BasicTableRef::operator<=(U* p) const noexcept -{ - return get() <= p; -} - -template -template -bool BasicTableRef::operator>=(const BasicTableRef& p) const noexcept -{ - return get() >= p.get(); -} - -template -template -bool BasicTableRef::operator>=(U* p) const noexcept -{ - return get() >= p; -} - -template -bool operator==(T* a, const BasicTableRef& b) noexcept -{ - return b == a; -} - -template -bool operator!=(T* a, const BasicTableRef& b) noexcept -{ - return b != a; -} - -template -bool operator<(T* a, const BasicTableRef& b) noexcept -{ - return b > a; -} - -template -bool operator>(T* a, const BasicTableRef& b) noexcept -{ - return b < a; -} - -template -bool operator<=(T* a, const BasicTableRef& b) noexcept -{ - return b >= a; -} - -template -bool operator>=(T* a, const BasicTableRef& b) noexcept -{ - return b <= a; -} - - -} // namespace realm - -#endif // REALM_TABLE_REF_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/table_view.hpp b/Lesson14/Pods/Realm/include/core/realm/table_view.hpp deleted file mode 100644 index 3989da0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/table_view.hpp +++ /dev/null @@ -1,1614 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_TABLE_VIEW_HPP -#define REALM_TABLE_VIEW_HPP - -#include -#include -#include -#include -#include - -namespace realm { - -// Views, tables and synchronization between them: -// -// Views are built through queries against either tables or another view. -// Views may be restricted to only hold entries provided by another view. -// this other view is called the "restricting view". -// Views may be sorted in ascending or descending order of values in one ore more columns. -// -// Views remember the query from which it was originally built. -// Views remember the table from which it was originally built. -// Views remember a restricting view if one was used when it was originally built. -// Views remember the sorting criteria (columns and direction) -// -// A view may be operated in one of two distinct modes: *reflective* and *imperative*. -// Sometimes the term "reactive" is used instead of "reflective" with the same meaning. -// -// Reflective views: -// - A reflective view *always* *reflect* the result of running the query. -// If the underlying tables or tableviews change, the reflective view changes as well. -// A reflective view may need to rerun the query it was generated from, a potentially -// costly operation which happens on demand. -// - It does not matter whether changes are explicitly done within the transaction, or -// occur implicitly as part of advance_read() or promote_to_write(). -// -// Imperative views: -// - An imperative view only *initially* holds the result of the query. An imperative -// view *never* reruns the query. To force the view to match it's query (by rerunning it), -// the view must be operated in reflective mode. -// An imperative view can be modified explicitly. References can be added, removed or -// changed. -// -// - In imperative mode, the references in the view tracks movement of the referenced data: -// If you delete an entry which is referenced from a view, said reference is detached, -// not removed. -// - It does not matter whether the delete is done in-line (as part of the current transaction), -// or if it is done implicitly as part of advance_read() or promote_to_write(). -// -// The choice between reflective and imperative views might eventually be represented by a -// switch on the tableview, but isn't yet. For now, clients (bindings) must call sync_if_needed() -// to get reflective behavior. -// -// Use cases: -// -// 1. Presenting data -// The first use case (and primary motivator behind the reflective view) is to just track -// and present the state of the database. In this case, the view is operated in reflective -// mode, it is not modified within the transaction, and it is not used to modify data in -// other parts of the database. -// -// 2. Handover -// The second use case is "handover." The implicit rerun of the query in our first use case -// may be too costly to be acceptable on the main thread. Instead you want to run the query -// on a worker thread, but display it on the main thread. To achieve this, you need two -// SharedGroups locked on to the same version of the database. If you have that, you can -// *handover* a view from one thread/SharedGroup to the other. -// -// Handover is a two-step procedure. First, the accessors are *exported* from one SharedGroup, -// called the sourcing group, then it is *imported* into another SharedGroup, called the -// receiving group. The thread associated with the sourcing SharedGroup will be -// responsible for the export operation, while the thread associated with the receiving -// SharedGroup will do the import operation. -// -// 3. Iterating a view and changing data -// The third use case (and a motivator behind the imperative view) is when you want -// to make changes to the database in accordance with a query result. Imagine you want to -// find all employees with a salary below a limit and raise their salaries to the limit (pseudocode): -// -// promote_to_write(); -// view = table.where().less_than(salary_column,limit).find_all(); -// for (size_t i = 0; i < view.size(); ++i) { -// view.set_int(salary_column, i, limit); -// // add this to get reflective mode: view.sync_if_needed(); -// } -// commit_and_continue_as_read(); -// -// This is idiomatic imperative code and it works if the view is operated in imperative mode. -// -// If the view is operated in reflective mode, the behaviour surprises most people: When the -// first salary is changed, the entry no longer fullfills the query, so it is dropped from the -// view implicitly. view[0] is removed, view[1] moves to view[0] and so forth. But the next -// loop iteration has i=1 and refers to view[1], thus skipping view[0]. The end result is that -// every other employee get a raise, while the others don't. -// -// 4. Iterating intermixed with implicit updates -// This leads us to use case 4, which is similar to use case 3, but uses promote_to_write() -// intermixed with iterating a view. This is actually quite important to some, who do not want -// to end up with a large write transaction. -// -// view = table.where().less_than(salary_column,limit).find_all(); -// for (size_t i = 0; i < view.size(); ++i) { -// promote_to_write(); -// view.set_int(salary_column, i, limit); -// commit_and_continue_as_write(); -// } -// -// Anything can happen at the call to promote_to_write(). The key question then becomes: how -// do we support a safe way of realising the original goal (raising salaries) ? -// -// using the imperative operating mode: -// -// view = table.where().less_than(salary_column,limit).find_all(); -// for (size_t i = 0; i < view.size(); ++i) { -// promote_to_write(); -// // add r.sync_if_needed(); to get reflective mode -// if (r.is_row_attached(i)) { -// Row r = view[i]; -// r.set_int(salary_column, limit); -// } -// commit_and_continue_as_write(); -// } -// -// This is safe, and we just aim for providing low level safety: is_row_attached() can tell -// if the reference is valid, and the references in the view continue to point to the -// same object at all times, also following implicit updates. The rest is up to the -// application logic. -// -// It is important to see, that there is no guarantee that all relevant employees get -// their raise in cases whith concurrent updates. At every call to promote_to_write() new -// employees may be added to the underlying table, but as the view is in imperative mode, -// these new employees are not added to the view. Also at promote_to_write() an existing -// employee could recieve a (different, larger) raise which would then be overwritten and lost. -// However, these are problems that you should expect, since the activity is spread over multiple -// transactions. - - -/// Common base class for TableView and ConstTableView. -class TableViewBase : public RowIndexes { -public: - // - not in use / implemented yet: ... explicit calls to sync_if_needed() must be used - // to get 'reflective' mode. - // enum mode { mode_Reflective, mode_Imperative }; - // void set_operating_mode(mode); - // mode get_operating_mode(); - bool is_empty() const noexcept; - - // Tells if the table that this TableView points at still exists or has been deleted. - bool is_attached() const noexcept; - - bool is_row_attached(size_t row_ndx) const noexcept; - size_t size() const noexcept; - size_t num_attached_rows() const noexcept; - - // Get the query used to create this TableView - // The query will have a null source table if this tv was not created from - // a query - const Query& get_query() const noexcept; - - // Column information - const ColumnBase& get_column_base(size_t index) const; - - size_t get_column_count() const noexcept; - StringData get_column_name(size_t column_ndx) const noexcept; - size_t get_column_index(StringData name) const; - DataType get_column_type(size_t column_ndx) const noexcept; - - // Getting values - int64_t get_int(size_t column_ndx, size_t row_ndx) const noexcept; - bool get_bool(size_t column_ndx, size_t row_ndx) const noexcept; - OldDateTime get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept; - Timestamp get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept; - float get_float(size_t column_ndx, size_t row_ndx) const noexcept; - double get_double(size_t column_ndx, size_t row_ndx) const noexcept; - StringData get_string(size_t column_ndx, size_t row_ndx) const noexcept; - BinaryData get_binary(size_t column_ndx, size_t row_ndx) const noexcept; - Mixed get_mixed(size_t column_ndx, size_t row_ndx) const noexcept; - DataType get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept; - size_t get_link(size_t column_ndx, size_t row_ndx) const noexcept; - - // Links - bool is_null_link(size_t column_ndx, size_t row_ndx) const noexcept; - - // Subtables - size_t get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept; - - // Searching - template - size_t find_first(size_t column_ndx, T value) const; - - size_t find_first_int(size_t column_ndx, int64_t value) const; - size_t find_first_bool(size_t column_ndx, bool value) const; - size_t find_first_olddatetime(size_t column_ndx, OldDateTime value) const; - size_t find_first_float(size_t column_ndx, float value) const; - size_t find_first_double(size_t column_ndx, double value) const; - size_t find_first_string(size_t column_ndx, StringData value) const; - size_t find_first_binary(size_t column_ndx, BinaryData value) const; - size_t find_first_timestamp(size_t column_ndx, Timestamp value) const; - - // Aggregate functions. count_target is ignored by all except Count. Hack because of bug in optional - // arguments in clang and vs2010 (fixed in 2012) - template - R aggregate(R (ColType::*aggregateMethod)(size_t, size_t, size_t, size_t*) const, size_t column_ndx, - T count_target, size_t* return_ndx = nullptr) const; - - int64_t sum_int(size_t column_ndx) const; - int64_t maximum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; - int64_t minimum_int(size_t column_ndx, size_t* return_ndx = nullptr) const; - double average_int(size_t column_ndx, size_t* value_count = nullptr) const; - size_t count_int(size_t column_ndx, int64_t target) const; - - double sum_float(size_t column_ndx) const; - float maximum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; - float minimum_float(size_t column_ndx, size_t* return_ndx = nullptr) const; - double average_float(size_t column_ndx, size_t* value_count = nullptr) const; - size_t count_float(size_t column_ndx, float target) const; - - double sum_double(size_t column_ndx) const; - double maximum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; - double minimum_double(size_t column_ndx, size_t* return_ndx = nullptr) const; - double average_double(size_t column_ndx, size_t* value_count = nullptr) const; - size_t count_double(size_t column_ndx, double target) const; - - OldDateTime maximum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; - OldDateTime minimum_olddatetime(size_t column_ndx, size_t* return_ndx = nullptr) const; - - Timestamp minimum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; - Timestamp maximum_timestamp(size_t column_ndx, size_t* return_ndx = nullptr) const; - size_t count_timestamp(size_t column_ndx, Timestamp target) const; - - // Simple pivot aggregate method. Experimental! Please do not - // document method publicly. - void aggregate(size_t group_by_column, size_t aggr_column, Table::AggrType op, Table& result) const; - - // Get row index in the source table this view is "looking" at. - size_t get_source_ndx(size_t row_ndx) const noexcept; - - /// Search this view for the specified source table row (specified by its - /// index in the source table). If found, the index of that row within this - /// view is returned, otherwise `realm::not_found` is returned. - size_t find_by_source_ndx(size_t source_ndx) const noexcept; - - // Conversion - void to_json(std::ostream&, size_t link_depth = 0, std::map* renames = nullptr) const; - void to_string(std::ostream&, size_t limit = 500) const; - void row_to_string(size_t row_ndx, std::ostream&) const; - - // Determine if the view is 'in sync' with the underlying table - // as well as other views used to generate the view. Note that updates - // through views maintains synchronization between view and table. - // It doesnt by itself maintain other views as well. So if a view - // is generated from another view (not a table), updates may cause - // that view to be outdated, AND as the generated view depends upon - // it, it too will become outdated. - bool is_in_sync() const; - - // Tells if this TableView depends on a LinkList or row that has been deleted. - bool depends_on_deleted_object() const; - - // Synchronize a view to match a table or tableview from which it - // has been derived. Synchronization is achieved by rerunning the - // query used to generate the view. If derived from another view, that - // view will be synchronized as well. - // - // "live" or "reactive" views are implemented by calling sync_if_needed - // before any of the other access-methods whenever the view may have become - // outdated. - // - // This will make the TableView empty and in sync with the highest possible table version - // if the TableView depends on an object (LinkView or row) that has been deleted. - uint_fast64_t sync_if_needed() const; - - // Sort m_row_indexes according to one column - void sort(size_t column, bool ascending = true); - - // Sort m_row_indexes according to multiple columns - void sort(SortDescriptor order); - - // Remove rows that are duplicated with respect to the column set passed as argument. - // distinct() will preserve the original order of the row pointers, also if the order is a result of sort() - // If two rows are indentical (for the given set of distinct-columns), then the last row is removed. - // You can call sync_if_needed() to update the distinct view, just like you can for a sorted view. - // Each time you call distinct() it will compound on the previous calls - void distinct(size_t column); - void distinct(DistinctDescriptor columns); - void limit(LimitDescriptor limit); - void include(IncludeDescriptor include_paths); - IncludeDescriptor get_include_descriptors(); - - // Replace the order of sort and distinct operations, bypassing manually - // calling sort and distinct. This is a convenience method for bindings. - void apply_descriptor_ordering(DescriptorOrdering new_ordering); - - // Gets a readable and parsable string which completely describes the sort and - // distinct operations applied to this view. - std::string get_descriptor_ordering_description() const; - - // Returns whether the rows are guaranteed to be in table order. - // This is true only of unsorted TableViews created from either: - // - Table::find_all() - // - Query::find_all() when the query is not restricted to a view. - bool is_in_table_order() const; - - virtual ~TableViewBase() noexcept; - - virtual std::unique_ptr clone() const = 0; - -protected: - // This TableView can be "born" from 4 different sources: - // - LinkView - // - Query::find_all() - // - Table::get_distinct_view() - // - Table::get_backlink_view() - // Return the version of the source it was created from. - uint64_t outside_version() const; - - void do_sync(); - - // Null if, and only if, the view is detached. - mutable TableRef m_table; - - // The link column that this view contain backlinks for. - const BacklinkColumn* m_linked_column = nullptr; - // The target row that rows in this view link to. - ConstRow m_linked_row; - - // If this TableView was created from a LinkView, then this reference points to it. Otherwise it's 0 - mutable ConstLinkViewRef m_linkview_source; - - // m_distinct_column_source != npos if this view was created from distinct values in a column of m_table. - size_t m_distinct_column_source = npos; - - // Stores the ordering criteria of applied sort and distinct operations. - DescriptorOrdering m_descriptor_ordering; - - // A valid query holds a reference to its table which must match our m_table. - // hence we can use a query with a null table reference to indicate that the view - // was NOT generated by a query, but follows a table directly. - Query m_query; - // parameters for findall, needed to rerun the query - size_t m_start; - size_t m_end; - size_t m_limit; - - mutable util::Optional m_last_seen_version; - - size_t m_num_detached_refs = 0; - /// Construct null view (no memory allocated). - TableViewBase(); - - /// Construct empty view, ready for addition of row indices. - TableViewBase(Table* parent); - TableViewBase(Table* parent, Query& query, size_t start, size_t end, size_t limit); - TableViewBase(Table* parent, size_t column, BasicRowExpr row); - TableViewBase(Table* parent, ConstLinkViewRef link_view); - - enum DistinctViewTag { DistinctView }; - TableViewBase(DistinctViewTag, Table* parent, size_t column_ndx); - - /// Copy constructor. - TableViewBase(const TableViewBase&); - - /// Move constructor. - TableViewBase(TableViewBase&&) noexcept; - - TableViewBase& operator=(const TableViewBase&); - TableViewBase& operator=(TableViewBase&&) noexcept; - - template - static R find_all_integer(V*, size_t, int64_t); - - template - static R find_all_float(V*, size_t, float); - - template - static R find_all_double(V*, size_t, double); - - template - static R find_all_string(V*, size_t, StringData); - - using HandoverPatch = TableViewHandoverPatch; - - // handover machinery entry points based on dynamic type. These methods: - // a) forward their calls to the static type entry points. - // b) new/delete patch data structures. - virtual std::unique_ptr clone_for_handover(std::unique_ptr& patch, - ConstSourcePayload mode) const = 0; - - virtual std::unique_ptr clone_for_handover(std::unique_ptr& patch, - MutableSourcePayload mode) = 0; - - void apply_and_consume_patch(std::unique_ptr& patch, Group& group) - { - apply_patch(*patch, group); - patch.reset(); - } - // handover machinery entry points based on static type - void apply_patch(HandoverPatch& patch, Group& group); - TableViewBase(const TableViewBase& source, HandoverPatch& patch, ConstSourcePayload mode); - TableViewBase(TableViewBase& source, HandoverPatch& patch, MutableSourcePayload mode); - -private: - void allocate_row_indexes(); - void detach() const noexcept; // may have to remove const - size_t find_first_integer(size_t column_ndx, int64_t value) const; - template - Timestamp minmax_timestamp(size_t column_ndx, size_t* return_ndx) const; - - friend class Table; - friend class Query; - friend class SharedGroup; - - // Called by table to adjust any row references: - void adj_row_acc_insert_rows(size_t row_ndx, size_t num_rows) noexcept; - void adj_row_acc_erase_row(size_t row_ndx) noexcept; - void adj_row_acc_move_over(size_t from_row_ndx, size_t to_row_ndx) noexcept; - void adj_row_acc_swap_rows(size_t row_ndx_1, size_t row_ndx_2) noexcept; - void adj_row_acc_move_row(size_t from_row_ndx, size_t to_row_ndx) noexcept; - void adj_row_acc_clear() noexcept; -}; - - -inline void TableViewBase::detach() const noexcept // may have to remove const -{ - m_table = TableRef(); -} - - -class ConstTableView; - - -enum class RemoveMode { ordered, unordered }; - - -/// A TableView gives read and write access to the parent table. -/// -/// A 'const TableView' cannot be changed (e.g. sorted), nor can the -/// parent table be modified through it. -/// -/// A TableView is both copyable and movable. -class TableView : public TableViewBase { -public: - using TableViewBase::TableViewBase; - - TableView() = default; - - // Rows - typedef BasicRowExpr
RowExpr; - typedef BasicRowExpr ConstRowExpr; - RowExpr get(size_t row_ndx) noexcept; - ConstRowExpr get(size_t row_ndx) const noexcept; - RowExpr front() noexcept; - ConstRowExpr front() const noexcept; - RowExpr back() noexcept; - ConstRowExpr back() const noexcept; - RowExpr operator[](size_t row_ndx) noexcept; - ConstRowExpr operator[](size_t row_ndx) const noexcept; - - // Setting values - void set_int(size_t column_ndx, size_t row_ndx, int64_t value); - void set_bool(size_t column_ndx, size_t row_ndx, bool value); - void set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value); - void set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value); - template - void set_enum(size_t column_ndx, size_t row_ndx, E value); - void set_float(size_t column_ndx, size_t row_ndx, float value); - void set_double(size_t column_ndx, size_t row_ndx, double value); - void set_string(size_t column_ndx, size_t row_ndx, StringData value); - void set_binary(size_t column_ndx, size_t row_ndx, BinaryData value); - void set_mixed(size_t column_ndx, size_t row_ndx, Mixed value); - void set_subtable(size_t column_ndx, size_t row_ndx, const Table* table); - void set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx); - - // Subtables - TableRef get_subtable(size_t column_ndx, size_t row_ndx); - ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; - void clear_subtable(size_t column_ndx, size_t row_ndx); - - // Links - TableRef get_link_target(size_t column_ndx) noexcept; - ConstTableRef get_link_target(size_t column_ndx) const noexcept; - void nullify_link(size_t column_ndx, size_t row_ndx); - - /// \defgroup table_view_removes - //@{ - /// \brief Remove the specified row (or rows) from the underlying table. - /// - /// remove() removes the specified row from the underlying table, - /// remove_last() removes the last row in the table view from the underlying - /// table, and clear removes all the rows in the table view from the - /// underlying table. - /// - /// When rows are removed from the underlying table, they will by necessity - /// also be removed from the table view. - /// - /// The order of the remaining rows in the the table view will be maintained - /// regardless of the value passed for \a underlying_mode. - /// - /// \param row_ndx The index within this table view of the row to be - /// removed. - /// - /// \param underlying_mode If set to RemoveMode::ordered (the default), the - /// rows will be removed from the underlying table in a way that maintains - /// the order of the remaining rows in the underlying table. If set to - /// RemoveMode::unordered, the order of the remaining rows in the underlying - /// table will not in general be maintaind, but the operation will generally - /// be much faster. In any case, the order of remaining rows in the table - /// view will not be affected. - void remove(size_t row_ndx, RemoveMode underlying_mode = RemoveMode::ordered); - void remove_last(RemoveMode underlying_mode = RemoveMode::ordered); - void clear(RemoveMode underlying_mode = RemoveMode::ordered); - //@} - - // Searching (Int and String) - TableView find_all_int(size_t column_ndx, int64_t value); - ConstTableView find_all_int(size_t column_ndx, int64_t value) const; - TableView find_all_bool(size_t column_ndx, bool value); - ConstTableView find_all_bool(size_t column_ndx, bool value) const; - TableView find_all_olddatetime(size_t column_ndx, OldDateTime value); - ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; - TableView find_all_float(size_t column_ndx, float value); - ConstTableView find_all_float(size_t column_ndx, float value) const; - TableView find_all_double(size_t column_ndx, double value); - ConstTableView find_all_double(size_t column_ndx, double value) const; - TableView find_all_string(size_t column_ndx, StringData value); - ConstTableView find_all_string(size_t column_ndx, StringData value) const; - // FIXME: Need: TableView find_all_binary(size_t column_ndx, BinaryData value); - // FIXME: Need: ConstTableView find_all_binary(size_t column_ndx, BinaryData value) const; - - Table& get_parent() noexcept; - const Table& get_parent() const noexcept; - - std::unique_ptr clone() const override - { - return std::unique_ptr(new TableView(*this)); - } - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, - ConstSourcePayload mode) const override - { - patch.reset(new HandoverPatch); - std::unique_ptr retval(new TableView(*this, *patch, mode)); - return retval; - } - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, - MutableSourcePayload mode) override - { - patch.reset(new HandoverPatch); - std::unique_ptr retval(new TableView(*this, *patch, mode)); - return retval; - } - -private: - TableView(Table& parent); - TableView(Table& parent, Query& query, size_t start, size_t end, size_t limit); - TableView(Table& parent, ConstLinkViewRef); - - TableView(DistinctViewTag, Table& parent, size_t column_ndx); - - TableView find_all_integer(size_t column_ndx, int64_t value); - ConstTableView find_all_integer(size_t column_ndx, int64_t value) const; - - friend class ConstTableView; - friend class Table; - friend class Query; - friend class TableViewBase; - friend class LinkView; -}; - - -/// A ConstTableView gives read access to the parent table, but no -/// write access. The view itself, though, can be changed, for -/// example, it can be sorted. -/// -/// Note that methods are declared 'const' if, and only if they leave -/// the view unmodified, and this is irrespective of whether they -/// modify the parent table. -/// -/// A ConstTableView has both copy and move semantics. See TableView -/// for more on this. -class ConstTableView : public TableViewBase { -public: - using TableViewBase::TableViewBase; - - ConstTableView() = default; - - ConstTableView(const TableView&); - ConstTableView(TableView&&); - ConstTableView& operator=(const TableView&); - ConstTableView& operator=(TableView&&); - - // Rows - typedef BasicRowExpr ConstRowExpr; - ConstRowExpr get(size_t row_ndx) const noexcept; - ConstRowExpr front() const noexcept; - ConstRowExpr back() const noexcept; - ConstRowExpr operator[](size_t row_ndx) const noexcept; - - // Subtables - ConstTableRef get_subtable(size_t column_ndx, size_t row_ndx) const; - - // Links - ConstTableRef get_link_target(size_t column_ndx) const noexcept; - - // Searching (Int and String) - ConstTableView find_all_int(size_t column_ndx, int64_t value) const; - ConstTableView find_all_bool(size_t column_ndx, bool value) const; - ConstTableView find_all_olddatetime(size_t column_ndx, OldDateTime value) const; - ConstTableView find_all_float(size_t column_ndx, float value) const; - ConstTableView find_all_double(size_t column_ndx, double value) const; - ConstTableView find_all_string(size_t column_ndx, StringData value) const; - - const Table& get_parent() const noexcept; - - std::unique_ptr clone() const override - { - return std::unique_ptr(new ConstTableView(*this)); - } - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, - ConstSourcePayload mode) const override - { - patch.reset(new HandoverPatch); - std::unique_ptr retval(new ConstTableView(*this, *patch, mode)); - return retval; - } - - std::unique_ptr clone_for_handover(std::unique_ptr& patch, - MutableSourcePayload mode) override - { - patch.reset(new HandoverPatch); - std::unique_ptr retval(new ConstTableView(*this, *patch, mode)); - return retval; - } - -private: - ConstTableView(const Table& parent); - - ConstTableView find_all_integer(size_t column_ndx, int64_t value) const; - - friend class TableView; - friend class Table; - friend class Query; - friend class TableViewBase; -}; - - -// ================================================================================================ -// TableViewBase Implementation: - -inline const Query& TableViewBase::get_query() const noexcept -{ - return m_query; -} - -inline bool TableViewBase::is_empty() const noexcept -{ - return m_row_indexes.is_empty(); -} - -inline bool TableViewBase::is_attached() const noexcept -{ - return bool(m_table); -} - -inline bool TableViewBase::is_row_attached(size_t row_ndx) const noexcept -{ - return m_row_indexes.get(row_ndx) != detached_ref; -} - -inline size_t TableViewBase::size() const noexcept -{ - return m_row_indexes.size(); -} - -inline size_t TableViewBase::num_attached_rows() const noexcept -{ - return m_row_indexes.size() - m_num_detached_refs; -} - -inline size_t TableViewBase::get_source_ndx(size_t row_ndx) const noexcept -{ - return to_size_t(m_row_indexes.get(row_ndx)); -} - -inline size_t TableViewBase::find_by_source_ndx(size_t source_ndx) const noexcept -{ - REALM_ASSERT(source_ndx < m_table->size()); - return m_row_indexes.find_first(source_ndx); -} - -inline void TableViewBase::allocate_row_indexes() -{ - // FIXME: This code is unreasonably complicated because it uses `IntegerColumn` as - // a free-standing container, and beause `IntegerColumn` does not conform to the - // RAII idiom (nor should it). - Allocator& alloc = m_row_indexes.get_alloc(); - _impl::DeepArrayRefDestroyGuard ref_guard(alloc); - ref_guard.reset(IntegerColumn::create(alloc)); // Throws - m_table->register_view(this); // Throws - m_row_indexes.init_from_ref(alloc, ref_guard.release()); -} - -inline TableViewBase::TableViewBase() - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws -{ - ref_type ref = IntegerColumn::create(m_row_indexes.get_alloc()); // Throws - m_row_indexes.get_root_array()->init_from_ref(ref); -} - -inline TableViewBase::TableViewBase(Table* parent) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) - , m_table(parent->get_table_ref()) // Throws - , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) -{ - allocate_row_indexes(); -} - -inline TableViewBase::TableViewBase(Table* parent, Query& query, size_t start, size_t end, size_t lim) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) // Throws - , m_table(parent->get_table_ref()) - , m_query(query) - , m_start(start) - , m_end(end) - , m_limit(lim) - , m_last_seen_version(outside_version()) -{ - allocate_row_indexes(); -} - -inline TableViewBase::TableViewBase(Table* parent, size_t column, BasicRowExpr row) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) - , m_table(parent->get_table_ref()) // Throws - , m_linked_column(&parent->get_column_link_base(column).get_backlink_column()) - , m_linked_row(row) - , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) -{ - allocate_row_indexes(); -} - -inline TableViewBase::TableViewBase(DistinctViewTag, Table* parent, size_t column_ndx) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) - , m_table(parent->get_table_ref()) // Throws - , m_distinct_column_source(column_ndx) - , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) -{ - REALM_ASSERT(m_distinct_column_source != npos); - - allocate_row_indexes(); -} - -inline TableViewBase::TableViewBase(Table* parent, ConstLinkViewRef link_view) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) - , m_table(parent->get_table_ref()) // Throws - , m_linkview_source(std::move(link_view)) - , m_last_seen_version(m_table ? util::make_optional(m_table->m_version) : util::none) -{ - REALM_ASSERT(m_linkview_source); - - allocate_row_indexes(); -} - -inline TableViewBase::TableViewBase(const TableViewBase& tv) - : RowIndexes(IntegerColumn::unattached_root_tag(), Allocator::get_default()) - , m_table(tv.m_table) - , m_linked_column(tv.m_linked_column) - , m_linked_row(tv.m_linked_row) - , m_linkview_source(tv.m_linkview_source) - , m_distinct_column_source(tv.m_distinct_column_source) - , m_descriptor_ordering(std::move(tv.m_descriptor_ordering)) - , m_query(tv.m_query) - , m_start(tv.m_start) - , m_end(tv.m_end) - , m_limit(tv.m_limit) - , m_last_seen_version(tv.m_last_seen_version) - , m_num_detached_refs(tv.m_num_detached_refs) -{ - // FIXME: This code is unreasonably complicated because it uses `IntegerColumn` as - // a free-standing container, and because `IntegerColumn` does not conform to the - // RAII idiom (nor should it). - Allocator& alloc = m_row_indexes.get_alloc(); - MemRef mem = tv.m_row_indexes.get_root_array()->clone_deep(alloc); // Throws - _impl::DeepArrayRefDestroyGuard ref_guard(mem.get_ref(), alloc); - if (m_table) - m_table->register_view(this); // Throws - m_row_indexes.init_from_mem(alloc, mem); - ref_guard.release(); - RowIndexes::m_limit_count = tv.m_limit_count; -} - -inline TableViewBase::TableViewBase(TableViewBase&& tv) noexcept - : RowIndexes(std::move(tv.m_row_indexes)) - , m_table(std::move(tv.m_table)) - , m_linked_column(tv.m_linked_column) - , m_linked_row(tv.m_linked_row) - , m_linkview_source(std::move(tv.m_linkview_source)) - , m_distinct_column_source(tv.m_distinct_column_source) - , m_descriptor_ordering(std::move(tv.m_descriptor_ordering)) - , m_query(std::move(tv.m_query)) - , m_start(tv.m_start) - , m_end(tv.m_end) - , m_limit(tv.m_limit) - , - // if we are created from a table view which is outdated, take care to use the outdated - // version number so that we can later trigger a sync if needed. - m_last_seen_version(tv.m_last_seen_version) - , m_num_detached_refs(tv.m_num_detached_refs) -{ - RowIndexes::m_limit_count = tv.m_limit_count; - if (m_table) - m_table->move_registered_view(&tv, this); -} - -inline TableViewBase::~TableViewBase() noexcept -{ - if (m_table) { - m_table->unregister_view(this); - m_table = TableRef(); - } - m_row_indexes.destroy(); // Shallow -} - -inline TableViewBase& TableViewBase::operator=(TableViewBase&& tv) noexcept -{ - if (m_table) - m_table->unregister_view(this); - m_table = std::move(tv.m_table); - if (m_table) - m_table->move_registered_view(&tv, this); - - m_row_indexes.move_assign(tv.m_row_indexes); - m_limit_count = tv.m_limit_count; - m_query = std::move(tv.m_query); - m_num_detached_refs = tv.m_num_detached_refs; - m_last_seen_version = tv.m_last_seen_version; - m_start = tv.m_start; - m_end = tv.m_end; - m_limit = tv.m_limit; - m_linked_column = tv.m_linked_column; - m_linked_row = tv.m_linked_row; - m_linkview_source = std::move(tv.m_linkview_source); - m_descriptor_ordering = std::move(tv.m_descriptor_ordering); - m_distinct_column_source = tv.m_distinct_column_source; - - return *this; -} - -inline TableViewBase& TableViewBase::operator=(const TableViewBase& tv) -{ - if (this == &tv) - return *this; - - if (m_table != tv.m_table) { - if (m_table) - m_table->unregister_view(this); - m_table = tv.m_table; - if (m_table) - m_table->register_view(this); - } - - Allocator& alloc = m_row_indexes.get_alloc(); - MemRef mem = tv.m_row_indexes.get_root_array()->clone_deep(alloc); // Throws - _impl::DeepArrayRefDestroyGuard ref_guard(mem.get_ref(), alloc); - m_row_indexes.destroy(); - m_row_indexes.get_root_array()->init_from_mem(mem); - ref_guard.release(); - m_limit_count = tv.m_limit_count; - - m_query = tv.m_query; - m_num_detached_refs = tv.m_num_detached_refs; - m_last_seen_version = tv.m_last_seen_version; - m_start = tv.m_start; - m_end = tv.m_end; - m_limit = tv.m_limit; - m_linked_column = tv.m_linked_column; - m_linked_row = tv.m_linked_row; - m_linkview_source = tv.m_linkview_source; - m_descriptor_ordering = tv.m_descriptor_ordering; - m_distinct_column_source = tv.m_distinct_column_source; - - return *this; -} - -#define REALM_ASSERT_COLUMN(column_ndx) \ - REALM_ASSERT(m_table); \ - REALM_ASSERT(column_ndx < m_table->get_column_count()) - -#define REALM_ASSERT_ROW(row_ndx) \ - REALM_ASSERT(m_table); \ - REALM_ASSERT(row_ndx < m_row_indexes.size()) - -#define REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, column_type) \ - REALM_ASSERT_COLUMN(column_ndx); \ - REALM_DIAG_PUSH(); \ - REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE(); \ - REALM_ASSERT(m_table->get_column_type(column_ndx) == column_type || \ - (m_table->get_column_type(column_ndx) == type_OldDateTime && column_type == type_Int)); \ - REALM_DIAG_POP() - -#define REALM_ASSERT_INDEX(column_ndx, row_ndx) \ - REALM_ASSERT_COLUMN(column_ndx); \ - REALM_ASSERT(row_ndx < m_row_indexes.size()) - -#define REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, column_type) \ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, column_type); \ - REALM_ASSERT(row_ndx < m_row_indexes.size()) - -#define REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx) \ - REALM_ASSERT_COLUMN(column_ndx); \ - REALM_DIAG_PUSH(); \ - REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE(); \ - REALM_ASSERT(m_table->get_column_type(column_ndx) == type_Table || \ - (m_table->get_column_type(column_ndx) == type_Mixed)); \ - REALM_DIAG_POP(); \ - REALM_ASSERT(row_ndx < m_row_indexes.size()) - -// Column information - -inline const ColumnBase& TableViewBase::get_column_base(size_t index) const -{ - return m_table->get_column_base(index); -} - -inline size_t TableViewBase::get_column_count() const noexcept -{ - REALM_ASSERT(m_table); - return m_table->get_column_count(); -} - -inline StringData TableViewBase::get_column_name(size_t column_ndx) const noexcept -{ - REALM_ASSERT(m_table); - return m_table->get_column_name(column_ndx); -} - -inline size_t TableViewBase::get_column_index(StringData name) const -{ - REALM_ASSERT(m_table); - return m_table->get_column_index(name); -} - -inline DataType TableViewBase::get_column_type(size_t column_ndx) const noexcept -{ - REALM_ASSERT(m_table); - return m_table->get_column_type(column_ndx); -} - - -// Getters - - -inline int64_t TableViewBase::get_int(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_int(column_ndx, to_size_t(real_ndx)); -} - -inline bool TableViewBase::get_bool(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Bool); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_bool(column_ndx, to_size_t(real_ndx)); -} - -inline OldDateTime TableViewBase::get_olddatetime(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_OldDateTime); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_olddatetime(column_ndx, to_size_t(real_ndx)); -} - -inline Timestamp TableViewBase::get_timestamp(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Timestamp); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_timestamp(column_ndx, to_size_t(real_ndx)); -} - -inline float TableViewBase::get_float(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Float); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_float(column_ndx, to_size_t(real_ndx)); -} - -inline double TableViewBase::get_double(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Double); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_double(column_ndx, to_size_t(real_ndx)); -} - -inline StringData TableViewBase::get_string(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_String); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_string(column_ndx, to_size_t(real_ndx)); -} - -inline BinaryData TableViewBase::get_binary(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Binary); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_binary(column_ndx, to_size_t(real_ndx)); -} - -inline Mixed TableViewBase::get_mixed(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_mixed(column_ndx, to_size_t(real_ndx)); -} - -inline DataType TableViewBase::get_mixed_type(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_mixed_type(column_ndx, to_size_t(real_ndx)); -} - -inline size_t TableViewBase::get_subtable_size(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_subtable_size(column_ndx, to_size_t(real_ndx)); -} - -inline size_t TableViewBase::get_link(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_link(column_ndx, to_size_t(real_ndx)); -} - -inline TableRef TableView::get_link_target(size_t column_ndx) noexcept -{ - return m_table->get_link_target(column_ndx); -} - -inline ConstTableRef TableView::get_link_target(size_t column_ndx) const noexcept -{ - return m_table->get_link_target(column_ndx); -} - -inline ConstTableRef ConstTableView::get_link_target(size_t column_ndx) const noexcept -{ - return m_table->get_link_target(column_ndx); -} - -inline bool TableViewBase::is_null_link(size_t column_ndx, size_t row_ndx) const noexcept -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->is_null_link(column_ndx, to_size_t(real_ndx)); -} - - -// Searching - - -inline size_t TableViewBase::find_first_int(size_t column_ndx, int64_t value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); - return find_first_integer(column_ndx, value); -} - -inline size_t TableViewBase::find_first_bool(size_t column_ndx, bool value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); - return find_first_integer(column_ndx, value ? 1 : 0); -} - -inline size_t TableViewBase::find_first_olddatetime(size_t column_ndx, OldDateTime value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); - return find_first_integer(column_ndx, int64_t(value.get_olddatetime())); -} - -inline size_t TableViewBase::find_first_integer(size_t column_ndx, int64_t value) const -{ - return find_first(column_ndx, value); -} - -inline size_t TableViewBase::find_first_float(size_t column_ndx, float value) const -{ - return find_first(column_ndx, value); -} - -inline size_t TableViewBase::find_first_double(size_t column_ndx, double value) const -{ - return find_first(column_ndx, value); -} - -inline size_t TableViewBase::find_first_string(size_t column_ndx, StringData value) const -{ - return find_first(column_ndx, value); -} - -inline size_t TableViewBase::find_first_binary(size_t column_ndx, BinaryData value) const -{ - return find_first(column_ndx, value); -} - -inline size_t TableViewBase::find_first_timestamp(size_t column_ndx, Timestamp value) const -{ - return find_first(column_ndx, value); -} - - -template -R TableViewBase::find_all_integer(V* view, size_t column_ndx, int64_t value) -{ - typedef typename std::remove_const::type TNonConst; - return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); -} - -template -R TableViewBase::find_all_float(V* view, size_t column_ndx, float value) -{ - typedef typename std::remove_const::type TNonConst; - return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); -} - -template -R TableViewBase::find_all_double(V* view, size_t column_ndx, double value) -{ - typedef typename std::remove_const::type TNonConst; - return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); -} - -template -R TableViewBase::find_all_string(V* view, size_t column_ndx, StringData value) -{ - typedef typename std::remove_const::type TNonConst; - return view->m_table->where(const_cast(view)).equal(column_ndx, value).find_all(); -} - - -//-------------------------- TableView, ConstTableView implementation: - -inline ConstTableView::ConstTableView(const TableView& tv) - : TableViewBase(tv) -{ -} - -inline ConstTableView::ConstTableView(TableView&& tv) - : TableViewBase(std::move(tv)) -{ -} - -inline void TableView::remove_last(RemoveMode underlying_mode) -{ - if (!is_empty()) - remove(size() - 1, underlying_mode); -} - -inline Table& TableView::get_parent() noexcept -{ - return *m_table; -} - -inline const Table& TableView::get_parent() const noexcept -{ - return *m_table; -} - -inline const Table& ConstTableView::get_parent() const noexcept -{ - return *m_table; -} - -inline TableView::TableView(Table& parent) - : TableViewBase(&parent) -{ -} - -inline TableView::TableView(Table& parent, Query& query, size_t start, size_t end, size_t lim) - : TableViewBase(&parent, query, start, end, lim) -{ -} - -inline TableView::TableView(Table& parent, ConstLinkViewRef link_view) -: TableViewBase(&parent, std::move(link_view)) -{ -} - -inline TableView::TableView(TableViewBase::DistinctViewTag, Table& parent, size_t column_ndx) - : TableViewBase(TableViewBase::DistinctView, &parent, column_ndx) -{ -} - -inline ConstTableView::ConstTableView(const Table& parent) - : TableViewBase(const_cast(&parent)) -{ -} - -inline ConstTableView& ConstTableView::operator=(const TableView& tv) -{ - TableViewBase::operator=(tv); - return *this; -} - -inline ConstTableView& ConstTableView::operator=(TableView&& tv) -{ - TableViewBase::operator=(std::move(tv)); - return *this; -} - - -// - string -inline TableView TableView::find_all_string(size_t column_ndx, StringData value) -{ - return TableViewBase::find_all_string(this, column_ndx, value); -} - -inline ConstTableView TableView::find_all_string(size_t column_ndx, StringData value) const -{ - return TableViewBase::find_all_string(this, column_ndx, value); -} - -inline ConstTableView ConstTableView::find_all_string(size_t column_ndx, StringData value) const -{ - return TableViewBase::find_all_string(this, column_ndx, value); -} - -// - float -inline TableView TableView::find_all_float(size_t column_ndx, float value) -{ - return TableViewBase::find_all_float(this, column_ndx, value); -} - -inline ConstTableView TableView::find_all_float(size_t column_ndx, float value) const -{ - return TableViewBase::find_all_float(this, column_ndx, value); -} - -inline ConstTableView ConstTableView::find_all_float(size_t column_ndx, float value) const -{ - return TableViewBase::find_all_float(this, column_ndx, value); -} - - -// - double -inline TableView TableView::find_all_double(size_t column_ndx, double value) -{ - return TableViewBase::find_all_double(this, column_ndx, value); -} - -inline ConstTableView TableView::find_all_double(size_t column_ndx, double value) const -{ - return TableViewBase::find_all_double(this, column_ndx, value); -} - -inline ConstTableView ConstTableView::find_all_double(size_t column_ndx, double value) const -{ - return TableViewBase::find_all_double(this, column_ndx, value); -} - - -// -- 3 variants of the 3 find_all_{int, bool, date} all based on integer - -inline TableView TableView::find_all_integer(size_t column_ndx, int64_t value) -{ - return TableViewBase::find_all_integer(this, column_ndx, value); -} - -inline ConstTableView TableView::find_all_integer(size_t column_ndx, int64_t value) const -{ - return TableViewBase::find_all_integer(this, column_ndx, value); -} - -inline ConstTableView ConstTableView::find_all_integer(size_t column_ndx, int64_t value) const -{ - return TableViewBase::find_all_integer(this, column_ndx, value); -} - - -inline TableView TableView::find_all_int(size_t column_ndx, int64_t value) -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); - return find_all_integer(column_ndx, value); -} - -inline TableView TableView::find_all_bool(size_t column_ndx, bool value) -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); - return find_all_integer(column_ndx, value ? 1 : 0); -} - -inline TableView TableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); - return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); -} - - -inline ConstTableView TableView::find_all_int(size_t column_ndx, int64_t value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); - return find_all_integer(column_ndx, value); -} - -inline ConstTableView TableView::find_all_bool(size_t column_ndx, bool value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); - return find_all_integer(column_ndx, value ? 1 : 0); -} - -inline ConstTableView TableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); - return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); -} - - -inline ConstTableView ConstTableView::find_all_int(size_t column_ndx, int64_t value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Int); - return find_all_integer(column_ndx, value); -} - -inline ConstTableView ConstTableView::find_all_bool(size_t column_ndx, bool value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_Bool); - return find_all_integer(column_ndx, value ? 1 : 0); -} - -inline ConstTableView ConstTableView::find_all_olddatetime(size_t column_ndx, OldDateTime value) const -{ - REALM_ASSERT_COLUMN_AND_TYPE(column_ndx, type_OldDateTime); - return find_all_integer(column_ndx, int64_t(value.get_olddatetime())); -} - - -// Rows - - -inline TableView::RowExpr TableView::get(size_t row_ndx) noexcept -{ - REALM_ASSERT_ROW(row_ndx); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get(to_size_t(real_ndx)); -} - -inline TableView::ConstRowExpr TableView::get(size_t row_ndx) const noexcept -{ - REALM_ASSERT_ROW(row_ndx); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get(to_size_t(real_ndx)); -} - -inline ConstTableView::ConstRowExpr ConstTableView::get(size_t row_ndx) const noexcept -{ - REALM_ASSERT_ROW(row_ndx); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get(to_size_t(real_ndx)); -} - -inline TableView::RowExpr TableView::front() noexcept -{ - return get(0); -} - -inline TableView::ConstRowExpr TableView::front() const noexcept -{ - return get(0); -} - -inline ConstTableView::ConstRowExpr ConstTableView::front() const noexcept -{ - return get(0); -} - -inline TableView::RowExpr TableView::back() noexcept -{ - size_t last_row_ndx = size() - 1; - return get(last_row_ndx); -} - -inline TableView::ConstRowExpr TableView::back() const noexcept -{ - size_t last_row_ndx = size() - 1; - return get(last_row_ndx); -} - -inline ConstTableView::ConstRowExpr ConstTableView::back() const noexcept -{ - size_t last_row_ndx = size() - 1; - return get(last_row_ndx); -} - -inline TableView::RowExpr TableView::operator[](size_t row_ndx) noexcept -{ - return get(row_ndx); -} - -inline TableView::ConstRowExpr TableView::operator[](size_t row_ndx) const noexcept -{ - return get(row_ndx); -} - -inline ConstTableView::ConstRowExpr ConstTableView::operator[](size_t row_ndx) const noexcept -{ - return get(row_ndx); -} - - -// Subtables - - -inline TableRef TableView::get_subtable(size_t column_ndx, size_t row_ndx) -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); -} - -inline ConstTableRef TableView::get_subtable(size_t column_ndx, size_t row_ndx) const -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); -} - -inline ConstTableRef ConstTableView::get_subtable(size_t column_ndx, size_t row_ndx) const -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->get_subtable(column_ndx, to_size_t(real_ndx)); -} - -inline void TableView::clear_subtable(size_t column_ndx, size_t row_ndx) -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - return m_table->clear_subtable(column_ndx, to_size_t(real_ndx)); -} - - -// Setters - - -inline void TableView::set_int(size_t column_ndx, size_t row_ndx, int64_t value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Int); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_int(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_bool(size_t column_ndx, size_t row_ndx, bool value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Bool); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_bool(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_olddatetime(size_t column_ndx, size_t row_ndx, OldDateTime value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_OldDateTime); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_olddatetime(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_timestamp(size_t column_ndx, size_t row_ndx, Timestamp value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Timestamp); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_timestamp(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_float(size_t column_ndx, size_t row_ndx, float value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Float); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_float(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_double(size_t column_ndx, size_t row_ndx, double value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Double); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_double(column_ndx, to_size_t(real_ndx), value); -} - -template -inline void TableView::set_enum(size_t column_ndx, size_t row_ndx, E value) -{ - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_int(column_ndx, real_ndx, value); -} - -inline void TableView::set_string(size_t column_ndx, size_t row_ndx, StringData value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_String); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_string(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_binary(size_t column_ndx, size_t row_ndx, BinaryData value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Binary); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_binary(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_mixed(size_t column_ndx, size_t row_ndx, Mixed value) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Mixed); - - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_mixed(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_subtable(size_t column_ndx, size_t row_ndx, const Table* value) -{ - REALM_ASSERT_INDEX_AND_TYPE_TABLE_OR_MIXED(column_ndx, row_ndx); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_subtable(column_ndx, to_size_t(real_ndx), value); -} - -inline void TableView::set_link(size_t column_ndx, size_t row_ndx, size_t target_row_ndx) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->set_link(column_ndx, to_size_t(real_ndx), target_row_ndx); -} - -inline void TableView::nullify_link(size_t column_ndx, size_t row_ndx) -{ - REALM_ASSERT_INDEX_AND_TYPE(column_ndx, row_ndx, type_Link); - const int64_t real_ndx = m_row_indexes.get(row_ndx); - REALM_ASSERT(real_ndx != detached_ref); - m_table->nullify_link(column_ndx, to_size_t(real_ndx)); -} - -} // namespace realm - -#endif // REALM_TABLE_VIEW_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/timestamp.hpp b/Lesson14/Pods/Realm/include/core/realm/timestamp.hpp deleted file mode 100644 index 2108245..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/timestamp.hpp +++ /dev/null @@ -1,187 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_TIMESTAMP_HPP -#define REALM_TIMESTAMP_HPP - -#include -#include -#include -#include -#include - -namespace realm { - -class Timestamp { -public: - // Construct from the number of seconds and nanoseconds since the UNIX epoch: 00:00:00 UTC on 1 January 1970 - // - // To split a native nanosecond representation, only division and modulo are necessary: - // - // s = native_nano / nanoseconds_per_second - // n = native_nano % nanoseconds_per_second - // Timestamp ts(s, n); - // - // To convert back into native nanosecond representation, simple multiply and add: - // - // native_nano = ts.s * nanoseconds_per_second + ts.n - // - // Specifically this allows the nanosecond part to become negative (only) for Timestamps before the UNIX epoch. - // Usually this will not need special attention, but for reference, valid Timestamps will have one of the - // following sign combinations: - // - // s | n - // ----- - // + | + - // + | 0 - // 0 | + - // 0 | 0 - // 0 | - - // - | 0 - // - | - - // - // Examples: - // The UNIX epoch is constructed by Timestamp(0, 0) - // Relative times are constructed as follows: - // +1 second is constructed by Timestamp(1, 0) - // +1 nanosecond is constructed by Timestamp(0, 1) - // +1.1 seconds (1100 milliseconds after the epoch) is constructed by Timestamp(1, 100000000) - // -1.1 seconds (1100 milliseconds before the epoch) is constructed by Timestamp(-1, -100000000) - // - Timestamp(int64_t seconds, int32_t nanoseconds) - : m_seconds(seconds) - , m_nanoseconds(nanoseconds) - , m_is_null(false) - { - REALM_ASSERT_EX(-nanoseconds_per_second < nanoseconds && nanoseconds < nanoseconds_per_second, nanoseconds); - const bool both_non_negative = seconds >= 0 && nanoseconds >= 0; - const bool both_non_positive = seconds <= 0 && nanoseconds <= 0; - REALM_ASSERT_EX(both_non_negative || both_non_positive, both_non_negative, both_non_positive); - } - Timestamp(realm::null) - : m_is_null(true) - { - } - template - Timestamp(std::chrono::time_point tp) - : m_is_null(false) - { - int64_t native_nano = std::chrono::duration_cast(tp.time_since_epoch()).count(); - m_seconds = native_nano / nanoseconds_per_second; - m_nanoseconds = static_cast(native_nano % nanoseconds_per_second); - } - Timestamp() - : Timestamp(null{}) - { - } - - bool is_null() const - { - return m_is_null; - } - - int64_t get_seconds() const noexcept - { - REALM_ASSERT(!m_is_null); - return m_seconds; - } - - int32_t get_nanoseconds() const noexcept - { - REALM_ASSERT(!m_is_null); - return m_nanoseconds; - } - - template - std::chrono::time_point get_time_point() - { - REALM_ASSERT(!m_is_null); - - int64_t native_nano = m_seconds * nanoseconds_per_second + m_nanoseconds; - auto duration = std::chrono::duration_cast(std::chrono::duration{native_nano}); - - return std::chrono::time_point(duration); - } - - // Note that only == and != operators work if one of the Timestamps are null! Else use realm::Greater, - // realm::Less, etc, instead. This is in order to collect all treatment of null behaviour in a single place for all - // types (query_conditions.hpp) to ensure that all types sort and compare null vs. non-null in the same manner, - // especially for int/float where we cannot override operators. This design is open for discussion, though, - // because it has usability drawbacks - bool operator==(const Timestamp& rhs) const - { - if (is_null() && rhs.is_null()) - return true; - - if (is_null() != rhs.is_null()) - return false; - - return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; - } - bool operator!=(const Timestamp& rhs) const - { - return !(*this == rhs); - } - bool operator>(const Timestamp& rhs) const - { - REALM_ASSERT(!is_null()); - REALM_ASSERT(!rhs.is_null()); - return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); - } - bool operator<(const Timestamp& rhs) const - { - REALM_ASSERT(!is_null()); - REALM_ASSERT(!rhs.is_null()); - return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); - } - bool operator<=(const Timestamp& rhs) const - { - REALM_ASSERT(!is_null()); - REALM_ASSERT(!rhs.is_null()); - return *this < rhs || *this == rhs; - } - bool operator>=(const Timestamp& rhs) const - { - REALM_ASSERT(!is_null()); - REALM_ASSERT(!rhs.is_null()); - return *this > rhs || *this == rhs; - } - Timestamp& operator=(const Timestamp& rhs) = default; - - template - friend std::basic_ostream& operator<<(std::basic_ostream& out, const Timestamp&); - static constexpr int32_t nanoseconds_per_second = 1000000000; - -private: - int64_t m_seconds; - int32_t m_nanoseconds; - bool m_is_null; -}; - -// LCOV_EXCL_START -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const Timestamp& d) -{ - out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")"; - return out; -} -// LCOV_EXCL_STOP - -} // namespace realm - -#endif // REALM_TIMESTAMP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/unicode.hpp b/Lesson14/Pods/Realm/include/core/realm/unicode.hpp deleted file mode 100644 index d8b3d33..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/unicode.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UNICODE_HPP -#define REALM_UNICODE_HPP - -#include -#include -#include - -#include -#include -#include - - -namespace realm { - -enum string_compare_method_t { - STRING_COMPARE_CORE, - STRING_COMPARE_CPP11, - STRING_COMPARE_CALLBACK, - STRING_COMPARE_CORE_SIMILAR -}; - -extern StringCompareCallback string_compare_callback; -extern string_compare_method_t string_compare_method; - -// Description for set_string_compare_method(): -// -// Short summary: iOS language binding: call -// set_string_compare_method() for fast but slightly inaccurate sort in some countries, or -// set_string_compare_method(2, callbackptr) for slow but precise sort (see callbackptr below) -// -// Different countries ('locales') have different sorting order for strings and letters. Because there unfortunatly -// doesn't exist any unified standardized way to compare strings in C++ on multiple platforms, we need this method. -// -// It determins how sorting a TableView by a String column must take place. The 'method' argument can be: -// -// 0: Fast core-only compare (no OS/framework calls). LIMITATIONS: Works only upto 'Latin Extended 2' (unicodes -// 0...591). Also, sorting order is according to 'en_US' so it may be slightly inaccurate for some countries. -// 'callback' argument is ignored. -// -// Return value: Always 'true' -// -// 1: Native C++11 method if core is compiled as C++11. Gives precise sorting according -// to user's current locale. LIMITATIONS: Currently works only on Windows and on Linux with clang. Does NOT work on -// iOS (due to only 'C' locale being available in CoreFoundation, which puts 'Z' before 'a'). Unknown if works on -// Windows Phone / Android. Furthermore it does NOT work on Linux with gcc 4.7 or 4.8 (lack of c++11 feature that -// can convert utf8->wstring without calls to setlocale()). -// -// Return value: 'true' if supported, otherwise 'false' (if so, then previous setting, if any, is preserved). -// -// 2: Callback method. Language binding / C++ user must provide a utf-8 callback method of prototype: -// bool callback(const char* string1, const char* string2) where 'callback' must return bool(string1 < string2). -// -// Return value: Always 'true' -// -// Default is method = 0 if the function is never called -// -// NOT THREAD SAFE! Call once during initialization or make sure it's not called simultaneously with different -// arguments. The setting is remembered per-process; it does NOT need to be called prior to each sort -bool set_string_compare_method(string_compare_method_t method, StringCompareCallback callback); - - -// Return size in bytes of utf8 character. No error checking -size_t sequence_length(char lead); - -// Limitations for case insensitive string search -// Case insensitive search (equal, begins_with, ends_with, like and contains) -// only works for unicodes 0...0x7f which is the same as the 0...127 -// ASCII character set (letters a-z and A-Z). - -// In does *not* work for the 0...255 ANSI character set that contains -// characters from many European countries like Germany, France, Denmark, -// etc. - -// It also does not work for characters from non-western countries like -// Japan, Russia, Arabia, etc. - -// If there exists characters outside the ASCII range either in the text -// to be searched for, or in the Realm string column which is searched -// in, then the compare yields a random result such that the row may or -// may not be included in the result set. - -// Return bool(string1 < string2) -bool utf8_compare(StringData string1, StringData string2); - -// Return unicode value of character. -uint32_t utf8value(const char* character); - -inline bool equal_sequence(const char*& begin, const char* end, const char* begin2); - -// FIXME: The current approach to case insensitive comparison requires -// that case mappings can be done in a way that does not change he -// number of bytes used to encode the individual Unicode -// character. This is not generally the case, so, as far as I can see, -// this approach has no future. -// -// FIXME: The current approach to case insensitive comparison relies -// on checking each "haystack" character against the corresponding -// character in both a lower cased and an upper cased version of the -// "needle". While this leads to efficient comparison, it ignores the -// fact that "case folding" is the only correct approach to case -// insensitive comparison in a locale agnostic Unicode -// environment. -// -// See -// http://www.w3.org/International/wiki/Case_folding -// http://userguide.icu-project.org/transforms/casemappings#TOC-Case-Folding. -// -// The ideal API would probably be something like this: -// -// case_fold: utf_8 -> case_folded -// equal_case_fold: (needle_case_folded, single_haystack_entry_utf_8) -> found -// search_case_fold: (needle_case_folded, huge_haystack_string_utf_8) -> found_at_position -// -// The case folded form would probably be using UTF-32 or UTF-16. - - -/// If successful, returns a string of the same size as \a source. -/// Returns none if invalid UTF-8 encoding was encountered. -util::Optional case_map(StringData source, bool upper); - -enum IgnoreErrorsTag { IgnoreErrors }; -std::string case_map(StringData source, bool upper, IgnoreErrorsTag); - -/// Assumes that the sizes of \a needle_upper and \a needle_lower are -/// identical to the size of \a haystack. Returns false if the needle -/// is different from the haystack. -bool equal_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower); - -/// Assumes that the sizes of \a needle_upper and \a needle_lower are -/// both equal to \a needle_size. Returns haystack.size() if the -/// needle was not found. -size_t search_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size); - -/// Assumes that the sizes of \a needle_upper and \a needle_lower are -/// both equal to \a needle_size. Returns false if the -/// needle was not found. -bool contains_ins(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size, const std::array &charmap); - -/// Case insensitive wildcard matching ('?' for single char, '*' for zero or more chars) -bool string_like_ins(StringData text, StringData pattern) noexcept; -bool string_like_ins(StringData text, StringData upper, StringData lower) noexcept; - -} // namespace realm - -#endif // REALM_UNICODE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/aes_cryptor.hpp b/Lesson14/Pods/Realm/include/core/realm/util/aes_cryptor.hpp deleted file mode 100644 index 23720b1..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/aes_cryptor.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#if REALM_ENABLE_ENCRYPTION - -#if REALM_PLATFORM_APPLE -#include -#elif defined(_WIN32) -#include -#include -#include -#pragma comment(lib, "bcrypt.lib") -#else -#include -#include -#endif - -namespace realm { -namespace util { - -struct iv_table; -class EncryptedFileMapping; - -class AESCryptor { -public: - AESCryptor(const uint8_t* key); - ~AESCryptor() noexcept; - - void set_file_size(off_t new_size); - - bool read(FileDesc fd, off_t pos, char* dst, size_t size); - void write(FileDesc fd, off_t pos, const char* src, size_t size) noexcept; - -private: - enum EncryptionMode { -#if REALM_PLATFORM_APPLE - mode_Encrypt = kCCEncrypt, - mode_Decrypt = kCCDecrypt -#elif defined(_WIN32) - mode_Encrypt = 0, - mode_Decrypt = 1 -#else - mode_Encrypt = 1, - mode_Decrypt = 0 -#endif - }; - -#if REALM_PLATFORM_APPLE - CCCryptorRef m_encr; - CCCryptorRef m_decr; -#elif defined(_WIN32) - BCRYPT_KEY_HANDLE m_aes_key_handle; -#else - uint8_t m_aesKey[32]; - EVP_CIPHER_CTX* m_ctx; -#endif - - uint8_t m_hmacKey[32]; - std::vector m_iv_buffer; - std::unique_ptr m_rw_buffer; - std::unique_ptr m_dst_buffer; - - void calc_hmac(const void* src, size_t len, uint8_t* dst, const uint8_t* key) const; - bool check_hmac(const void* data, size_t len, const uint8_t* hmac) const; - void crypt(EncryptionMode mode, off_t pos, char* dst, const char* src, const char* stored_iv) noexcept; - iv_table& get_iv_table(FileDesc fd, off_t data_pos) noexcept; - void handle_error(); -}; - -struct ReaderInfo { - const void* reader_ID; - uint64_t version; -}; - -struct SharedFileInfo { - FileDesc fd; - AESCryptor cryptor; - std::vector mappings; - uint64_t last_scanned_version = 0; - uint64_t current_version = 0; - size_t num_decrypted_pages = 0; - size_t num_reclaimed_pages = 0; - size_t progress_index = 0; - std::vector readers; - - SharedFileInfo(const uint8_t* key, FileDesc file_descriptor); -}; -} -} - -#endif // REALM_ENABLE_ENCRYPTION diff --git a/Lesson14/Pods/Realm/include/core/realm/util/allocation_metrics.hpp b/Lesson14/Pods/Realm/include/core/realm/util/allocation_metrics.hpp deleted file mode 100644 index 10176e7..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/allocation_metrics.hpp +++ /dev/null @@ -1,326 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_ALLOCATION_METRICS_HPP -#define REALM_UTIL_ALLOCATION_METRICS_HPP - -#include -#include - -#include - -namespace realm { -namespace util { - -/// Designate a name to be used in heap allocation metrics. -/// -/// An instance can be used with `AllocationMetricsContext::get_metric()` to -/// obtain an instance of `MeteredAllocator` that counts -/// allocations/deallocations towards this name, within that context. -/// -/// Instances of `AllocationMetricName` should be statically allocated. When an -/// instance has been initialized, it must not be destroyed until the program -/// terminates. This is to ensure that iterating over existing names is -/// thread-safe and lock-free. -/// -/// Similarly, when an instance of `AllocationMetricsContext` has been -/// allocated, no further instances of AllocationMetricName must be -/// instantiated. -struct AllocationMetricName { - explicit AllocationMetricName(const char* name) noexcept; - - /// Get the string name. - /// - /// This method is thread-safe. - const char* name() const noexcept; - - /// Get the index of this metric. The index corresponds to an allocator - /// inside the current instance of AllocatorMetricTenant. - /// - /// This method is thread-safe. - size_t index() const noexcept; - - /// Get the next name. The names are returned in no particular order. - /// - /// This method is thread-safe. - const AllocationMetricName* next() const noexcept; - - /// Get the first name in the internal list of names, for the purpose - /// of iterating over all names in the program. - /// - /// This method is thread-safe. - static const AllocationMetricName* get_top() noexcept; - static const AllocationMetricName* find(const char* name) noexcept; -private: - const char* m_name; - size_t m_index; // Index into `AllocationMetricsContext::m_metrics`. - - // This is used to iterate over all existing components. Instances of - // AllocationMetricName are expected to be statically allocated. - const AllocationMetricName* m_next = nullptr; -}; - - -/// A heap memory allocator that keeps track of how much was -/// allocated/deallocated throughout its lifetime. -/// -/// Memory is allocated with `DefaultAllocator`. -/// -/// All methods on instances of this class are thread-safe. -class MeteredAllocator final : public AllocatorBase { -public: - MeteredAllocator() noexcept; - - static MeteredAllocator& unknown() noexcept; - - /// Return the currently allocated number of bytes. - /// - /// This method is thread-safe, but may temporarily return slightly - /// inaccurate results if allocations/deallocations are happening while it - /// is being called. - std::size_t get_currently_allocated_bytes() const noexcept; - - /// Return the total number of bytes that have been allocated (including - /// allocations that have since been freed). - /// - /// This method is thread-safe. - std::size_t get_total_allocated_bytes() const noexcept; - - /// Return the total number of bytes that have been freed. - /// - /// This method is thread-safe. - std::size_t get_total_deallocated_bytes() const noexcept; - - // AllocatorBase interface: - - /// Return a reference to an MeteredAllocator that belongs to the current - /// AllocationMetricsContext (if any) and the current AllocationMetricNameScope - /// (if any). - /// - /// The returned reference is valid for the duration of the lifetime of the - /// instance of AllocationMetricsContext that is "current" at the time of - /// calling this function, and namely it is valid beyond the lifetime of - /// the current AllocationMetricNameScope. - /// - /// If there is no current AllocationMetricsContext, the global "unknown" - /// tenant will be used. - /// - /// If no metric name is currently in scope (through the use of - /// AllocationMetricNameScope), allocations and deallocations will be counted - /// towards the default "unknown" metric. - /// - /// This method is thread-safe. - static MeteredAllocator& get_default() noexcept; - - /// Allocate memory, accounting for the allocation in metrics. - /// - /// This method is thread-safe. - void* allocate(size_t size, size_t align) override final; - - /// Free memory, accounting for the deallocation in metrics. - /// - /// This method is thread-safe. - void free(void* ptr, size_t size) noexcept override final; - - /// Notify metrics that an allocation happened. - /// - /// This method is thread-safe. - void did_allocate_bytes(std::size_t) noexcept; - - /// Notify metrics that a deallocation happened. - /// - /// This method is thread-safe. - void did_free_bytes(std::size_t) noexcept; - -private: - std::atomic m_allocated_bytes; - // These members are spaced by 64 bytes to prevent false sharing - // (inter-processor CPU locks when multiple processes are modifying them - // concurrently). - char dummy[56]; - std::atomic m_deallocated_bytes; - char dummy2[56]; // Prevent false sharing with the next element. -}; - -/// `AllocationMetricsContext` represents a runtime scope for metrics, such as -/// for instance a server running in a multi-tenant scenario, where each tenant -/// would have one context associated with it. -/// -/// `AllocationMetricsContext` is not available on mobile, due to lack of -/// thread-local storage support on iOS. -struct AllocationMetricsContext { -public: - AllocationMetricsContext(); - ~AllocationMetricsContext(); - -#if !REALM_MOBILE - /// Get the thread-specific AllocationMetricsContext. If none has been set, a - /// reference to a globally-allocated "unknown" tenant will be returned. - static AllocationMetricsContext& get_current() noexcept; -#endif - - /// Get the statically-allocated "unknown" tenant. - static AllocationMetricsContext& get_unknown(); - - MeteredAllocator& get_metric(const AllocationMetricName& name) noexcept; -private: - std::unique_ptr m_metrics; - - // In debug builds, this is incremented/decremented by - // `AllocationMetricsContextScope`, and checked in the destructor, to avoid - // dangling references. - std::atomic m_refcount; - friend class AllocationMetricsContextScope; -}; - -/// Open a scope where metered memory allocations are counted towards the given -/// name. -/// -/// Creating an instance of this class causes calls to -/// `MeteredAllocator::get_default()` from the current thread to return a -/// reference to an allocator that accounts for allocations/deallocations -/// under the named metric specified as the constructor argument. -/// -/// When such an instance is destroyed, the previous scope will come back -/// in effect (if one exists; if none exists, the "unknown" metric will be -/// used). -/// -/// It is usually an error to create instances of this class with non-scope -/// lifetime, for example on the heap. For that reason, `operator new` is -/// disabled as a precaution. -/// -/// If no `AllocationMetricsContext` is current (by instantiation of -/// `AllocationMetricsContextScope`), metrics recorded in the scope introduced -/// by this instance will count towards the "unknown" context, accessible by -/// calling `AllocationMetricsContext::get_unknown()`. -class AllocationMetricNameScope final { -public: - /// Establish a scope under which all allocations will be tracked as - /// belonging to \a name. - explicit AllocationMetricNameScope(const AllocationMetricName& name) noexcept; - ~AllocationMetricNameScope(); - AllocationMetricNameScope(AllocationMetricNameScope&&) = delete; - AllocationMetricNameScope& operator=(AllocationMetricNameScope&&) = delete; - - void* operator new(std::size_t) = delete; -private: - const AllocationMetricName& m_name; - const AllocationMetricName* m_previous = nullptr; -}; - -/// Open a scope using the given context for allocation metrics. -/// -/// Creating an instance of this class causes calls to -/// `AllocationMetricsContext::get_current()` to return the provided -/// instance. This function is called when by `MeteredAllocator::get_default()` -/// to return an instance that belongs to the given context. -/// -/// When the instance is destroyed, the previous context will become active, or -/// the "unknown" context if there was none. -/// -/// It is usually an error to create instances of this class with non-scope -/// lifetime, for example on the heap. For that reason, `operator new` is -/// disabled as a precaution. -class AllocationMetricsContextScope final { -public: - explicit AllocationMetricsContextScope(AllocationMetricsContext& context) noexcept; - ~AllocationMetricsContextScope(); - AllocationMetricsContextScope(AllocationMetricsContextScope&&) = delete; - AllocationMetricsContextScope& operator=(AllocationMetricsContextScope&&) = delete; - - void* operator new(std::size_t) = delete; - -private: - AllocationMetricsContext& m_context; - AllocationMetricsContext& m_previous; -}; - - -/// Convenience STL-compatible allocator that counts allocations as part of the -/// current AllocationMetricNameScope. -template -using MeteredSTLAllocator = STLAllocator; - - -// Implementation: - -inline const char* AllocationMetricName::name() const noexcept -{ - return m_name; -} - -inline size_t AllocationMetricName::index() const noexcept -{ - return m_index; -} - -inline const AllocationMetricName* AllocationMetricName::next() const noexcept -{ - return m_next; -} - -inline std::size_t MeteredAllocator::get_currently_allocated_bytes() const noexcept -{ - return get_total_allocated_bytes() - get_total_deallocated_bytes(); -} - -inline std::size_t MeteredAllocator::get_total_allocated_bytes() const noexcept -{ - return m_allocated_bytes.load(std::memory_order_relaxed); -} - -inline std::size_t MeteredAllocator::get_total_deallocated_bytes() const noexcept -{ - return m_deallocated_bytes.load(std::memory_order_relaxed); -} - -inline void* MeteredAllocator::allocate(size_t size, size_t align) -{ - void* ptr = DefaultAllocator::get_default().allocate(size, align); - did_allocate_bytes(size); - return ptr; -} - -inline void MeteredAllocator::free(void* ptr, size_t size) noexcept -{ - DefaultAllocator::get_default().free(ptr, size); - did_free_bytes(size); -} - -inline void MeteredAllocator::did_allocate_bytes(std::size_t size) noexcept -{ -#if !REALM_MOBILE - m_allocated_bytes.fetch_add(size, std::memory_order_relaxed); -#else - static_cast(size); -#endif -} - -inline void MeteredAllocator::did_free_bytes(std::size_t size) noexcept -{ -#if !REALM_MOBILE - m_deallocated_bytes.fetch_add(size, std::memory_order_relaxed); -#else - static_cast(size); -#endif -} -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_ALLOCATION_METRICS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/allocator.hpp b/Lesson14/Pods/Realm/include/core/realm/util/allocator.hpp deleted file mode 100644 index c0a0a83..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/allocator.hpp +++ /dev/null @@ -1,398 +0,0 @@ -/************************************************************************* - * - * Copyright 2018 Realm Inc. - * - * 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 REALM_UTIL_ALLOCATOR_HPP -#define REALM_UTIL_ALLOCATOR_HPP - -#include -#include -#include - -namespace realm { -namespace util { - -/// Dynamic heap allocation interface. -/// -/// Implementors may optionally implement a static method `get_default()`, which -/// should return a reference to an allocator instance. This allows -/// `STLAllocator` to be default-constructed. -/// -/// NOTE: This base class is not related to the `realm::Allocator` interface, -/// which is used in the context of allocating memory inside a Realm file. -struct AllocatorBase { - static constexpr std::size_t max_alignment = 16; // FIXME: This is arch-dependent - - /// Allocate \a size bytes at aligned at \a align. - /// - /// May throw `std::bad_alloc` if allocation fails. May **NOT** return - /// an invalid pointer (such as `nullptr`). - virtual void* allocate(std::size_t size, std::size_t align) = 0; - - /// Free the previously allocated block of memory. \a size is not required - /// to be accurate, and is only provided for statistics and debugging - /// purposes. - /// - /// \a ptr may be `nullptr`, in which case this shall be a noop. - virtual void free(void* ptr, size_t size) noexcept = 0; -}; - -/// Implementation of AllocatorBase that uses `operator new`/`operator delete`. -/// -/// Using this allocator with standard containers is zero-overhead: No -/// additional storage is required at any level. -struct DefaultAllocator final : AllocatorBase { - /// Return a reference to a global singleton. - /// - /// This method is thread-safe. - static DefaultAllocator& get_default() noexcept; - - /// Allocate memory (using `operator new`). - /// - /// \a align must not exceed `max_alignment` before C++17. - /// - /// This method is thread-safe. - void* allocate(std::size_t size, std::size_t align) final; - - /// Free memory (using `operator delete`). - /// - /// If \a ptr equals `nullptr`, this is a no-op. - /// - /// This method is thread-safe. - void free(void* ptr, std::size_t size) noexcept final; - -private: - static DefaultAllocator g_instance; - DefaultAllocator() - { - } -}; - -template -struct STLDeleter; - -namespace detail { -/// Base class for things that hold a reference to an allocator. The default -/// implementation carries a pointer to the allocator instance. Singleton -/// allocators (such as `DefaultAllocator`) may specialize this class such that -/// no extra storage is needed. -template -struct GetAllocator { - // Note: Some allocators may not define get_default(). This is OK, and - // this constructor will not be instantiated (SFINAE). - GetAllocator() noexcept - : m_allocator(&Allocator::get_default()) - { - } - - template - GetAllocator(A& allocator) noexcept - : m_allocator(&allocator) - { - } - - template - GetAllocator& operator=(const GetAllocator& other) noexcept - { - m_allocator = &other.get_allocator(); - return *this; - } - - Allocator& get_allocator() const noexcept - { - return *m_allocator; - } - - bool operator==(const GetAllocator& other) const noexcept - { - return m_allocator == other.m_allocator; - } - - bool operator!=(const GetAllocator& other) const noexcept - { - return m_allocator != other.m_allocator; - } - - Allocator* m_allocator; -}; - -/// Specialization for `DefaultAllocator` that has zero size, i.e. no extra -/// storage requirements compared with `std::allocator`. -template <> -struct GetAllocator { - GetAllocator() noexcept - { - } - - GetAllocator(DefaultAllocator&) noexcept - { - } - - DefaultAllocator& get_allocator() const noexcept - { - return DefaultAllocator::get_default(); - } - - bool operator==(const GetAllocator&) const noexcept - { - return true; - } - - bool operator!=(const GetAllocator&) const noexcept - { - return false; - } -}; -} // namespace detail - -/// STL-compatible static dispatch bridge to a dynamic implementation of -/// `AllocatorBase`. Wraps a pointer to an object that adheres to the -/// `AllocatorBase` interface. It is optional whether the `Allocator` class -/// template argument actually derives from `AllocatorBase`. -/// -/// The intention is that users of this class can set `Allocator` to the -/// nearest-known base class of the expected allocator implementations, such -/// that appropriate devirtualization can take place. -template -struct STLAllocator : detail::GetAllocator { - using value_type = T; - using Deleter = STLDeleter; - - // These typedefs are optional, but GCC 4.9 requires them when using the - // allocator together with std::map, std::basic_string, etc. - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using reference = T&; - using const_reference = const T&; - using pointer = T*; - using const_pointer = const T*; - - /// The default constructor is only availble when the static method - /// `Allocator::get_default()` exists. - STLAllocator() noexcept - { - } - - constexpr STLAllocator(Allocator& base) noexcept - : detail::GetAllocator(base) - { - } - template - constexpr STLAllocator(const STLAllocator& other) noexcept - : detail::GetAllocator(other.get_allocator()) - { - } - - STLAllocator& operator=(const STLAllocator& other) noexcept = default; - - T* allocate(std::size_t n) - { - static_assert(alignof(T) <= Allocator::max_alignment, "Over-aligned allocation"); - void* ptr = this->get_allocator().allocate(sizeof(T) * n, alignof(T)); - return static_cast(ptr); - } - - void deallocate(T* ptr, std::size_t n) noexcept - { - this->get_allocator().free(ptr, sizeof(T) * n); - } - - operator Allocator&() const - { - return this->get_allocator(); - } - - template - struct rebind { - using other = STLAllocator; - }; - - // construct() and destroy() are optional, but are required by some - // containers under GCC 4.9 (verified for at least std::list). - template - void construct(T* ptr, Args&&... args) - { - ::new (ptr) T(std::forward(args)...); - } - - template - void destroy(U* ptr) - { - ptr->~U(); - } - -private: - template - friend struct STLAllocator; -}; - -template -struct STLDeleter : detail::GetAllocator { - // The reason for this member is to accurately pass `size` to `free()` when - // deallocating. `sizeof(T)` may not be good enough, because the pointer may - // have been cast to a relative type of different size. - size_t m_size; - - explicit STLDeleter(Allocator& allocator) noexcept - : STLDeleter(0, allocator) - { - } - explicit STLDeleter(size_t size, Allocator& allocator) noexcept - : detail::GetAllocator(allocator) - , m_size(size) - { - } - - template - STLDeleter(const STLDeleter& other) noexcept - : detail::GetAllocator(other.get_allocator()) - , m_size(other.m_size) - { - } - - void operator()(T* ptr) - { - ptr->~T(); - this->get_allocator().free(ptr, m_size); - } -}; - -template -struct STLDeleter : detail::GetAllocator { - // Note: Array-allocated pointers cannot be upcast to base classes, because - // of array slicing. - size_t m_count; - explicit STLDeleter(Allocator& allocator) noexcept - : STLDeleter(0, allocator) - { - } - explicit STLDeleter(size_t count, Allocator& allocator) noexcept - : detail::GetAllocator(allocator) - , m_count(count) - { - } - - template - STLDeleter(const STLDeleter& other) noexcept - : detail::GetAllocator(other.get_allocator()) - , m_count(other.m_count) - { - } - - template - STLDeleter& operator=(const STLDeleter& other) noexcept - { - static_cast&>(*this) = - static_cast&>(other); - m_count = other.m_count; - return *this; - } - - void operator()(T* ptr) - { - for (size_t i = 0; i < m_count; ++i) { - ptr[i].~T(); - } - this->get_allocator().free(ptr, m_count * sizeof(T)); - } -}; - -/// make_unique with custom allocator (non-array version) -template -auto make_unique(Allocator& allocator, Args&&... args) - -> std::enable_if_t::value, std::unique_ptr>> -{ - void* memory = allocator.allocate(sizeof(T), alignof(T)); // Throws - T* ptr; - try { - ptr = new (memory) T(std::forward(args)...); // Throws - } - catch (...) { - allocator.free(memory, sizeof(T)); - throw; - } - std::unique_ptr> result{ptr, STLDeleter{sizeof(T), allocator}}; - return result; -} - -/// make_unique with custom allocator supporting `get_default()` -/// (non-array-version) -template -auto make_unique(Args&&... args) - -> std::enable_if_t::value, std::unique_ptr>> -{ - return make_unique(Allocator::get_default(), std::forward(args)...); -} - -/// make_unique with custom allocator (array version) -template -auto make_unique(Allocator& allocator, size_t count) - -> std::enable_if_t::value, std::unique_ptr>> -{ - using T = std::remove_extent_t; - void* memory = allocator.allocate(sizeof(T) * count, alignof(T)); // Throws - T* ptr = reinterpret_cast(memory); - size_t constructed = 0; - try { - // FIXME: Can't use array placement new, because MSVC has a buggy - // implementation of it. :-( - while (constructed < count) { - new (&ptr[constructed]) T; // Throws - ++constructed; - } - } - catch (...) { - for (size_t i = 0; i < constructed; ++i) { - ptr[i].~T(); - } - allocator.free(memory, sizeof(T) * count); - throw; - } - std::unique_ptr> result{ptr, STLDeleter{count, allocator}}; - return result; -} - -/// make_unique with custom allocator supporting `get_default()` (array version) -template -auto make_unique(size_t count) - -> std::enable_if_t::value, std::unique_ptr>> -{ - return make_unique(Allocator::get_default(), count); -} - - -// Implementation: - -inline DefaultAllocator& DefaultAllocator::get_default() noexcept -{ - return g_instance; -} - -inline void* DefaultAllocator::allocate(std::size_t size, std::size_t) -{ - return new char[size]; -} - -inline void DefaultAllocator::free(void* ptr, std::size_t) noexcept -{ - delete[] static_cast(ptr); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_ALLOCATOR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/any.hpp b/Lesson14/Pods/Realm/include/core/realm/util/any.hpp deleted file mode 100644 index 5ac72b2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/any.hpp +++ /dev/null @@ -1,165 +0,0 @@ -//////////////////////////////////////////////////////////////////////////// -// -// Copyright 2017 Realm Inc. -// -// 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 REALM_UTIL_ANY_HPP -#define REALM_UTIL_ANY_HPP - -#include -#include -#include -#include - -#include - -namespace realm { -namespace util { - -using bad_cast = ExceptionWithBacktrace; - -// A naive implementation of C++17's std::any -// This does not perform the small-object optimization or make any particular -// attempt at being performant -class Any final { -public: - // Constructors - - Any() = default; - Any(Any&&) noexcept = default; - ~Any() = default; - Any& operator=(Any&&) noexcept = default; - - Any(Any const& rhs) - : m_value(rhs.m_value ? rhs.m_value->copy() : nullptr) - { - } - - template::type, Any>::value>::type> - Any(T&& value) - : m_value(std::make_unique::type>>(std::forward(value))) - { - } - - Any& operator=(Any const& rhs) - { - m_value = rhs.m_value ? rhs.m_value->copy() : nullptr; - return *this; - } - - template::type, Any>::value>::type> - Any& operator=(T&& value) - { - m_value = std::make_unique::type>>(std::forward(value)); - return *this; - } - - // Modifiers - - void reset() noexcept { m_value.reset(); } - void swap(Any& rhs) noexcept { std::swap(m_value, rhs.m_value); } - - // Observers - - bool has_value() const noexcept { return m_value != nullptr; } - std::type_info const& type() const noexcept { return m_value ? m_value->type() : typeid(void); } - -private: - struct ValueBase { - virtual ~ValueBase() noexcept { } - virtual std::type_info const& type() const noexcept = 0; - virtual std::unique_ptr copy() const = 0; - }; - template - struct Value : ValueBase { - T value; - template Value(U&& v) : value(std::forward(v)) { } - - std::type_info const& type() const noexcept override { return typeid(T); } - std::unique_ptr copy() const override - { - return std::make_unique>(value); - } - }; - std::unique_ptr m_value; - - template - friend const T* any_cast(const Any* operand) noexcept; - template - friend T* any_cast(Any* operand) noexcept; - - template - const T* cast() const noexcept - { - return &static_cast*>(m_value.get())->value; - } - - template - T* cast() noexcept - { - return &static_cast*>(m_value.get())->value; - } -}; - -template -T any_cast(Any const& value) -{ - auto ptr = any_cast::type>::type>(&value); - if (!ptr) - throw bad_cast(); - return *ptr; -} - -template -T any_cast(Any& value) -{ - auto ptr = any_cast::type>(&value); - if (!ptr) - throw bad_cast(); - return *ptr; -} - -template -T any_cast(Any&& value) -{ - auto ptr = any_cast::type>(&value); - if (!ptr) - throw bad_cast(); - return std::move(*ptr); -} - -template -T* any_cast(Any* value) noexcept -{ - return value && value->type() == typeid(T) ? value->cast() : nullptr; -} - -template -const T* any_cast(const Any* value) noexcept -{ - return value && value->type() == typeid(T) ? value->cast() : nullptr; -} -} // namespace util -} // namespace realm - -namespace std { -inline void swap(realm::util::Any& lhs, realm::util::Any& rhs) noexcept -{ - lhs.swap(rhs); -} -} // namespace std - -#endif // REALM_UTIL_ANY_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/assert.hpp b/Lesson14/Pods/Realm/include/core/realm/util/assert.hpp deleted file mode 100644 index 5e75066..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/assert.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_ASSERT_HPP -#define REALM_UTIL_ASSERT_HPP - -#include -#include - -#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG) -#define REALM_ASSERTIONS_ENABLED 1 -#else -#define REALM_ASSERTIONS_ENABLED 0 -#endif - -#define REALM_ASSERT_RELEASE(condition) \ - (REALM_LIKELY(condition) ? static_cast(0) \ - : realm::util::terminate("Assertion failed: " #condition, __FILE__, __LINE__)) - -#if REALM_ASSERTIONS_ENABLED -#define REALM_ASSERT(condition) REALM_ASSERT_RELEASE(condition) -#else -#define REALM_ASSERT(condition) static_cast(sizeof bool(condition)) -#endif - -#ifdef REALM_DEBUG -#define REALM_ASSERT_DEBUG(condition) REALM_ASSERT_RELEASE(condition) -#else -#define REALM_ASSERT_DEBUG(condition) static_cast(sizeof bool(condition)) -#endif - -#define REALM_STRINGIFY(X) #X - -#define REALM_ASSERT_RELEASE_EX(condition, ...) \ - (REALM_LIKELY(condition) ? static_cast(0) \ - : realm::util::terminate_with_info("Assertion failed: " #condition, __LINE__, __FILE__, \ - REALM_STRINGIFY((__VA_ARGS__)), __VA_ARGS__)) - -#ifdef REALM_DEBUG -#define REALM_ASSERT_DEBUG_EX REALM_ASSERT_RELEASE_EX -#else -#define REALM_ASSERT_DEBUG_EX(condition, ...) static_cast(sizeof bool(condition)) -#endif - -// Becase the assert is used in noexcept methods, it's a bad idea to allocate -// buffer space for the message so therefore we must pass it to terminate which -// will 'cerr' it for us without needing any buffer -#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG) - -#define REALM_ASSERT_EX REALM_ASSERT_RELEASE_EX - -#define REALM_ASSERT_3(left, cmp, right) \ - (REALM_LIKELY((left)cmp(right)) ? static_cast(0) \ - : realm::util::terminate("Assertion failed: " \ - "" #left " " #cmp " " #right, \ - __FILE__, __LINE__, left, right)) - -#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \ - (REALM_LIKELY(((left1)cmp1(right1))logical((left2)cmp2(right2))) \ - ? static_cast(0) \ - : realm::util::terminate("Assertion failed: " \ - "" #left1 " " #cmp1 " " #right1 " " #logical " " \ - "" #left2 " " #cmp2 " " #right2, \ - __FILE__, __LINE__, left1, right1, left2, right2)) - -#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \ - (REALM_LIKELY(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))) \ - ? static_cast(0) \ - : realm::util::terminate("Assertion failed: " \ - "" #left1 " " #cmp1 " " #right1 " " #logical1 " " \ - "" #left2 " " #cmp2 " " #right2 " " #logical2 " " \ - "" #left3 " " #cmp3 " " #right3, \ - __FILE__, __LINE__, left1, right1, left2, right2, left3, right3)) -#else -#define REALM_ASSERT_EX(condition, ...) static_cast(sizeof bool(condition)) -#define REALM_ASSERT_3(left, cmp, right) static_cast(sizeof bool((left)cmp(right))) -#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \ - static_cast(sizeof bool(((left1)cmp1(right1))logical((left2)cmp2(right2)))) -#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \ - static_cast(sizeof bool(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3)))) -#endif - -#define REALM_UNREACHABLE() realm::util::terminate("Unreachable code", __FILE__, __LINE__) -#ifdef REALM_COVER -#define REALM_COVER_NEVER(x) false -#define REALM_COVER_ALWAYS(x) true -#else -#define REALM_COVER_NEVER(x) (x) -#define REALM_COVER_ALWAYS(x) (x) -#endif - -#endif // REALM_UTIL_ASSERT_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/backtrace.hpp b/Lesson14/Pods/Realm/include/core/realm/util/backtrace.hpp deleted file mode 100644 index 8011023..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/backtrace.hpp +++ /dev/null @@ -1,226 +0,0 @@ -/************************************************************************* - * - * Copyright 2018 Realm Inc. - * - * 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 REALM_UTIL_BACKTRACE_HPP -#define REALM_UTIL_BACKTRACE_HPP - -#include -#include -#include - -namespace realm { -namespace util { - -/// Backtrace encapsulates a stack trace, usually as captured by `backtrace()` -/// and `backtrace_symbols()` (or platform-specific equivalents). -struct Backtrace { - /// Capture a symbolicated stack trace, excluding the call to `capture()` - /// itself. If any error occurs while capturing the stack trace or - /// translating symbol names, a `Backtrace` object is returned containing a - /// single line describing the error. - /// - /// This function only allocates memory as part of calling - /// `backtrace_symbols()` (or the current platform's equivalent). - static Backtrace capture() noexcept; - - /// Print the backtrace to the stream. Each line is separated by a newline. - /// The format of the output is unspecified. - void print(std::ostream&) const; - - /// Construct an empty stack trace. - Backtrace() noexcept - { - } - - /// Move constructor. This operation cannot fail. - Backtrace(Backtrace&&) noexcept; - - /// Copy constructor. See the copy assignment operator. - Backtrace(const Backtrace&) noexcept; - - ~Backtrace(); - - /// Move assignment operator. This operation cannot fail. - Backtrace& operator=(Backtrace&&) noexcept; - - /// Copy assignment operator. Copying a `Backtrace` object may result in a - /// memory allocation. If such an allocation fails, the backtrace is - /// replaced with a single line describing the error. - Backtrace& operator=(const Backtrace&) noexcept; - -private: - Backtrace(void* memory, const char* const* strs, size_t len) - : m_memory(memory) - , m_strs(strs) - , m_len(len) - { - } - Backtrace(void* memory, size_t len) - : m_memory(memory) - , m_strs(static_cast(memory)) - , m_len(len) - { - } - - // m_memory is a pointer to the memory block returned by - // `backtrace_symbols()`. It is usually equal to `m_strs`, except in the - // case where an error has occurred and `m_strs` points to statically - // allocated memory describing the error. - // - // When `m_memory` is non-null, the memory is owned by this object. - void* m_memory = nullptr; - - // A pointer to a list of string pointers describing the stack trace (same - // format as returned by `backtrace_symbols()`). - const char* const* m_strs = nullptr; - - // Number of entries in this stack trace. - size_t m_len = 0; -}; - -namespace detail { - -class ExceptionWithBacktraceBase { -public: - ExceptionWithBacktraceBase() - : m_backtrace(util::Backtrace::capture()) - { - } - const util::Backtrace& backtrace() const noexcept - { - return m_backtrace; - } - virtual const char* message() const noexcept = 0; - -protected: - util::Backtrace m_backtrace; - // Cannot use Optional here, because Optional wants to use - // ExceptionWithBacktrace. - mutable bool m_has_materialized_message = false; - mutable std::string m_materialized_message; - - // Render the message and the backtrace into m_message_with_backtrace. If an - // exception is thrown while rendering the message, the message without the - // backtrace will be returned. - const char* materialize_message() const noexcept; -}; - -} // namespace detail - -/// Base class for exceptions that record a stack trace of where they were -/// thrown. -/// -/// The template argument is expected to be an exception type conforming to the -/// standard library exception API (`std::exception` and friends). -/// -/// It is possible to opt in to exception backtraces in two ways, (a) as part of -/// the exception type, in which case the backtrace will always be included for -/// all exceptions of that type, or (b) at the call-site of an opaque exception -/// type, in which case it is up to the throw-site to decide whether a backtrace -/// should be included. -/// -/// Example (a): -/// ``` -/// class MyException : ExceptionWithBacktrace { -/// public: -/// const char* message() const noexcept override -/// { -/// return "MyException error message"; -/// } -/// }; -/// -/// ... -/// -/// try { -/// throw MyException{}; -/// } -/// catch (const MyException& ex) { -/// // Print the backtrace without the message: -/// std::cerr << ex.backtrace() << "\n"; -/// // Print the exception message and the backtrace: -/// std::cerr << ex.what() << "\n"; -/// // Print the exception message without the backtrace: -/// std::cerr << ex.message() << "\n"; -/// } -/// ``` -/// -/// Example (b): -/// ``` -/// class MyException : std::exception { -/// public: -/// const char* what() const noexcept override -/// { -/// return "MyException error message"; -/// } -/// }; -/// -/// ... -/// -/// try { -/// throw ExceptionWithBacktrace{}; -/// } -/// catch (const MyException& ex) { -/// // Print the exception message and the backtrace: -/// std::cerr << ex.what() << "\n"; -/// } -/// ``` -template -class ExceptionWithBacktrace : public Base, public detail::ExceptionWithBacktraceBase { -public: - template - inline ExceptionWithBacktrace(Args&&... args) - : Base(std::forward(args)...) - , detail::ExceptionWithBacktraceBase() // backtrace captured here - { - } - - /// Return the message of the exception, including the backtrace of where - /// the exception was thrown. - const char* what() const noexcept final - { - return materialize_message(); - } - - /// Return the message of the exception without the backtrace. The default - /// implementation calls `Base::what()`. - const char* message() const noexcept override - { - return Base::what(); - } -}; - -// Wrappers for standard exception types with backtrace support -using runtime_error = ExceptionWithBacktrace; -using range_error = ExceptionWithBacktrace; -using overflow_error = ExceptionWithBacktrace; -using underflow_error = ExceptionWithBacktrace; -using bad_alloc = ExceptionWithBacktrace; -using invalid_argument = ExceptionWithBacktrace; -using out_of_range = ExceptionWithBacktrace; -using logic_error = ExceptionWithBacktrace; - -} // namespace util -} // namespace realm - -inline std::ostream& operator<<(std::ostream& os, const realm::util::Backtrace& bt) -{ - bt.print(os); - return os; -} - -#endif // REALM_UTIL_BACKTRACE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/base64.hpp b/Lesson14/Pods/Realm/include/core/realm/util/base64.hpp deleted file mode 100644 index 8d808a6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/base64.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_BASE64_HPP -#define REALM_UTIL_BASE64_HPP - -#include -#include -#include - -namespace realm { -namespace util { - - -/// base64_encode() encodes the bnary data in \param in_buffer of size \param in_buffer_size. -/// The encoded data is placed in \param out_buffer. The size of \param \out_buffer is passed in -/// \param out_buffer_size. The output buffer \param out_buffer must be -/// large enough to hold the base64 encoded data. The size can be obtained from the function -/// base64_encoded_size. \param out_buffer_size is only used to assert that the output buffer is -/// large enough. -size_t base64_encode(const char *in_buffer, size_t in_buffer_size, char* out_buffer, size_t out_buffer_size) noexcept; - -/// base64_encoded_size() returns the exact size of the base64 encoded -/// data as a function of the size of the input data. -inline size_t base64_encoded_size(size_t in_buffer_size) noexcept -{ - return 4 * ((in_buffer_size + 2) / 3); -} - - -/// Decode base64-encoded string in input, and places the result in out_buffer. -/// The length of the out_buffer must be at least 3 * input.size() / 4. -/// -/// The input must be padded base64 (i.e. the number of non-whitespace -/// characters in the input must be a multiple of 4). Whitespace (spaces, tabs, -/// newlines) is ignored. -/// -/// The algorithm stops when the first character not in the base64 character -/// set is encountered, or when the end of the input is reached. -/// -/// \returns the number of successfully decoded bytes written to out_buffer, or -/// none if the whole input was not valid base64. -Optional base64_decode(StringData input, char* out_buffer, size_t out_buffer_len) noexcept; - -/// Return an upper bound on the decoded size of a Base64-encoded data -/// stream of length \a base64_size. The returned value is suitable for -/// allocation of buffers containing decoded data. -inline size_t base64_decoded_size(size_t base64_size) noexcept -{ - return (base64_size * 3 + 3) / 4; -} - - - -/// base64_decode_to_vector() is a convenience function that decodes \param -/// encoded and returns the result in a std::vector with the correct size. -/// This function returns none if the input is invalid. -Optional> base64_decode_to_vector(StringData encoded); - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_BASE64_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/basic_system_errors.hpp b/Lesson14/Pods/Realm/include/core/realm/util/basic_system_errors.hpp deleted file mode 100644 index 8f7a626..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/basic_system_errors.hpp +++ /dev/null @@ -1,89 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP -#define REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP - -#include -#include - - -namespace realm { -namespace util { -namespace error { - -enum basic_system_errors { - /// Address family not supported by protocol. - address_family_not_supported = EAFNOSUPPORT, - - /// Invalid argument. - invalid_argument = EINVAL, - - /// Cannot allocate memory. - no_memory = ENOMEM, - - /// Operation cancelled. - operation_aborted = ECANCELED, - - /// Connection aborted. - connection_aborted = ECONNABORTED, - - /// Connection reset by peer - connection_reset = ECONNRESET, - - /// Broken pipe - broken_pipe = EPIPE, - - /// Resource temporarily unavailable - resource_unavailable_try_again = EAGAIN, -}; - -std::error_code make_error_code(basic_system_errors) noexcept; - -} // namespace error -} // namespace util -} // namespace realm - -namespace std { - -template <> -class is_error_code_enum { -public: - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace util { - -std::error_code make_basic_system_error_code(int) noexcept; - - -// implementation - -inline std::error_code make_basic_system_error_code(int err) noexcept -{ - using namespace error; - return make_error_code(basic_system_errors(err)); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_BASIC_SYSTEM_ERRORS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/bind_ptr.hpp b/Lesson14/Pods/Realm/include/core/realm/util/bind_ptr.hpp deleted file mode 100644 index e5b8a99..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/bind_ptr.hpp +++ /dev/null @@ -1,484 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_BIND_PTR_HPP -#define REALM_UTIL_BIND_PTR_HPP - -#include -#include -#include -#include - -#include -#include - - -namespace realm { -namespace util { - -class bind_ptr_base { -public: - struct adopt_tag { - }; -}; - - -/// A generic intrusive smart pointer that binds itself explicitely to -/// the target object. -/// -/// This class is agnostic towards what 'binding' means for the target -/// object, but a common use is 'reference counting'. See RefCountBase -/// for an example of that. -/// -/// This smart pointer implementation assumes that the target object -/// destructor never throws. -template -class bind_ptr : public bind_ptr_base { -public: - constexpr bind_ptr() noexcept - : m_ptr(nullptr) - { - } - ~bind_ptr() noexcept - { - unbind(); - } - - explicit bind_ptr(T* p) noexcept - { - bind(p); - } - template - explicit bind_ptr(U* p) noexcept - { - bind(p); - } - - bind_ptr(T* p, adopt_tag) noexcept - { - m_ptr = p; - } - template - bind_ptr(U* p, adopt_tag) noexcept - { - m_ptr = p; - } - - // Copy construct - bind_ptr(const bind_ptr& p) noexcept - { - bind(p.m_ptr); - } - template - bind_ptr(const bind_ptr& p) noexcept - { - bind(p.m_ptr); - } - - // Copy assign - bind_ptr& operator=(const bind_ptr& p) noexcept - { - bind_ptr(p).swap(*this); - return *this; - } - template - bind_ptr& operator=(const bind_ptr& p) noexcept - { - bind_ptr(p).swap(*this); - return *this; - } - - // Move construct - bind_ptr(bind_ptr&& p) noexcept - : m_ptr(p.release()) - { - } - template - bind_ptr(bind_ptr&& p) noexcept - : m_ptr(p.release()) - { - } - - // Move assign - bind_ptr& operator=(bind_ptr&& p) noexcept - { - bind_ptr(std::move(p)).swap(*this); - return *this; - } - template - bind_ptr& operator=(bind_ptr&& p) noexcept - { - bind_ptr(std::move(p)).swap(*this); - return *this; - } - - //@{ - // Comparison - template - bool operator==(const bind_ptr&) const noexcept; - - template - bool operator==(U*) const noexcept; - - template - bool operator!=(const bind_ptr&) const noexcept; - - template - bool operator!=(U*) const noexcept; - - template - bool operator<(const bind_ptr&) const noexcept; - - template - bool operator<(U*) const noexcept; - - template - bool operator>(const bind_ptr&) const noexcept; - - template - bool operator>(U*) const noexcept; - - template - bool operator<=(const bind_ptr&) const noexcept; - - template - bool operator<=(U*) const noexcept; - - template - bool operator>=(const bind_ptr&) const noexcept; - - template - bool operator>=(U*) const noexcept; - //@} - - // Dereference - T& operator*() const noexcept - { - return *m_ptr; - } - T* operator->() const noexcept - { - return m_ptr; - } - - explicit operator bool() const noexcept - { - return m_ptr != 0; - } - - T* get() const noexcept - { - return m_ptr; - } - void reset() noexcept - { - bind_ptr().swap(*this); - } - void reset(T* p) noexcept - { - bind_ptr(p).swap(*this); - } - template - void reset(U* p) noexcept - { - bind_ptr(p).swap(*this); - } - - T* release() noexcept - { - T* const p = m_ptr; - m_ptr = nullptr; - return p; - } - - void swap(bind_ptr& p) noexcept - { - std::swap(m_ptr, p.m_ptr); - } - friend void swap(bind_ptr& a, bind_ptr& b) noexcept - { - a.swap(b); - } - -protected: - struct casting_move_tag { - }; - template - bind_ptr(bind_ptr* p, casting_move_tag) noexcept - : m_ptr(static_cast(p->release())) - { - } - -private: - T* m_ptr; - - void bind(T* p) noexcept - { - if (p) - p->bind_ptr(); - m_ptr = p; - } - void unbind() noexcept - { - if (m_ptr) - m_ptr->unbind_ptr(); - } - - template - friend class bind_ptr; -}; - - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const bind_ptr& p) -{ - out << static_cast(p.get()); - return out; -} - - -//@{ -// Comparison -template -bool operator==(T*, const bind_ptr&) noexcept; -template -bool operator!=(T*, const bind_ptr&) noexcept; -template -bool operator<(T*, const bind_ptr&) noexcept; -template -bool operator>(T*, const bind_ptr&) noexcept; -template -bool operator<=(T*, const bind_ptr&) noexcept; -template -bool operator>=(T*, const bind_ptr&) noexcept; -//@} - - -/// Polymorphic convenience base class for reference counting objects. -/// -/// Together with bind_ptr, this class delivers simple instrusive -/// reference counting. -/// -/// \sa bind_ptr -class RefCountBase { -public: - RefCountBase() noexcept - : m_ref_count(0) - { - } - virtual ~RefCountBase() noexcept - { - REALM_ASSERT(m_ref_count == 0); - } - - RefCountBase(const RefCountBase&) = delete; - RefCountBase(RefCountBase&&) = delete; - - void operator=(const RefCountBase&) = delete; - void operator=(RefCountBase&&) = delete; - -protected: - void bind_ptr() const noexcept - { - ++m_ref_count; - } - void unbind_ptr() const noexcept - { - if (--m_ref_count == 0) - delete this; - } - -private: - mutable unsigned long m_ref_count; - - template - friend class bind_ptr; -}; - - -/// Same as RefCountBase, but this one makes the copying of, and the -/// destruction of counted references thread-safe. -/// -/// \sa RefCountBase -/// \sa bind_ptr -class AtomicRefCountBase { -public: - AtomicRefCountBase() noexcept - : m_ref_count(0) - { - } - virtual ~AtomicRefCountBase() noexcept - { - REALM_ASSERT(m_ref_count == 0); - } - - AtomicRefCountBase(const AtomicRefCountBase&) = delete; - AtomicRefCountBase(AtomicRefCountBase&&) = delete; - - void operator=(const AtomicRefCountBase&) = delete; - void operator=(AtomicRefCountBase&&) = delete; - -protected: - // FIXME: Operators ++ and -- as used below use - // std::memory_order_seq_cst. This can be optimized. - void bind_ptr() const noexcept - { - ++m_ref_count; - } - void unbind_ptr() const noexcept - { - if (--m_ref_count == 0) { - delete this; - } - } - -private: - mutable std::atomic m_ref_count; - - template - friend class bind_ptr; -}; - - -// Implementation: - -template -template -bool bind_ptr::operator==(const bind_ptr& p) const noexcept -{ - return m_ptr == p.m_ptr; -} - -template -template -bool bind_ptr::operator==(U* p) const noexcept -{ - return m_ptr == p; -} - -template -template -bool bind_ptr::operator!=(const bind_ptr& p) const noexcept -{ - return m_ptr != p.m_ptr; -} - -template -template -bool bind_ptr::operator!=(U* p) const noexcept -{ - return m_ptr != p; -} - -template -template -bool bind_ptr::operator<(const bind_ptr& p) const noexcept -{ - return m_ptr < p.m_ptr; -} - -template -template -bool bind_ptr::operator<(U* p) const noexcept -{ - return m_ptr < p; -} - -template -template -bool bind_ptr::operator>(const bind_ptr& p) const noexcept -{ - return m_ptr > p.m_ptr; -} - -template -template -bool bind_ptr::operator>(U* p) const noexcept -{ - return m_ptr > p; -} - -template -template -bool bind_ptr::operator<=(const bind_ptr& p) const noexcept -{ - return m_ptr <= p.m_ptr; -} - -template -template -bool bind_ptr::operator<=(U* p) const noexcept -{ - return m_ptr <= p; -} - -template -template -bool bind_ptr::operator>=(const bind_ptr& p) const noexcept -{ - return m_ptr >= p.m_ptr; -} - -template -template -bool bind_ptr::operator>=(U* p) const noexcept -{ - return m_ptr >= p; -} - -template -bool operator==(T* a, const bind_ptr& b) noexcept -{ - return b == a; -} - -template -bool operator!=(T* a, const bind_ptr& b) noexcept -{ - return b != a; -} - -template -bool operator<(T* a, const bind_ptr& b) noexcept -{ - return b > a; -} - -template -bool operator>(T* a, const bind_ptr& b) noexcept -{ - return b < a; -} - -template -bool operator<=(T* a, const bind_ptr& b) noexcept -{ - return b >= a; -} - -template -bool operator>=(T* a, const bind_ptr& b) noexcept -{ - return b <= a; -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_BIND_PTR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/buffer.hpp b/Lesson14/Pods/Realm/include/core/realm/util/buffer.hpp deleted file mode 100644 index d65bdaf..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/buffer.hpp +++ /dev/null @@ -1,302 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_BUFFER_HPP -#define REALM_UTIL_BUFFER_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace realm { -namespace util { - - -/// A simple buffer concept that owns a region of memory and knows its -/// size. -template -class Buffer { -public: - Buffer(Allocator& alloc = Allocator::get_default()) noexcept - : m_data(nullptr, STLDeleter{alloc}) - , m_size(0) - { - } - explicit Buffer(size_t initial_size, Allocator& alloc = Allocator::get_default()); - Buffer(Buffer&&) noexcept = default; - Buffer& operator=(Buffer&&) noexcept = default; - - T& operator[](size_t i) noexcept - { - return m_data[i]; - } - const T& operator[](size_t i) const noexcept - { - return m_data[i]; - } - - T* data() noexcept - { - return m_data.get(); - } - const T* data() const noexcept - { - return m_data.get(); - } - size_t size() const noexcept - { - return m_size; - } - - /// False iff the data() returns null. - explicit operator bool() const noexcept - { - return bool(m_data); - } - - /// Discards the original contents. - void set_size(size_t new_size); - - /// \param new_size Specifies the new buffer size. - /// \param copy_begin, copy_end Specifies a range of element - /// values to be retained. \a copy_end must be less than, or equal - /// to size(). - /// - /// \param copy_to Specifies where the retained range should be - /// copied to. `\a copy_to + \a copy_end - \a copy_begin` must be - /// less than, or equal to \a new_size. - void resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to); - - void reserve(size_t used_size, size_t min_capacity); - - void reserve_extra(size_t used_size, size_t min_extra_capacity); - - /// Release the internal buffer to the caller. - REALM_NODISCARD std::unique_ptr> release() noexcept; - - friend void swap(Buffer& a, Buffer& b) noexcept - { - using std::swap; - swap(a.m_data, b.m_data); - swap(a.m_size, b.m_size); - } - - Allocator& get_allocator() const noexcept - { - return m_data.get_deleter().get_allocator(); - } - -private: - std::unique_ptr> m_data; - size_t m_size; -}; - - -/// A buffer that can be efficiently resized. It acheives this by -/// using an underlying buffer that may be larger than the logical -/// size, and is automatically expanded in progressively larger steps. -template -class AppendBuffer { -public: - AppendBuffer(Allocator& alloc = Allocator::get_default()) noexcept; - AppendBuffer(AppendBuffer&&) noexcept = default; - AppendBuffer& operator=(AppendBuffer&&) noexcept = default; - - /// Returns the current size of the buffer. - size_t size() const noexcept; - - /// Gives read and write access to the elements. - T* data() noexcept; - - /// Gives read access the elements. - const T* data() const noexcept; - - /// Append the specified elements. This increases the size of this - /// buffer by \a append_data_size. If the caller has previously requested - /// a minimum capacity that is greater than, or equal to the - /// resulting size, this function is guaranteed to not throw. - void append(const T* append_data, size_t append_data_size); - - /// If the specified size is less than the current size, then the - /// buffer contents is truncated accordingly. If the specified - /// size is greater than the current size, then the extra elements - /// will have undefined values. If the caller has previously - /// requested a minimum capacity that is greater than, or equal to - /// the specified size, this function is guaranteed to not throw. - void resize(size_t new_size); - - /// This operation does not change the size of the buffer as - /// returned by size(). If the specified capacity is less than the - /// current capacity, this operation has no effect. - void reserve(size_t min_capacity); - - /// Set the size to zero. The capacity remains unchanged. - void clear() noexcept; - - /// Release the underlying buffer and reset the size. Note: The returned - /// buffer may be larger than the amount of data appended to this buffer. - /// Callers should call `size()` prior to releasing the buffer to know the - /// usable/logical size. - REALM_NODISCARD Buffer release() noexcept; - -private: - util::Buffer m_buffer; - size_t m_size; -}; - - -// Implementation: - -class BufferSizeOverflow : public std::exception { -public: - const char* what() const noexcept override - { - return "Buffer size overflow"; - } -}; - -template -inline Buffer::Buffer(size_t initial_size, A& alloc) - : m_data(util::make_unique(alloc, initial_size)) // Throws - , m_size(initial_size) -{ -} - -template -inline void Buffer::set_size(size_t new_size) -{ - m_data = util::make_unique(get_allocator(), new_size); // Throws - m_size = new_size; -} - -template -inline void Buffer::resize(size_t new_size, size_t copy_begin, size_t copy_end, size_t copy_to) -{ - auto new_data = util::make_unique(get_allocator(), new_size); // Throws - realm::safe_copy_n(m_data.get() + copy_begin, copy_end - copy_begin, new_data.get() + copy_to); - m_data = std::move(new_data); - m_size = new_size; -} - -template -inline void Buffer::reserve(size_t used_size, size_t min_capacity) -{ - size_t current_capacity = m_size; - if (REALM_LIKELY(current_capacity >= min_capacity)) - return; - size_t new_capacity = current_capacity; - - // Use growth factor 1.5. - if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_capacity, 3))) - new_capacity = std::numeric_limits::max(); - new_capacity /= 2; - - if (REALM_UNLIKELY(new_capacity < min_capacity)) - new_capacity = min_capacity; - resize(new_capacity, 0, used_size, 0); // Throws -} - -template -inline void Buffer::reserve_extra(size_t used_size, size_t min_extra_capacity) -{ - size_t min_capacity = used_size; - if (REALM_UNLIKELY(int_add_with_overflow_detect(min_capacity, min_extra_capacity))) - throw BufferSizeOverflow(); - reserve(used_size, min_capacity); // Throws -} - -template -inline std::unique_ptr> Buffer::release() noexcept -{ - m_size = 0; - return std::move(m_data); -} - - -template -inline AppendBuffer::AppendBuffer(A& alloc) noexcept - : m_buffer(alloc) - , m_size(0) -{ -} - -template -inline size_t AppendBuffer::size() const noexcept -{ - return m_size; -} - -template -inline T* AppendBuffer::data() noexcept -{ - return m_buffer.data(); -} - -template -inline const T* AppendBuffer::data() const noexcept -{ - return m_buffer.data(); -} - -template -inline void AppendBuffer::append(const T* append_data, size_t append_data_size) -{ - m_buffer.reserve_extra(m_size, append_data_size); // Throws - realm::safe_copy_n(append_data, append_data_size, m_buffer.data() + m_size); - m_size += append_data_size; -} - -template -inline void AppendBuffer::reserve(size_t min_capacity) -{ - m_buffer.reserve(m_size, min_capacity); -} - -template -inline void AppendBuffer::resize(size_t new_size) -{ - reserve(new_size); - m_size = new_size; -} - -template -inline void AppendBuffer::clear() noexcept -{ - m_size = 0; -} - -template -inline Buffer AppendBuffer::release() noexcept -{ - m_size = 0; - return std::move(m_buffer); -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_BUFFER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/buffer_stream.hpp b/Lesson14/Pods/Realm/include/core/realm/util/buffer_stream.hpp deleted file mode 100644 index be5064e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/buffer_stream.hpp +++ /dev/null @@ -1,151 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_BUFFER_STREAM_HPP -#define REALM_UTIL_BUFFER_STREAM_HPP - -#include -#include - -namespace realm { -namespace util { - - -template, class A = std::allocator > -class BasicResettableExpandableOutputStreambuf: public std::basic_stringbuf { -public: - using char_type = typename std::basic_stringbuf::char_type; - - /// Reset current writing position (std::basic_streambuf::pptr()) to the - /// beginning of the output buffer without reallocating buffer memory. - void reset() noexcept; - - //@{ - /// Get a pointer to the beginning of the output buffer - /// (std::basic_streambuf::pbase()). Note that this will change as the - /// buffer is reallocated. - char_type* data() noexcept; - const char_type* data() const noexcept; - //@} - - /// Get the number of bytes written to the output buffer since the creation - /// of the stream buffer, or since the last invocation of reset() - /// (std::basic_streambuf::pptr() - std::basic_streambuf::pbase()). - std::size_t size() const noexcept; -}; - - -template, class A = std::allocator > -class BasicResettableExpandableBufferOutputStream: public std::basic_ostream { -public: - using char_type = typename std::basic_ostream::char_type; - - BasicResettableExpandableBufferOutputStream(); - - /// Calls BasicResettableExpandableOutputStreambuf::reset(). - void reset() noexcept; - - //@{ - /// Calls BasicResettableExpandableOutputStreambuf::data(). - char_type* data() noexcept; - const char_type* data() const noexcept; - //@} - - /// Calls BasicResettableExpandableOutputStreambuf::size(). - std::size_t size() const noexcept; - -private: - BasicResettableExpandableOutputStreambuf m_streambuf; -}; - - -using ResettableExpandableBufferOutputStream = BasicResettableExpandableBufferOutputStream; - - - - -// Implementation - -template -inline void BasicResettableExpandableOutputStreambuf::reset() noexcept -{ - char_type* pbeg = this->pbase(); - char_type* pend = this->epptr(); - this->setp(pbeg, pend); -} - -template -inline typename BasicResettableExpandableOutputStreambuf::char_type* -BasicResettableExpandableOutputStreambuf::data() noexcept -{ - return this->pbase(); -} - -template -inline const typename BasicResettableExpandableOutputStreambuf::char_type* -BasicResettableExpandableOutputStreambuf::data() const noexcept -{ - return this->pbase(); -} - -template -inline std::size_t BasicResettableExpandableOutputStreambuf::size() const noexcept -{ - std::size_t size = std::size_t(this->pptr() - this->pbase()); - return size; -} - -template -inline BasicResettableExpandableBufferOutputStream:: -BasicResettableExpandableBufferOutputStream(): - std::basic_ostream(&m_streambuf) // Throws -{ -} - -template -inline void BasicResettableExpandableBufferOutputStream::reset() noexcept -{ - m_streambuf.reset(); -} - -template -inline typename BasicResettableExpandableBufferOutputStream::char_type* -BasicResettableExpandableBufferOutputStream::data() noexcept -{ - return m_streambuf.data(); -} - -template -inline const typename BasicResettableExpandableBufferOutputStream::char_type* -BasicResettableExpandableBufferOutputStream::data() const noexcept -{ - return m_streambuf.data(); -} - -template -inline std::size_t BasicResettableExpandableBufferOutputStream::size() const noexcept -{ - return m_streambuf.size(); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_BUFFER_STREAM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/call_with_tuple.hpp b/Lesson14/Pods/Realm/include/core/realm/util/call_with_tuple.hpp deleted file mode 100644 index 7d2eab0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/call_with_tuple.hpp +++ /dev/null @@ -1,66 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_CALL_WITH_TUPLE_HPP -#define REALM_UTIL_CALL_WITH_TUPLE_HPP - -#include -#include - -namespace realm { -namespace _impl { - -/// \cond doxygen_skip -/// Doxygen warns about a recursive class relation, but this is intentional. - -template -struct Indexes { -}; -template -struct GenIndexes : GenIndexes { -}; -template -struct GenIndexes<0, I...> { - typedef Indexes type; -}; - -/// \endcond - -template -auto call_with_tuple(F func, std::tuple args, Indexes) -> decltype(func(std::get(args)...)) -{ - static_cast(args); // Prevent GCC warning when tuple is empty - return func(std::get(args)...); -} - -} // namespace _impl - -namespace util { - -template -auto call_with_tuple(F func, std::tuple args) - -> decltype(_impl::call_with_tuple(std::move(func), std::move(args), - typename _impl::GenIndexes::type())) -{ - return _impl::call_with_tuple(std::move(func), std::move(args), typename _impl::GenIndexes::type()); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_CALL_WITH_TUPLE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/cf_ptr.hpp b/Lesson14/Pods/Realm/include/core/realm/util/cf_ptr.hpp deleted file mode 100644 index a1ec431..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/cf_ptr.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_CF_PTR_HPP -#define REALM_UTIL_CF_PTR_HPP - -#include - -#if REALM_PLATFORM_APPLE - -#include - -namespace realm { -namespace util { - -template -class CFPtr { -public: - explicit CFPtr(Ref ref = nullptr) noexcept - : m_ref(ref) - { - } - - CFPtr(CFPtr&& rg) noexcept - : m_ref(rg.m_ref) - { - rg.m_ref = nullptr; - } - - ~CFPtr() noexcept - { - if (m_ref) - CFRelease(m_ref); - } - - CFPtr& operator=(CFPtr&& rg) noexcept - { - REALM_ASSERT(!m_ref || m_ref != rg.m_ref); - if (m_ref) - CFRelease(m_ref); - m_ref = rg.m_ref; - rg.m_ref = nullptr; - return *this; - } - - explicit operator bool() const noexcept - { - return bool(m_ref); - } - - Ref get() const noexcept - { - return m_ref; - } - - Ref release() noexcept - { - Ref ref = m_ref; - m_ref = nullptr; - return ref; - } - - void reset(Ref ref = nullptr) noexcept - { - REALM_ASSERT(!m_ref || m_ref != ref); - if (m_ref) - CFRelease(m_ref); - m_ref = ref; - } - -private: - Ref m_ref; -}; - -template -CFPtr adoptCF(Ref ptr) -{ - return CFPtr(ptr); -} - -template -CFPtr retainCF(Ref ptr) -{ - CFRetain(ptr); - return CFPtr(ptr); -} -} -} - - -#endif // REALM_PLATFORM_APPLE - -#endif // REALM_UTIL_CF_PTR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/cf_str.hpp b/Lesson14/Pods/Realm/include/core/realm/util/cf_str.hpp deleted file mode 100644 index a1ae1ec..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/cf_str.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************* - * - * Copyright 2020 Realm Inc. - * - * 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 REALM_UTIL_CF_STR_HPP -#define REALM_UTIL_CF_STR_HPP - -#include - -#if REALM_PLATFORM_APPLE - -#include - -namespace realm { -namespace util { - -inline std::string cfstring_to_std_string(CFStringRef cf_str) -{ - std::string ret; - // If the CFString happens to store UTF-8 we can read its data directly - if (const char *utf8 = CFStringGetCStringPtr(cf_str, kCFStringEncodingUTF8)) { - ret = utf8; - return ret; - } - - // Otherwise we need to convert the CFString to UTF-8 - CFIndex length = CFStringGetLength(cf_str); - CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; - ret.resize(max_size); - CFStringGetCString(cf_str, &ret[0], max_size, kCFStringEncodingUTF8); - ret.resize(strlen(ret.c_str())); - return ret; -} - -} -} - -#endif // REALM_PLATFORM_APPLE - -#endif // REALM_UTIL_CF_STR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/circular_buffer.hpp b/Lesson14/Pods/Realm/include/core/realm/util/circular_buffer.hpp deleted file mode 100644 index 4ae07cc..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/circular_buffer.hpp +++ /dev/null @@ -1,1011 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_CIRCULAR_BUFFER_HPP -#define REALM_UTIL_CIRCULAR_BUFFER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace realm { -namespace util { - -/// \brief A container backed by a "circular buffer". -/// -/// This container is similar to std::deque in that it offers efficient element -/// insertion and removal at both ends. Insertion at either end occurs in -/// amortized constant time. Removal at either end occurs in constant time. -/// -/// As opposed to std::deque, this container allows for reservation of buffer -/// space, such that value insertion can be guaranteed to not reallocate buffer -/// memory, and to not throw. -/// -/// More specifically, a single insert operation, that inserts zero or more -/// values at either end, is guaranteed to not reallocate buffer memory if the -/// prior capacity (capacity()) is greater than, or equal to the prior size -/// (size()) plus the number of inserted values. Further more, such an operation -/// is guaranteed to not throw if the capacity is sufficient, and the relevant -/// constructor of the value type does not throw, and, in the case of inserting -/// a range of values specified as a pair of iterators, if no exception is -/// thrown while operating on those iterators. -/// -/// This container uses a single contiguous chunk of memory as backing storage, -/// but it allows for the logical sequence of values to wrap around from the -/// end, to the beginning of that chunk. Because the logical sequence of values -/// can have a storage-wise discontinuity of this kind, this container does not -/// meet the requirements of `ContiguousContainer` (as defined by C++17). -/// -/// When the first element is removed (pop_front()), iterators pointing to the -/// removed element will be invalidated. All other iterators, including "end -/// iterators" (end()), will remain valid. -/// -/// When the last element is removed (pop_back()), iterators pointing to the -/// removed element will become "end iterators" (end()), and "end iterators" -/// will be invalidated. All other iterators will remain valid. -/// -/// When an element is inserted at the front (push_front()), and the prior -/// capacity (capacity()) is strictly greater than the prior size (size()), all -/// iterators remain valid. -/// -/// When an element is inserted at the back (push_back()), and the prior -/// capacity (capacity()) is strictly greater than the prior size (size()), "end -/// iterators" (end()) become iterators to the inserted element, and all other -/// iterators remain valid. -/// -/// Operations pop_front(), pop_back(), and clear(), are guaranteed to leave the -/// capacity unchanged. -/// -/// Iterators are of the "random access" kind (std::random_access_iterator_tag). -template class CircularBuffer { -private: - template class Iter; - - template using RequireIter = - std::enable_if_t::iterator_category, - std::input_iterator_tag>::value>; - -public: - static_assert(std::is_nothrow_destructible::value, ""); - - using value_type = T; - using size_type = std::size_t; - using reference = value_type&; - using const_reference = const value_type&; - using iterator = Iter; - using const_iterator = Iter; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - CircularBuffer() noexcept; - CircularBuffer(const CircularBuffer&); - CircularBuffer(CircularBuffer&&) noexcept; - CircularBuffer(std::initializer_list); - explicit CircularBuffer(size_type size); - CircularBuffer(size_type size, const T& value); - template> CircularBuffer(I begin, I end); - ~CircularBuffer() noexcept; - - CircularBuffer& operator=(const CircularBuffer&); - CircularBuffer& operator=(CircularBuffer&&) noexcept; - CircularBuffer& operator=(std::initializer_list); - - void assign(std::initializer_list); - void assign(size_type size, const T& value); - template> void assign(I begin, I end); - - // Element access - - reference at(size_type); - const_reference at(size_type) const; - - reference operator[](size_type) noexcept; - const_reference operator[](size_type) const noexcept; - - reference front() noexcept; - const_reference front() const noexcept; - - reference back() noexcept; - const_reference back() const noexcept; - - // Iterators - - iterator begin() noexcept; - const_iterator begin() const noexcept; - const_iterator cbegin() const noexcept; - - iterator end() noexcept; - const_iterator end() const noexcept; - const_iterator cend() const noexcept; - - reverse_iterator rbegin() noexcept; - const_reverse_iterator rbegin() const noexcept; - const_reverse_iterator crbegin() const noexcept; - - reverse_iterator rend() noexcept; - const_reverse_iterator rend() const noexcept; - const_reverse_iterator crend() const noexcept; - - // Size / capacity - - bool empty() const noexcept; - size_type size() const noexcept; - size_type capacity() const noexcept; - - void reserve(size_type capacity); - void shrink_to_fit(); - - // Modifiers - - reference push_front(const T&); - reference push_back(const T&); - - reference push_front(T&&); - reference push_back(T&&); - - template reference emplace_front(Args&&...); - template reference emplace_back(Args&&...); - - void pop_front() noexcept; - void pop_back() noexcept; - - // FIXME: emplace(const_iterator i, ...) -> j = unwrap(i.m_index); if (j >= (m_size+1)/2) insert_near_back(j, ...); else insert_near_front(j, ...); - - void clear() noexcept; - void resize(size_type size); - void resize(size_type size, const T& value); - - void swap(CircularBuffer&) noexcept; - - // Comparison - - template bool operator==(const CircularBuffer&) const - noexcept(noexcept(std::declval() == std::declval())); - template bool operator!=(const CircularBuffer&) const - noexcept(noexcept(std::declval() == std::declval())); - template bool operator<(const CircularBuffer&) const - noexcept(noexcept(std::declval() < std::declval())); - template bool operator>(const CircularBuffer&) const - noexcept(noexcept(std::declval() < std::declval())); - template bool operator<=(const CircularBuffer&) const - noexcept(noexcept(std::declval() < std::declval())); - template bool operator>=(const CircularBuffer&) const - noexcept(noexcept(std::declval() < std::declval())); - -private: - using Strut = typename std::aligned_storage::type; - std::unique_ptr m_memory_owner; - - // Index of first element in allocated memory chunk. - size_type m_begin = 0; - - // The number of elements within the allocated memory chunk, that are - // currently in use, i.e., the logical size of the circular buffer. - size_type m_size = 0; - - // Number of elements of type T that will fit into the currently allocated - // memory chunk. - // - // Except when m_size is zero, m_allocated_size must be strictly greater - // than m_size. This is required to ensure that the iterators returned by - // begin() and end() are equal only when the buffer is empty. - // - // INVARIANT: m_size == 0 ? m_allocated_size == 0 : m_size < m_allocated_size - size_type m_allocated_size = 0; - - T* get_memory_ptr() noexcept; - - // Assumption: index < m_allocated_size - size_type circular_inc(size_type index) noexcept; - size_type circular_dec(size_type index) noexcept; - size_type wrap(size_type index) noexcept; - size_type unwrap(size_type index) noexcept; - - template void copy(I begin, I end); - template void copy(I begin, I end, std::input_iterator_tag); - template void copy(I begin, I end, std::forward_iterator_tag); - - void destroy(size_type offset = 0) noexcept; - - void realloc(size_type new_allocated_size); -}; - - -template void swap(CircularBuffer&, CircularBuffer&) noexcept; - - - - -// Implementation - -template template class CircularBuffer::Iter : - public std::iterator { -public: - using difference_type = std::ptrdiff_t; - - Iter() noexcept - { - } - - template Iter(const Iter& i) noexcept - { - operator=(i); - } - - template Iter& operator=(const Iter& i) noexcept - { - // Check constness convertability - static_assert(std::is_convertible::value, ""); - m_buffer = i.m_buffer; - m_index = i.m_index; - return *this; - } - - U& operator*() const noexcept - { - T* memory = m_buffer->get_memory_ptr(); - return memory[m_index]; - } - - U* operator->() const noexcept - { - return &operator*(); - } - - U& operator[](difference_type i) const noexcept - { - Iter j = *this; - j += i; - return *j; - } - - Iter& operator++() noexcept - { - m_index = m_buffer->circular_inc(m_index); - return *this; - } - - Iter& operator--() noexcept - { - m_index = m_buffer->circular_dec(m_index); - return *this; - } - - Iter operator++(int) noexcept - { - size_type i = m_index; - operator++(); - return Iter{m_buffer, i}; - } - - Iter operator--(int) noexcept - { - size_type i = m_index; - operator--(); - return Iter{m_buffer, i}; - } - - Iter& operator+=(difference_type value) noexcept - { - // Care is needed to avoid unspecified arithmetic behaviour here. We can - // assume, however, that if `i` is the unwrapped (logical) index of the - // element pointed to by this iterator, then the mathematical value of i - // + value is representable in `size_type` (otherwise the resulting - // iterator would escape the boundaries of the buffer). We can therefore - // safely perform the addition in the unsigned domain of unwrapped - // element indexes, and rely on two's complement representation for - // negative values. - size_type i = m_buffer->unwrap(m_index); - i += size_type(value); - m_index = m_buffer->wrap(i); - return *this; - } - - Iter& operator-=(difference_type value) noexcept - { - // Care is needed to avoid unspecified arithmetic behaviour here. See - // the comment in the implementation of operator+=(). - size_type i = m_buffer->unwrap(m_index); - i -= size_type(value); - m_index = m_buffer->wrap(i); - return *this; - } - - Iter operator+(difference_type value) const noexcept - { - Iter i = *this; - i += value; - return i; - } - - Iter operator-(difference_type value) const noexcept - { - Iter i = *this; - i -= value; - return i; - } - - friend Iter operator+(difference_type value, const Iter& i) noexcept - { - Iter j = i; - j += value; - return j; - } - - template difference_type operator-(const Iter& i) const noexcept - { - REALM_ASSERT(m_buffer == i.m_buffer); - size_type i_1 = m_buffer->unwrap(m_index); - size_type i_2 = i.m_buffer->unwrap(i.m_index); - return from_twos_compl(size_type(i_1 - i_2)); - } - - template bool operator==(const Iter& i) const noexcept - { - REALM_ASSERT(m_buffer == i.m_buffer); - return (m_index == i.m_index); - } - - template bool operator!=(const Iter& i) const noexcept - { - return !operator==(i); - } - - template bool operator<(const Iter& i) const noexcept - { - REALM_ASSERT(m_buffer == i.m_buffer); - size_type i_1 = m_buffer->unwrap(m_index); - size_type i_2 = i.m_buffer->unwrap(i.m_index); - return (i_1 < i_2); - } - - template bool operator>(const Iter& i) const noexcept - { - return (i < *this); - } - - template bool operator<=(const Iter& i) const noexcept - { - return !operator>(i); - } - - template bool operator>=(const Iter& i) const noexcept - { - return !operator<(i); - } - -private: - CircularBuffer* m_buffer = nullptr; - - // Index of iterator position from beginning of allocated memory, i.e., from - // beginning of m_buffer->get_memory_ptr(). - size_type m_index = 0; - - Iter(CircularBuffer* buffer, size_type index) noexcept : - m_buffer{buffer}, - m_index{index} - { - } - - friend class CircularBuffer; - template friend class Iter; -}; - -template inline CircularBuffer::CircularBuffer() noexcept -{ -} - -template inline CircularBuffer::CircularBuffer(const CircularBuffer& buffer) -{ - try { - copy(buffer.begin(), buffer.end()); // Throws - } - catch (...) { - // If an exception was thrown above, the destructor will not be called, - // so we need to manually destroy the copies that were already made. - destroy(); - throw; - } -} - -template inline CircularBuffer::CircularBuffer(CircularBuffer&& buffer) noexcept : - m_memory_owner{std::move(buffer.m_memory_owner)}, - m_begin{buffer.m_begin}, - m_size{buffer.m_size}, - m_allocated_size{buffer.m_allocated_size} -{ - buffer.m_begin = 0; - buffer.m_size = 0; - buffer.m_allocated_size = 0; -} - -template inline CircularBuffer::CircularBuffer(std::initializer_list list) -{ - try { - copy(list.begin(), list.end()); // Throws - } - catch (...) { - // If an exception was thrown above, the destructor will not be called, - // so we need to manually destroy the copies that were already made. - destroy(); - throw; - } -} - -template inline CircularBuffer::CircularBuffer(size_type count) -{ - try { - resize(count); // Throws - } - catch (...) { - // If an exception was thrown above, the destructor will not be called, - // so we need to manually destroy the instances that were already - // created. - destroy(); - throw; - } -} - -template inline CircularBuffer::CircularBuffer(size_type count, const T& value) -{ - try { - resize(count, value); // Throws - } - catch (...) { - // If an exception was thrown above, the destructor will not be called, - // so we need to manually destroy the copies that were already made. - destroy(); - throw; - } -} - -template template inline CircularBuffer::CircularBuffer(I begin, I end) -{ - try { - copy(begin, end); // Throws - } - catch (...) { - // If an exception was thrown above, the destructor will not be called, - // so we need to manually destroy the copies that were already made. - destroy(); - throw; - } -} - -template inline CircularBuffer::~CircularBuffer() noexcept -{ - destroy(); -} - -template -inline auto CircularBuffer::operator=(const CircularBuffer& buffer) -> CircularBuffer& -{ - clear(); - copy(buffer.begin(), buffer.end()); // Throws - return *this; -} - -template -inline auto CircularBuffer::operator=(CircularBuffer&& buffer) noexcept -> CircularBuffer& -{ - destroy(); - m_memory_owner = std::move(buffer.m_memory_owner); - m_begin = buffer.m_begin; - m_size = buffer.m_size; - m_allocated_size = buffer.m_allocated_size; - buffer.m_begin = 0; - buffer.m_size = 0; - buffer.m_allocated_size = 0; - return *this; -} - -template -inline auto CircularBuffer::operator=(std::initializer_list list) -> CircularBuffer& -{ - clear(); - copy(list.begin(), list.end()); // Throws - return *this; -} - -template inline void CircularBuffer::assign(std::initializer_list list) -{ - clear(); - copy(list.begin(), list.end()); // Throws -} - -template inline void CircularBuffer::assign(size_type count, const T& value) -{ - clear(); - resize(count, value); // Throws -} - -template template inline void CircularBuffer::assign(I begin, I end) -{ - clear(); - copy(begin, end); // Throws -} - -template inline auto CircularBuffer::at(size_type i) -> reference -{ - if (REALM_LIKELY(i < m_size)) - return operator[](i); - throw util::out_of_range{"Index"}; -} - -template inline auto CircularBuffer::at(size_type i) const -> const_reference -{ - return const_cast(this)->at(i); // Throws -} - -template -inline auto CircularBuffer::operator[](size_type i) noexcept -> reference -{ - REALM_ASSERT(i < m_size); - T* memory = get_memory_ptr(); - size_type j = wrap(i); - return memory[j]; -} - -template -inline auto CircularBuffer::operator[](size_type i) const noexcept -> const_reference -{ - return const_cast(this)->operator[](i); -} - -template inline auto CircularBuffer::front() noexcept -> reference -{ - return operator[](0); -} - -template inline auto CircularBuffer::front() const noexcept -> const_reference -{ - return operator[](0); -} - -template inline auto CircularBuffer::back() noexcept -> reference -{ - return operator[](m_size-1); -} - -template -inline auto CircularBuffer::back() const noexcept -> const_reference -{ - return operator[](m_size-1); -} - -template inline auto CircularBuffer::begin() noexcept -> iterator -{ - return iterator{this, m_begin}; -} - -template inline auto CircularBuffer::begin() const noexcept -> const_iterator -{ - return const_cast(this)->begin(); -} - -template inline auto CircularBuffer::cbegin() const noexcept -> const_iterator -{ - return begin(); -} - -template inline auto CircularBuffer::end() noexcept -> iterator -{ - size_type i = wrap(m_size); - return iterator{this, i}; -} - -template inline auto CircularBuffer::end() const noexcept -> const_iterator -{ - return const_cast(this)->end(); -} - -template inline auto CircularBuffer::cend() const noexcept -> const_iterator -{ - return end(); -} - -template inline auto CircularBuffer::rbegin() noexcept -> reverse_iterator -{ - return std::reverse_iterator(end()); -} - -template inline auto CircularBuffer::rbegin() const noexcept -> const_reverse_iterator -{ - return const_cast(this)->rbegin(); -} - -template inline auto CircularBuffer::crbegin() const noexcept -> const_reverse_iterator -{ - return rbegin(); -} - -template inline auto CircularBuffer::rend() noexcept -> reverse_iterator -{ - return std::reverse_iterator(begin()); -} - -template inline auto CircularBuffer::rend() const noexcept -> const_reverse_iterator -{ - return const_cast(this)->rend(); -} - -template inline auto CircularBuffer::crend() const noexcept -> const_reverse_iterator -{ - return rend(); -} - -template inline bool CircularBuffer::empty() const noexcept -{ - return (m_size == 0); -} - -template inline auto CircularBuffer::size() const noexcept -> size_type -{ - return m_size; -} - -template void CircularBuffer::reserve(size_type capacity) -{ - if (capacity == 0) - return; - - // An extra element of capacity is needed such that the end iterator can - // always point one beyond the last element without becomeing equal to an - // iterator to the first element. - size_type min_allocated_size = capacity; - if (REALM_UNLIKELY(int_add_with_overflow_detect(min_allocated_size, 1))) - throw util::overflow_error{"Capacity"}; - - if (min_allocated_size <= m_allocated_size) - return; - - size_type new_allocated_size = m_allocated_size; - if (REALM_UNLIKELY(int_multiply_with_overflow_detect(new_allocated_size, 2))) - new_allocated_size = std::numeric_limits::max(); - if (new_allocated_size < min_allocated_size) - new_allocated_size = min_allocated_size; - realloc(new_allocated_size); // Throws -} - -template inline void CircularBuffer::shrink_to_fit() -{ - if (m_size > 0) { - // An extra element of capacity is needed such that the end iterator can - // always point one beyond the last element without becomeing equal to - // an iterator to the first element. - size_type new_allocated_size = m_size + 1; - if (new_allocated_size < m_allocated_size) - realloc(new_allocated_size); // Throws - } - else { - m_memory_owner.reset(); - m_begin = 0; - m_allocated_size = 0; - } -} - -template inline auto CircularBuffer::capacity() const noexcept -> size_type -{ - return (m_allocated_size > 0 ? m_allocated_size - 1 : 0); -} - -template inline auto CircularBuffer::push_front(const T& value) -> reference -{ - return emplace_front(value); // Throws -} - -template inline auto CircularBuffer::push_back(const T& value) -> reference -{ - return emplace_back(value); // Throws -} - -template inline auto CircularBuffer::push_front(T&& value) -> reference -{ - return emplace_front(value); // Throws -} - -template inline auto CircularBuffer::push_back(T&& value) -> reference -{ - return emplace_back(value); // Throws -} - -template -template inline auto CircularBuffer::emplace_front(Args&&... args) -> reference -{ - size_type new_size = m_size + 1; - reserve(new_size); // Throws - REALM_ASSERT(m_allocated_size > 0); - T* memory = get_memory_ptr(); - size_type i = circular_dec(m_begin); - new (&memory[i]) T(std::forward(args)...); // Throws - m_begin = i; - m_size = new_size; - return memory[i]; -} - -template -template inline auto CircularBuffer::emplace_back(Args&&... args) -> reference -{ - size_type new_size = m_size + 1; - reserve(new_size); // Throws - REALM_ASSERT(m_allocated_size > 0); - T* memory = get_memory_ptr(); - size_type i = wrap(m_size); - new (&memory[i]) T(std::forward(args)...); // Throws - m_size = new_size; - return memory[i]; -} - -template inline void CircularBuffer::pop_front() noexcept -{ - REALM_ASSERT(m_size > 0); - T* memory = get_memory_ptr(); - memory[m_begin].~T(); - m_begin = circular_inc(m_begin); - --m_size; -} - -template inline void CircularBuffer::pop_back() noexcept -{ - REALM_ASSERT(m_size > 0); - T* memory = get_memory_ptr(); - size_type new_size = m_size - 1; - size_type i = wrap(new_size); - memory[i].~T(); - m_size = new_size; -} - -template inline void CircularBuffer::clear() noexcept -{ - destroy(); - m_begin = 0; - m_size = 0; -} - -template inline void CircularBuffer::resize(size_type size) -{ - if (size <= m_size) { - size_type offset = size; - destroy(offset); - m_size = size; - return; - } - reserve(size); // Throws - T* memory = get_memory_ptr(); - size_type i = wrap(m_size); - do { - new (&memory[i]) T(); // Throws - i = circular_inc(i); - ++m_size; - } - while (m_size < size); -} - -template inline void CircularBuffer::resize(size_type size, const T& value) -{ - if (size <= m_size) { - size_type offset = size; - destroy(offset); - m_size = size; - return; - } - reserve(size); // Throws - T* memory = get_memory_ptr(); - size_type i = wrap(m_size); - do { - new (&memory[i]) T(value); // Throws - i = circular_inc(i); - ++m_size; - } - while (m_size < size); -} - -template inline void CircularBuffer::swap(CircularBuffer& buffer) noexcept -{ - std::swap(m_memory_owner, buffer.m_memory_owner); - std::swap(m_begin, buffer.m_begin); - std::swap(m_size, buffer.m_size); - std::swap(m_allocated_size, buffer.m_allocated_size); -} - -template template -inline bool CircularBuffer::operator==(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() == std::declval())) -{ - return std::equal(begin(), end(), buffer.begin(), buffer.end()); // Throws -} - -template template -inline bool CircularBuffer::operator!=(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() == std::declval())) -{ - return !operator==(buffer); // Throws -} - -template template -inline bool CircularBuffer::operator<(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() < std::declval())) -{ - return std::lexicographical_compare(begin(), end(), buffer.begin(), buffer.end()); // Throws -} - -template template -inline bool CircularBuffer::operator>(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() < std::declval())) -{ - return (buffer < *this); // Throws -} - -template template -inline bool CircularBuffer::operator<=(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() < std::declval())) -{ - return !operator>(buffer); // Throws -} - -template template -inline bool CircularBuffer::operator>=(const CircularBuffer& buffer) const - noexcept(noexcept(std::declval() < std::declval())) -{ - return !operator<(buffer); // Throws -} - -template inline T* CircularBuffer::get_memory_ptr() noexcept -{ - return static_cast(static_cast(m_memory_owner.get())); -} - -template -inline auto CircularBuffer::circular_inc(size_type index) noexcept -> size_type -{ - size_type index_2 = index + 1; - if (REALM_LIKELY(index_2 < m_allocated_size)) - return index_2; - return 0; -} - -template -inline auto CircularBuffer::circular_dec(size_type index) noexcept -> size_type -{ - if (REALM_LIKELY(index > 0)) - return index - 1; - return m_allocated_size - 1; -} - -template -inline auto CircularBuffer::wrap(size_type index) noexcept -> size_type -{ - size_type top = m_allocated_size - m_begin; - if (index < top) - return m_begin + index; - return index - top; -} - -template -inline auto CircularBuffer::unwrap(size_type index) noexcept -> size_type -{ - if (index >= m_begin) - return index - m_begin; - return m_allocated_size - (m_begin - index); -} - -template template inline void CircularBuffer::copy(I begin, I end) -{ - using iterator_category = typename std::iterator_traits::iterator_category; - copy(begin, end, iterator_category{}); // Throws -} - -template template -inline void CircularBuffer::copy(I begin, I end, std::input_iterator_tag) -{ - for (I j = begin; j != end; ++j) - push_back(*j); // Throws -} - -template template -inline void CircularBuffer::copy(I begin, I end, std::forward_iterator_tag) -{ - REALM_ASSERT(m_begin == 0); - REALM_ASSERT(m_size == 0); - size_type size = std::distance(begin, end); - reserve(size); // Throws - T* memory = get_memory_ptr(); - for (I i = begin; i != end; ++i) { - new (&memory[m_size]) T(*i); // Throws - ++m_size; - } -} - -template inline void CircularBuffer::destroy(size_type offset) noexcept -{ - T* memory = get_memory_ptr(); - size_type j = m_begin; - for (size_type i = offset; i < m_size; ++i) { - memory[j].~T(); - j = circular_inc(j); - } -} - -template void CircularBuffer::realloc(size_type new_allocated_size) -{ - REALM_ASSERT(new_allocated_size > 1); - REALM_ASSERT(new_allocated_size > m_size); - - // Allocate new buffer - std::unique_ptr new_memory_owner = - std::make_unique(new_allocated_size); // Throws - T* memory = get_memory_ptr(); - - // Move or copy elements to new buffer - { - T* new_memory = static_cast(static_cast(new_memory_owner.get())); - size_type i = 0; - try { - size_type j = m_begin; - while (i < m_size) { - new (&new_memory[i]) T(std::move_if_noexcept(memory[j])); // Throws - ++i; - j = circular_inc(j); - } - } - catch (...) { - // If an exception was thrown above, we know that elements were - // copied, and not moved (assuming that T is copy constructable if - // it is not nothrow move constructible), so we need to back out by - // destroying the copies that were already made. - for (size_type j = 0; j < i; ++j) - new_memory[j].~T(); - throw; - } - } - - // Destroy old elements - { - size_type j = m_begin; - for (size_type i = 0; i < m_size; ++i) { - memory[j].~T(); - j = circular_inc(j); - } - } - - m_memory_owner = std::move(new_memory_owner); - m_begin = 0; - m_allocated_size = new_allocated_size; -} - -template inline void swap(CircularBuffer& a, CircularBuffer& b) noexcept -{ - a.swap(b); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_CIRCULAR_BUFFER_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/config.h b/Lesson14/Pods/Realm/include/core/realm/util/config.h deleted file mode 100644 index 0ebbbe2..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/config.h +++ /dev/null @@ -1,23 +0,0 @@ -// Version information -#define REALM_VERSION "" - -// Specific headers -#define HAVE_MALLOC_H 0 - -// Realm-specific configuration -#define REALM_MAX_BPNODE_SIZE 1000 -#define REALM_ENABLE_ASSERTIONS 1 -#define REALM_ENABLE_ALLOC_SET_ZERO 0 -#define REALM_ENABLE_ENCRYPTION 1 -#define REALM_ENABLE_MEMDEBUG 0 -#define REALM_VALGRIND 0 -#define REALM_METRICS 1 -#define REALM_ASAN 0 -#define REALM_TSAN 0 - -#define REALM_INSTALL_PREFIX "/usr/local" -#define REALM_INSTALL_INCLUDEDIR "include" -#define REALM_INSTALL_BINDIR "bin" -#define REALM_INSTALL_LIBDIR "lib" -#define REALM_INSTALL_LIBEXECDIR "libexec" -#define REALM_INSTALL_EXEC_PREFIX "/usr/local" diff --git a/Lesson14/Pods/Realm/include/core/realm/util/demangle.hpp b/Lesson14/Pods/Realm/include/core/realm/util/demangle.hpp deleted file mode 100644 index 7af4fb8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/demangle.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_DEMANGLE_HPP -#define REALM_UTIL_DEMANGLE_HPP - -#include -#include - -namespace realm { -namespace util { - - -/// Demangle the specified C++ ABI identifier. -/// -/// See for example -/// http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaceabi.html -std::string demangle(const std::string&); - - -/// Get the demangled name of the specified type. -template inline std::string get_type_name() -{ - return demangle(typeid(T).name()); -} - - -/// Get the demangled name of the type of the specified argument. -template inline std::string get_type_name(const T& v) -{ - return demangle(typeid(v).name()); -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_DEMANGLE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/duplicating_logger.hpp b/Lesson14/Pods/Realm/include/core/realm/util/duplicating_logger.hpp deleted file mode 100644 index 774df3c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/duplicating_logger.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_DUPLICATING_LOGGER_HPP -#define REALM_UTIL_DUPLICATING_LOGGER_HPP - -#include - - -namespace realm { -namespace util { - -/// The log level threshold of a logger of this type will be decided by the -/// associated base logger. Therefore, the log level threshold specified via the -/// auxiliary logger will be ignored. -/// -/// Loggers of this type are thread-safe if the base logger and the auxiliary -/// loggers are both thread-safe. -class DuplicatingLogger : public Logger { -public: - explicit DuplicatingLogger(Logger& base_logger, Logger& aux_logger) noexcept; - -protected: - void do_log(Logger::Level, std::string message) override; - -private: - Logger& m_base_logger; - Logger& m_aux_logger; -}; - - - - -// Implementation - -inline DuplicatingLogger::DuplicatingLogger(Logger& base_logger, Logger& aux_logger) noexcept : - Logger{base_logger.level_threshold}, - m_base_logger{base_logger}, m_aux_logger{aux_logger} -{ -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_DUPLICATING_LOGGER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp b/Lesson14/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp deleted file mode 100644 index 6f5fd3c..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/encrypted_file_mapping.hpp +++ /dev/null @@ -1,181 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP -#define REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP - -#include -#include -#include - -#if REALM_ENABLE_ENCRYPTION - -typedef size_t (*Header_to_size)(const char* addr); - -#include - -namespace realm { -namespace util { - -struct SharedFileInfo; -class EncryptedFileMapping; - -class EncryptedFileMapping { -public: - // Adds the newly-created object to file.mappings iff it's successfully constructed - EncryptedFileMapping(SharedFileInfo& file, size_t file_offset, void* addr, size_t size, File::AccessMode access); - ~EncryptedFileMapping(); - - // Default implementations of copy/assign can trigger multiple destructions - EncryptedFileMapping(const EncryptedFileMapping&) = delete; - EncryptedFileMapping& operator=(const EncryptedFileMapping&) = delete; - - // Write all dirty pages to disk and mark them read-only - // Does not call fsync - void flush() noexcept; - - // Sync this file to disk - void sync() noexcept; - - // Make sure that memory in the specified range is synchronized with any - // changes made globally visible through call to write_barrier - void read_barrier(const void* addr, size_t size, Header_to_size header_to_size); - - // Ensures that any changes made to memory in the specified range - // becomes visible to any later calls to read_barrier() - void write_barrier(const void* addr, size_t size) noexcept; - - // Set this mapping to a new address and size - // Flushes any remaining dirty pages from the old mapping - void set(void* new_addr, size_t new_size, size_t new_file_offset); - - size_t collect_decryption_count() - { - return m_num_decrypted; - } - // reclaim any untouched pages - this is thread safe with respect to - // concurrent access/touching of pages - but must be called with the mutex locked. - void reclaim_untouched(size_t& progress_ptr, size_t& accumulated_savings) noexcept; - - bool contains_page(size_t page_in_file) const; - size_t get_local_index_of_address(const void* addr, size_t offset = 0) const; - - size_t get_end_index() - { - return m_first_page + m_page_state.size(); - } - size_t get_start_index() - { - return m_first_page; - } - -private: - SharedFileInfo& m_file; - - size_t m_page_shift; - size_t m_blocks_per_page; - - void* m_addr = nullptr; - - size_t m_first_page; - size_t m_num_decrypted; // 1 for every page decrypted - - enum PageState { - Touched = 1, // a ref->ptr translation has taken place - UpToDate = 2, // the page is fully up to date - PartiallyUpToDate = 4, // the page is valid for old translations, but requires re-decryption for new - Dirty = 8 // the page has been modified with respect to what's on file. - }; - std::vector m_page_state; - // little helpers: - inline void clear(PageState& ps, int p) - { - ps = PageState(ps & ~p); - } - inline bool is_not(PageState& ps, int p) - { - return (ps & p) == 0; - } - inline bool is(PageState& ps, int p) - { - return (ps & p) != 0; - } - inline void set(PageState& ps, int p) - { - ps = PageState(ps | p); - } - // 1K pages form a chunk - this array allows us to skip entire chunks during scanning - std::vector m_chunk_dont_scan; - static constexpr int page_to_chunk_shift = 10; - static constexpr size_t page_to_chunk_factor = size_t(1) << page_to_chunk_shift; - - File::AccessMode m_access; - -#ifdef REALM_DEBUG - std::unique_ptr m_validate_buffer; -#endif - - char* page_addr(size_t local_page_ndx) const noexcept; - - void mark_outdated(size_t local_page_ndx) noexcept; - bool copy_up_to_date_page(size_t local_page_ndx) noexcept; - void refresh_page(size_t local_page_ndx); - void write_page(size_t local_page_ndx) noexcept; - void write_and_update_all(size_t local_page_ndx, size_t begin_offset, size_t end_offset) noexcept; - void reclaim_page(size_t page_ndx); - void validate_page(size_t local_page_ndx) noexcept; - void validate() noexcept; -}; - -inline size_t EncryptedFileMapping::get_local_index_of_address(const void* addr, size_t offset) const -{ - REALM_ASSERT_EX(addr >= m_addr, addr, m_addr); - - size_t local_ndx = ((reinterpret_cast(addr) - reinterpret_cast(m_addr) + offset) >> m_page_shift); - REALM_ASSERT_EX(local_ndx < m_page_state.size(), local_ndx, m_page_state.size()); - return local_ndx; -} - -inline bool EncryptedFileMapping::contains_page(size_t page_in_file) const -{ - // first check for (page_in_file >= m_first_page) so that the following - // subtraction using unsigned types never wraps under 0 - return page_in_file >= m_first_page && page_in_file - m_first_page < m_page_state.size(); -} - - -} -} - -#endif // REALM_ENABLE_ENCRYPTION - -namespace realm { -namespace util { - -/// Thrown by EncryptedFileMapping if a file opened is non-empty and does not -/// contain valid encrypted data -struct DecryptionFailed : util::File::AccessError { - DecryptionFailed() - : util::File::AccessError("Decryption failed", std::string()) - { - } -}; -} -} - -#endif // REALM_UTIL_ENCRYPTED_FILE_MAPPING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/enum.hpp b/Lesson14/Pods/Realm/include/core/realm/util/enum.hpp deleted file mode 100644 index c11d166..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/enum.hpp +++ /dev/null @@ -1,224 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_ENUM_HPP -#define REALM_UTIL_ENUM_HPP - -#include -#include -#include -#include - - -namespace realm { -namespace util { - -/// This template class allows you to endow a fundamental `enum` type with -/// information about how to print out the individual values, and how to parse -/// them. -/// -/// Here is an example: -/// -/// // Declaration -/// -/// enum class Color { orange, purple, brown }; -/// -/// struct ColorSpec { static EnumAssoc map[]; }; -/// using ColorEnum = Enum; -/// -/// // Implementation -/// -/// EnumAssoc ColorSpec::map[] = { -/// { int(Color::orange), "orange" }, -/// { int(Color::purple), "purple" }, -/// { int(Color::brown), "brown" }, -/// { 0, 0 } -/// }; -/// -/// // Application -/// -/// ColorEnum color = Color::purple; -/// -/// std::cout << color; // Write a color -/// std::cin >> color; // Read a color -/// -/// The current implementation is restricted to enumeration types whose values -/// can all be represented in a regular integer. -template class Enum { -public: - using base_enum_type = E; - - Enum(E = {}) noexcept; - - operator E() const noexcept; - - const std::string& str() const; - - bool str(const std::string*&) const noexcept; - - /// \return True if, and only if successful. - static bool parse(const std::string& string, E& value); - -private: - E m_value = E{}; -}; - -template -std::basic_ostream& operator<<(std::basic_ostream&, - const Enum&); - -template -std::basic_istream& operator>>(std::basic_istream&, - Enum&); - - -struct EnumAssoc { - const int value; - const char* const name; -}; - - - - -// Implementation - -} // namespace util - -namespace _impl { - -class EnumMapper { -public: - EnumMapper(const util::EnumAssoc*, bool ignore_case); - - bool parse(const std::string& string, int& value, bool ignore_case) const; - - std::map value_to_name; - std::map name_to_value; -}; - -template const EnumMapper& get_enum_mapper() -{ - static EnumMapper mapper{S::map, ignore_case}; // Throws - return mapper; -} - -} // namespace _impl - -namespace util { - -template -inline Enum::Enum(E value) noexcept : - m_value{value} -{ -} - -template -inline Enum::operator E() const noexcept -{ - return m_value; -} - -template -inline const std::string& Enum::str() const -{ - return _impl::get_enum_mapper().val_to_name.at(m_value); // Throws -} - -template -inline bool Enum::str(const std::string*& string) const noexcept -{ - const auto& value_to_name = _impl::get_enum_mapper().value_to_name; - auto i = value_to_name.find(int(m_value)); - if (i == value_to_name.end()) - return false; - string = &i->second; - return true; -} - -template -inline bool Enum::parse(const std::string& string, E& value) -{ - int value_2; - if (!_impl::get_enum_mapper().parse(string, value_2, ignore_case)) // Throws - return false; - value = E(value_2); - return true; -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, - const Enum& e) -{ - const std::string* string; - if (e.str(string)) { - out << *string; - } - else { - out << int(E(e)); - } - return out; -} - -template -std::basic_istream& operator>>(std::basic_istream& in, - Enum& e) -{ - if (in.bad() || in.fail()) - return in; - std::string string; - const std::ctype& ctype = std::use_facet>(in.getloc()); - C underscore(ctype.widen('_')); - for (;;) { - C ch; - // Allow white-spaces to be skipped when stream is configured - // that way - if (string.empty()) { - in >> ch; - } - else { - in.get(ch); - } - if (!in) { - if (in.bad()) - return in; - in.clear(in.rdstate() & ~std::ios_base::failbit); - break; - } - if (!ctype.is(std::ctype_base::alnum, ch) && ch != underscore) { - in.unget(); - break; - } - char ch_2 = ctype.narrow(ch, '\0'); - string += ch_2; - } - E value = E{}; - if (!Enum::parse(string, value)) { // Throws - in.setstate(std::ios_base::badbit); - } - else { - e = value; - } - return in; -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_ENUM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/errno.hpp b/Lesson14/Pods/Realm/include/core/realm/util/errno.hpp deleted file mode 100644 index 4907f36..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/errno.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_ERRNO_HPP -#define REALM_UTIL_ERRNO_HPP - -#include - -#include - - -namespace realm { -namespace util { - -// Get the error message for a given error code, and append it to `prefix` -inline std::string get_errno_msg(const char* prefix, int err) -{ - return prefix + make_basic_system_error_code(err).message(); -} - -} // namespace util -} // namespace realm - -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/util/features.h b/Lesson14/Pods/Realm/include/core/realm/util/features.h deleted file mode 100644 index ed6d55a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/features.h +++ /dev/null @@ -1,344 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_FEATURES_H -#define REALM_UTIL_FEATURES_H - -#ifdef _MSC_VER -#pragma warning(disable : 4800) // Visual Studio int->bool performance warnings -#endif - -#if defined(_WIN32) && !defined(NOMINMAX) -#define NOMINMAX -#endif - -#ifndef REALM_NO_CONFIG -#include -#endif - -/* The maximum number of elements in a B+-tree node. Applies to inner nodes and - * to leaves. The minimum allowable value is 2. - */ -#ifndef REALM_MAX_BPNODE_SIZE -#define REALM_MAX_BPNODE_SIZE 1000 -#endif - - -#define REALM_QUOTE_2(x) #x -#define REALM_QUOTE(x) REALM_QUOTE_2(x) - -/* See these links for information about feature check macroes in GCC, - * Clang, and MSVC: - * - * http://gcc.gnu.org/projects/cxx0x.html - * http://clang.llvm.org/cxx_status.html - * http://clang.llvm.org/docs/LanguageExtensions.html#checks-for-standard-language-features - * http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx - * http://sourceforge.net/p/predef/wiki/Compilers - */ - - -/* Compiler is GCC and version is greater than or equal to the specified version */ -#define REALM_HAVE_AT_LEAST_GCC(maj, min) \ - (__GNUC__ > (maj) || __GNUC__ == (maj) && __GNUC_MINOR__ >= (min)) - -#if defined(__clang__) -#define REALM_HAVE_CLANG_FEATURE(feature) __has_feature(feature) -#define REALM_HAVE_CLANG_WARNING(warning) __has_warning(warning) -#else -#define REALM_HAVE_CLANG_FEATURE(feature) 0 -#define REALM_HAVE_CLANG_WARNING(warning) 0 -#endif - -#ifdef __has_cpp_attribute -#define REALM_HAS_CPP_ATTRIBUTE(attr) __has_cpp_attribute(attr) -#else -#define REALM_HAS_CPP_ATTRIBUTE(attr) 0 -#endif - -#if REALM_HAS_CPP_ATTRIBUTE(clang::fallthrough) -#define REALM_FALLTHROUGH [[clang::fallthrough]] -#elif REALM_HAS_CPP_ATTRIBUTE(gnu::fallthrough) -#define REALM_FALLTHROUGH [[gnu::fallthrough]] -#elif REALM_HAS_CPP_ATTRIBUTE(fallthrough) -#define REALM_FALLTHROUGH [[fallthrough]] -#else -#define REALM_FALLTHROUGH -#endif - -// This should be renamed to REALM_UNREACHABLE as soon as REALM_UNREACHABLE is renamed to -// REALM_ASSERT_NOT_REACHED which will better reflect its nature -#if defined(__GNUC__) || defined(__clang__) -#define REALM_COMPILER_HINT_UNREACHABLE __builtin_unreachable -#else -#define REALM_COMPILER_HINT_UNREACHABLE abort -#endif - -#if defined(__GNUC__) // clang or GCC -#define REALM_PRAGMA(v) _Pragma(REALM_QUOTE_2(v)) -#elif defined(_MSC_VER) // VS -#define REALM_PRAGMA(v) __pragma(v) -#else -#define REALM_PRAGMA(v) -#endif - -#if defined(__clang__) -#define REALM_DIAG(v) REALM_PRAGMA(clang diagnostic v) -#elif defined(__GNUC__) -#define REALM_DIAG(v) REALM_PRAGMA(GCC diagnostic v) -#else -#define REALM_DIAG(v) -#endif - -#define REALM_DIAG_PUSH() REALM_DIAG(push) -#define REALM_DIAG_POP() REALM_DIAG(pop) - -#ifdef _MSC_VER -#define REALM_VS_WARNING_DISABLE #pragma warning (default: 4297) -#endif - -#if REALM_HAVE_CLANG_WARNING("-Wtautological-compare") || REALM_HAVE_AT_LEAST_GCC(6, 0) -#define REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE() REALM_DIAG(ignored "-Wtautological-compare") -#else -#define REALM_DIAG_IGNORE_TAUTOLOGICAL_COMPARE() -#endif - -#ifdef _MSC_VER -# define REALM_DIAG_IGNORE_UNSIGNED_MINUS() REALM_PRAGMA(warning(disable:4146)) -#else -#define REALM_DIAG_IGNORE_UNSIGNED_MINUS() -#endif - -/* Compiler is MSVC (Microsoft Visual C++) */ -#if defined(_MSC_VER) && _MSC_VER >= 1600 -#define REALM_HAVE_AT_LEAST_MSVC_10_2010 1 -#endif -#if defined(_MSC_VER) && _MSC_VER >= 1700 -#define REALM_HAVE_AT_LEAST_MSVC_11_2012 1 -#endif -#if defined(_MSC_VER) && _MSC_VER >= 1800 -#define REALM_HAVE_AT_LEAST_MSVC_12_2013 1 -#endif - - -/* The way to specify that a function never returns. */ -#if REALM_HAVE_AT_LEAST_GCC(4, 8) || REALM_HAVE_CLANG_FEATURE(cxx_attributes) -#define REALM_NORETURN [[noreturn]] -#elif __GNUC__ -#define REALM_NORETURN __attribute__((noreturn)) -#elif defined(_MSC_VER) -#define REALM_NORETURN __declspec(noreturn) -#else -#define REALM_NORETURN -#endif - - -/* The way to specify that a variable or type is intended to possibly - * not be used. Use it to suppress a warning from the compiler. */ -#if __GNUC__ -#define REALM_UNUSED __attribute__((unused)) -#else -#define REALM_UNUSED -#endif - -/* The way to specify that a function is deprecated - * not be used. Use it to suppress a warning from the compiler. */ -#if __GNUC__ -#define REALM_DEPRECATED(x) [[deprecated(x)]] -#else -#define REALM_DEPRECATED(x) __declspec(deprecated(x)) -#endif - - -#if __GNUC__ || defined __INTEL_COMPILER -#define REALM_UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#define REALM_LIKELY(expr) __builtin_expect(!!(expr), 1) -#else -#define REALM_UNLIKELY(expr) (expr) -#define REALM_LIKELY(expr) (expr) -#endif - - -#if defined(__GNUC__) || defined(__HP_aCC) -#define REALM_FORCEINLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) -#define REALM_FORCEINLINE __forceinline -#else -#define REALM_FORCEINLINE inline -#endif - - -#if defined(__GNUC__) || defined(__HP_aCC) -#define REALM_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) -#define REALM_NOINLINE __declspec(noinline) -#else -#define REALM_NOINLINE -#endif - - -// FIXME: Change this to use [[nodiscard]] in C++17. -#if defined(__GNUC__) || defined(__HP_aCC) -#define REALM_NODISCARD __attribute__((warn_unused_result)) -#elif defined(_MSC_VER) -#define REALM_NODISCARD _Check_return_ -#else -#define REALM_NODISCARD -#endif - - -/* Thread specific data (only for POD types) */ -#if defined __clang__ -#define REALM_THREAD_LOCAL __thread -#else -#define REALM_THREAD_LOCAL thread_local -#endif - - -#if defined ANDROID -#define REALM_ANDROID 1 -#else -#define REALM_ANDROID 0 -#endif - -#if defined _WIN32 -# include -# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM) -# define REALM_WINDOWS 1 -# define REALM_UWP 0 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) -# define REALM_WINDOWS 0 -# define REALM_UWP 1 -# endif -#else -#define REALM_WINDOWS 0 -#define REALM_UWP 0 -#endif - -// Some documentation of the defines provided by Apple: -// http://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-SW13 -#if defined __APPLE__ && defined __MACH__ -#define REALM_PLATFORM_APPLE 1 -/* Apple OSX and iOS (Darwin). */ -#include -#include -#if TARGET_OS_IPHONE == 1 -/* Device (iPhone or iPad) or simulator. */ -#define REALM_IOS 1 -#else -#define REALM_IOS 0 -#endif -#if TARGET_OS_WATCH == 1 -/* Device (Apple Watch) or simulator. */ -#define REALM_WATCHOS 1 -#else -#define REALM_WATCHOS 0 -#endif -#if TARGET_OS_TV -/* Device (Apple TV) or simulator. */ -#define REALM_TVOS 1 -#else -#define REALM_TVOS 0 -#endif -#else -#define REALM_PLATFORM_APPLE 0 -#define REALM_IOS 0 -#define REALM_WATCHOS 0 -#define REALM_TVOS 0 -#endif - -// asl_log is deprecated in favor of os_log as of the following versions: -// macos(10.12), ios(10.0), watchos(3.0), tvos(10.0) -// versions are defined in /usr/include/Availability.h -// __MAC_10_12 101200 -// __IPHONE_10_0 100000 -// __WATCHOS_3_0 30000 -// __TVOS_10_0 100000 -#if REALM_PLATFORM_APPLE \ - && ( \ - (REALM_IOS && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) \ - && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) \ - || (REALM_TVOS && defined(__TV_OS_VERSION_MIN_REQUIRED) \ - && __TV_OS_VERSION_MIN_REQUIRED >= 100000) \ - || (REALM_WATCHOS && defined(__WATCH_OS_VERSION_MIN_REQUIRED) \ - && __WATCH_OS_VERSION_MIN_REQUIRED >= 30000) \ - || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \ - && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) \ - ) -#define REALM_APPLE_OS_LOG 1 -#else -#define REALM_APPLE_OS_LOG 0 -#endif - -#if REALM_ANDROID || REALM_IOS || REALM_WATCHOS || REALM_TVOS || REALM_UWP -#define REALM_MOBILE 1 -#else -#define REALM_MOBILE 0 -#endif - - -#if defined(REALM_DEBUG) && !defined(REALM_COOKIE_CHECK) -#define REALM_COOKIE_CHECK -#endif - -#if !REALM_IOS && !REALM_WATCHOS && !REALM_TVOS && !defined(_WIN32) && !REALM_ANDROID -#define REALM_ASYNC_DAEMON -#endif - -// We're in i686 mode -#if defined(__i386) || defined(__i386__) || defined(__i686__) || defined(_M_I86) || defined(_M_IX86) -#define REALM_ARCHITECTURE_X86_32 1 -#else -#define REALM_ARCHITECTURE_X86_32 0 -#endif - -// We're in amd64 mode -#if defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ - defined(_M_AMD64) -#define REALM_ARCHITECTURE_X86_64 1 -#else -#define REALM_ARCHITECTURE_X86_64 0 -#endif - -// Address Sanitizer -#if defined(__has_feature) // Clang -# if __has_feature(address_sanitizer) -# define REALM_SANITIZE_ADDRESS 1 -# else -# define REALM_SANITIZE_ADDRESS 0 -# endif -#elif defined(__SANITIZE_ADDRESS__) && __SANITIZE_ADDRESS__ // GCC -# define REALM_SANITIZE_ADDRESS 1 -#else -# define REALM_SANITIZE_ADDRESS 0 -#endif - -// Thread Sanitizer -#if defined(__has_feature) // Clang -# if __has_feature(thread_sanitizer) -# define REALM_SANITIZE_THREAD 1 -# else -# define REALM_SANITIZE_THREAD 0 -# endif -#elif defined(__SANITIZE_THREAD__) && __SANITIZE_THREAD__ // GCC -# define REALM_SANITIZE_THREAD 1 -#else -# define REALM_SANITIZE_THREAD 0 -#endif - -#endif /* REALM_UTIL_FEATURES_H */ diff --git a/Lesson14/Pods/Realm/include/core/realm/util/fifo_helper.hpp b/Lesson14/Pods/Realm/include/core/realm/util/fifo_helper.hpp deleted file mode 100644 index 6ca8d75..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/fifo_helper.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/************************************************************************* - * - * Copyright 2019 Realm Inc. - * - * 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 REALM_UTIL_FIFO_HELPER_HPP -#define REALM_UTIL_FIFO_HELPER_HPP - -#include - -namespace realm { -namespace util { - -// Attempts to create a FIFO file at the location determined by `path`. -// If creating the FIFO at this location fails, an exception is thrown. -// If a FIFO already exists at the given location, this method does nothing. -void create_fifo(std::string path); // throws - -// Same as above, but returns `false` if the FIFO could not be created instead of throwing. -bool try_create_fifo(const std::string& path); - -// Ensure that a path representing a directory ends with `/` -inline std::string normalize_dir(const std::string& path) { - return (!path.empty() && path.back() != '/') ? path + '/' : path; -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_FIFO_HELPER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/file.hpp b/Lesson14/Pods/Realm/include/core/realm/util/file.hpp deleted file mode 100644 index eb7ced0..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/file.hpp +++ /dev/null @@ -1,1331 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_FILE_HPP -#define REALM_UTIL_FILE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include // POSIX.1-2001 -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1900 // compiling with at least Visual Studio 2015 -#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING // switch to once we switch to C++17 -#include -namespace std { - namespace filesystem = std::experimental::filesystem::v1; -} -#define REALM_HAVE_STD_FILESYSTEM 1 -#else -#define REALM_HAVE_STD_FILESYSTEM 0 -#endif - -#include -#include -#include -#include -#include - - -namespace realm { -namespace util { - -class EncryptedFileMapping; - -/// Create the specified directory in the file system. -/// -/// \throw File::AccessError If the directory could not be created. If -/// the reason corresponds to one of the exception types that are -/// derived from File::AccessError, the derived exception type is -/// thrown (as long as the underlying system provides the information -/// to unambiguously distinguish that particular reason). -void make_dir(const std::string& path); - -/// Same as make_dir() except that this one returns false, rather than throwing -/// an exception, if the specified directory already existed. If the directory -// did not already exist and was newly created, this returns true. -bool try_make_dir(const std::string& path); - -/// Remove the specified empty directory path from the file system. It is an -/// error if the specified path is not a directory, or if it is a nonempty -/// directory. In so far as the specified path is a directory, std::remove(const -/// char*) is equivalent to this function. -/// -/// \throw File::AccessError If the directory could not be removed. If the -/// reason corresponds to one of the exception types that are derived from -/// File::AccessError, the derived exception type is thrown (as long as the -/// underlying system provides the information to unambiguously distinguish that -/// particular reason). -void remove_dir(const std::string& path); - -/// Same as remove_dir() except that this one returns false, rather -/// than throwing an exception, if the specified directory did not -/// exist. If the directory did exist, and was deleted, this function -/// returns true. -bool try_remove_dir(const std::string& path); - -/// Remove the specified directory after removing all its contents. Files -/// (nondirectory entries) will be removed as if by a call to File::remove(), -/// and empty directories as if by a call to remove_dir(). -/// -/// \throw File::AccessError If removal of the directory, or any of its contents -/// fail. -/// -/// remove_dir_recursive() assumes that no other process or thread is making -/// simultaneous changes in the directory. -void remove_dir_recursive(const std::string& path); - -/// Same as remove_dir_recursive() except that this one returns false, rather -/// than throwing an exception, if the specified directory did not -/// exist. If the directory did exist, and was deleted, this function -/// returns true. -/// -/// try_remove_dir_recursive() assumes that no other process or thread is making -/// simultaneous changes in the directory. -bool try_remove_dir_recursive(const std::string& path); - -/// Create a new unique directory for temporary files. The absolute -/// path to the new directory is returned without a trailing slash. -std::string make_temp_dir(); - -size_t page_size(); - - -/// This class provides a RAII abstraction over the concept of a file -/// descriptor (or file handle). -/// -/// Locks are automatically and immediately released when the File -/// instance is closed. -/// -/// You can use CloseGuard and UnlockGuard to acheive exception-safe -/// closing or unlocking prior to the File instance being detroyed. -/// -/// A single File instance must never be accessed concurrently by -/// multiple threads. -/// -/// You can write to a file via an std::ostream as follows: -/// -/// \code{.cpp} -/// -/// File::Streambuf my_streambuf(&my_file); -/// std::ostream out(&my_strerambuf); -/// out << 7945.9; -/// -/// \endcode -class File { -public: - enum Mode { - mode_Read, ///< access_ReadOnly, create_Never (fopen: rb) - mode_Update, ///< access_ReadWrite, create_Never (fopen: rb+) - mode_Write, ///< access_ReadWrite, create_Auto, flag_Trunc (fopen: wb+) - mode_Append ///< access_ReadWrite, create_Auto, flag_Append (fopen: ab+) - }; - - /// Equivalent to calling open(const std::string&, Mode) on a - /// default constructed instance. - explicit File(const std::string& path, Mode = mode_Read); - - /// Create an instance that is not initially attached to an open - /// file. - File() noexcept; - - ~File() noexcept; - - File(File&&) noexcept; - File& operator=(File&&) noexcept; - - // Disable copying by l-value. Copying an open file will create a scenario - // where the same file descriptor will be opened once but closed twice. - File(const File&) = delete; - File& operator=(const File&) = delete; - - /// Calling this function on an instance that is already attached - /// to an open file has undefined behavior. - /// - /// \throw AccessError If the file could not be opened. If the - /// reason corresponds to one of the exception types that are - /// derived from AccessError, the derived exception type is thrown - /// (as long as the underlying system provides the information to - /// unambiguously distinguish that particular reason). - void open(const std::string& path, Mode = mode_Read); - - /// This function is idempotent, that is, it is valid to call it - /// regardless of whether this instance currently is attached to - /// an open file. - void close() noexcept; - - /// Check whether this File instance is currently attached to an - /// open file. - bool is_attached() const noexcept; - - enum AccessMode { - access_ReadOnly, - access_ReadWrite, - }; - - enum CreateMode { - create_Auto, ///< Create the file if it does not already exist. - create_Never, ///< Fail if the file does not already exist. - create_Must ///< Fail if the file already exists. - }; - - enum { - flag_Trunc = 1, ///< Truncate the file if it already exists. - flag_Append = 2 ///< Move to end of file before each write. - }; - - /// See open(const std::string&, Mode). - /// - /// Specifying access_ReadOnly together with a create mode that is - /// not create_Never, or together with a non-zero \a flags - /// argument, results in undefined behavior. Specifying flag_Trunc - /// together with create_Must results in undefined behavior. - void open(const std::string& path, AccessMode, CreateMode, int flags); - - /// Same as open(path, access_ReadWrite, create_Auto, 0), except - /// that this one returns an indication of whether a new file was - /// created, or an existing file was opened. - void open(const std::string& path, bool& was_created); - - /// Read data into the specified buffer and return the number of - /// bytes read. If the returned number of bytes is less than \a - /// size, then the end of the file has been reached. - /// - /// Calling this function on an instance, that is not currently - /// attached to an open file, has undefined behavior. - size_t read(char* data, size_t size); - static size_t read_static(FileDesc fd, char* data, size_t size); - - /// Write the specified data to this file. - /// - /// Calling this function on an instance, that is not currently - /// attached to an open file, has undefined behavior. - /// - /// Calling this function on an instance, that was opened in - /// read-only mode, has undefined behavior. - void write(const char* data, size_t size); - static void write_static(FileDesc fd, const char* data, size_t size); - - // Tells current file pointer of fd - static uint64_t get_file_pos(FileDesc fd); - - /// Calls write(s.data(), s.size()). - void write(const std::string& s) - { - write(s.data(), s.size()); - } - - /// Calls read(data, N). - template - size_t read(char (&data)[N]) - { - return read(data, N); - } - - /// Calls write(data(), N). - template - void write(const char (&data)[N]) - { - write(data, N); - } - - /// Plays the same role as off_t in POSIX - typedef int_fast64_t SizeType; - - /// Calling this function on an instance that is not attached to - /// an open file has undefined behavior. - SizeType get_size() const; - static SizeType get_size_static(FileDesc fd); - - /// If this causes the file to grow, then the new section will - /// have undefined contents. Setting the size with this function - /// does not necessarily allocate space on the target device. If - /// you want to ensure allocation, call alloc(). Calling this - /// function will generally affect the read/write offset - /// associated with this File instance. - /// - /// Calling this function on an instance that is not attached to - /// an open file has undefined behavior. Calling this function on - /// a file that is opened in read-only mode, is an error. - void resize(SizeType); - - /// Same effect as prealloc_if_supported(original_size, new_size); - /// - /// The downside is that this function is not guaranteed to have - /// atomic behaviour on all systems, that is, two processes, or - /// two threads should never call this function concurrently for - /// the same underlying file even though they access the file - /// through distinct File instances. - /// - /// \sa prealloc_if_supported() - void prealloc(size_t new_size); - - /// When supported by the system, allocate space on the target - /// device for the specified region of the file. If the region - /// extends beyond the current end of the file, the file size is - /// increased as necessary. - /// - /// On systems that do not support this operation, this function - /// has no effect. You may call is_prealloc_supported() to - /// determine if it is supported on your system. - /// - /// Calling this function on an instance, that is not attached to - /// an open file, has undefined behavior. Calling this function on - /// a file, that is opened in read-only mode, is an error. - /// - /// This function is guaranteed to have atomic behaviour, that is, - /// there is never any risk of the file size being reduced even - /// with concurrently executing invocations. - /// - /// \sa prealloc() - /// \sa is_prealloc_supported() - bool prealloc_if_supported(SizeType offset, size_t size); - - /// See prealloc_if_supported(). - static bool is_prealloc_supported(); - - /// Reposition the read/write offset of this File - /// instance. Distinct File instances have separate independent - /// offsets, as long as the cucrrent process is not forked. - void seek(SizeType); - static void seek_static(FileDesc, SizeType); - - /// Flush in-kernel buffers to disk. This blocks the caller until the - /// synchronization operation is complete. On POSIX systems this function - /// calls `fsync()`. On Apple platforms if calls `fcntl()` with command - /// `F_FULLFSYNC`. - void sync(); - - /// Place an exclusive lock on this file. This blocks the caller - /// until all other locks have been released. - /// - /// Locks acquired on distinct File instances have fully recursive - /// behavior, even if they are acquired in the same process (or - /// thread) and are attached to the same underlying file. - /// - /// Calling this function on an instance that is not attached to - /// an open file, or on an instance that is already locked has - /// undefined behavior. - void lock_exclusive(); - - /// Place an shared lock on this file. This blocks the caller - /// until all other exclusive locks have been released. - /// - /// Locks acquired on distinct File instances have fully recursive - /// behavior, even if they are acquired in the same process (or - /// thread) and are attached to the same underlying file. - /// - /// Calling this function on an instance that is not attached to - /// an open file, or on an instance that is already locked has - /// undefined behavior. - void lock_shared(); - - /// Non-blocking version of lock_exclusive(). Returns true iff it - /// succeeds. - bool try_lock_exclusive(); - - /// Non-blocking version of lock_shared(). Returns true iff it - /// succeeds. - bool try_lock_shared(); - - /// Release a previously acquired lock on this file. This function - /// is idempotent. - void unlock() noexcept; - - /// Set the encryption key used for this file. Must be called before any - /// mappings are created or any data is read from or written to the file. - /// - /// \param key A 64-byte encryption key, or null to disable encryption. - void set_encryption_key(const char* key); - - /// Get the encryption key set by set_encryption_key(), - /// null_ptr if no key set. - const char* get_encryption_key(); - enum { - /// If possible, disable opportunistic flushing of dirted - /// pages of a memory mapped file to physical medium. On some - /// systems this cannot be disabled. On other systems it is - /// the default behavior. An explicit call to sync_map() will - /// flush the buffers regardless of whether this flag is - /// specified or not. - map_NoSync = 1 - }; - - /// Map this file into memory. The file is mapped as shared - /// memory. This allows two processes to interact under exatly the - /// same rules as applies to the interaction via regular memory of - /// multiple threads inside a single process. - /// - /// This File instance does not need to remain in existence after - /// the mapping is established. - /// - /// Multiple concurrent mappings may be created from the same File - /// instance. - /// - /// Specifying access_ReadWrite for a file that is opened in - /// read-only mode, is an error. - /// - /// Calling this function on an instance that is not attached to - /// an open file, or one that is attached to an empty file has - /// undefined behavior. - /// - /// Calling this function with a size that is greater than the - /// size of the file has undefined behavior. - void* map(AccessMode, size_t size, int map_flags = 0, size_t offset = 0) const; - - /// The same as unmap(old_addr, old_size) followed by map(a, - /// new_size, map_flags), but more efficient on some systems. - /// - /// The old address range must have been acquired by a call to - /// map() or remap() on this File instance, the specified access - /// mode and flags must be the same as the ones specified - /// previously, and this File instance must not have been reopend - /// in the meantime. Failing to adhere to these rules will result - /// in undefined behavior. - /// - /// If this function throws, the old address range will remain - /// mapped. - void* remap(void* old_addr, size_t old_size, AccessMode a, size_t new_size, int map_flags = 0, - size_t file_offset = 0) const; - -#if REALM_ENABLE_ENCRYPTION - void* map(AccessMode, size_t size, EncryptedFileMapping*& mapping, int map_flags = 0, size_t offset = 0) const; -#endif - /// Unmap the specified address range which must have been - /// previously returned by map(). - static void unmap(void* addr, size_t size) noexcept; - - /// Flush in-kernel buffers to disk. This blocks the caller until - /// the synchronization operation is complete. The specified - /// address range must be (a subset of) one that was previously returned by - /// map(). - static void sync_map(FileDesc fd, void* addr, size_t size); - - /// Check whether the specified file or directory exists. Note - /// that a file or directory that resides in a directory that the - /// calling process has no access to, will necessarily be reported - /// as not existing. - static bool exists(const std::string& path); - - /// Check whether the specified path exists and refers to a directory. If - /// the referenced file system object resides in an inaccessible directory, - /// this function returns false. - static bool is_dir(const std::string& path); - - /// Remove the specified file path from the file system. It is an error if - /// the specified path is a directory. If the specified file is a symbolic - /// link, the link is removed, leaving the liked file intact. In so far as - /// the specified path is not a directory, std::remove(const char*) is - /// equivalent to this function. - /// - /// The specified file must not be open by the calling process. If - /// it is, this function has undefined behaviour. Note that an - /// open memory map of the file counts as "the file being open". - /// - /// \throw AccessError If the specified directory entry could not - /// be removed. If the reason corresponds to one of the exception - /// types that are derived from AccessError, the derived exception - /// type is thrown (as long as the underlying system provides the - /// information to unambiguously distinguish that particular - /// reason). - static void remove(const std::string& path); - - /// Same as remove() except that this one returns false, rather - /// than throwing an exception, if the specified file does not - /// exist. If the file did exist, and was deleted, this function - /// returns true. - static bool try_remove(const std::string& path); - - /// Change the path of a directory entry. This can be used to - /// rename a file, and/or to move it from one directory to - /// another. This function is equivalent to std::rename(const - /// char*, const char*). - /// - /// \throw AccessError If the path of the directory entry could - /// not be changed. If the reason corresponds to one of the - /// exception types that are derived from AccessError, the derived - /// exception type is thrown (as long as the underlying system - /// provides the information to unambiguously distinguish that - /// particular reason). - static void move(const std::string& old_path, const std::string& new_path); - - /// Copy the file at the specified origin path to the specified target path. - static void copy(const std::string& origin_path, const std::string& target_path); - - /// Compare the two files at the specified paths for equality. Returns true - /// if, and only if they are equal. - static bool compare(const std::string& path_1, const std::string& path_2); - - /// Check whether two open file descriptors refer to the same - /// underlying file, that is, if writing via one of them, will - /// affect what is read from the other. In UNIX this boils down to - /// comparing inode numbers. - /// - /// Both instances have to be attached to open files. If they are - /// not, this function has undefined behavior. - bool is_same_file(const File&) const; - static bool is_same_file_static(FileDesc f1, FileDesc f2); - - // FIXME: Get rid of this method - bool is_removed() const; - - /// Resolve the specified path against the specified base directory. - /// - /// If \a path is absolute, or if \a base_dir is empty, \p path is returned - /// unmodified, otherwise \a path is resolved against \a base_dir. - /// - /// Examples (assuming POSIX): - /// - /// resolve("file", "dir") -> "dir/file" - /// resolve("../baz", "/foo/bar") -> "/foo/baz" - /// resolve("foo", ".") -> "./foo" - /// resolve(".", "/foo/") -> "/foo" - /// resolve("..", "foo") -> "." - /// resolve("../..", "foo") -> ".." - /// resolve("..", "..") -> "../.." - /// resolve("", "") -> "." - /// resolve("", "/") -> "/." - /// resolve("..", "/") -> "/." - /// resolve("..", "foo//bar") -> "foo" - /// - /// This function does not access the file system. - /// - /// \param path The path to be resolved. An empty string produces the same - /// result as as if "." was passed. The result has a trailing directory - /// separator (`/`) if, and only if this path has a trailing directory - /// separator. - /// - /// \param base_dir The base directory path, which may be relative or - /// absolute. A final directory separator (`/`) is optional. The empty - /// string is interpreted as a relative path. - static std::string resolve(const std::string& path, const std::string& base_dir); - - using ForEachHandler = std::function; - - /// Scan the specified directory recursivle, and report each file - /// (nondirectory entry) via the specified handler. - /// - /// The first argument passed to the handler is the name of a file (not the - /// whole path), and the second argument is the directory in which that file - /// resides. The directory will be specified as a path, and relative to \a - /// dir_path. The directory will be the empty string for files residing - /// directly in \a dir_path. - /// - /// If the handler returns false, scanning will be aborted immediately, and - /// for_each() will return false. Otherwise for_each() will return true. - /// - /// Scanning is done as if by a recursive set of DirScanner objects. - static bool for_each(const std::string& dir_path, ForEachHandler handler); - - struct UniqueID { -#ifdef _WIN32 // Windows version -// FIXME: This is not implemented for Windows -#else - // NDK r10e has a bug in sys/stat.h dev_t ino_t are 4 bytes, - // but stat.st_dev and st_ino are 8 bytes. So we just use uint64 instead. - dev_t device; - uint_fast64_t inode; -#endif - }; - // Return the unique id for the current opened file descriptor. - // Same UniqueID means they are the same file. - UniqueID get_unique_id() const; - // Return the file descriptor for the file - FileDesc get_descriptor() const; - // Return the path of the open file, or an empty string if - // this file has never been opened. - std::string get_path() const; - // Return false if the file doesn't exist. Otherwise uid will be set. - static bool get_unique_id(const std::string& path, UniqueID& uid); - - class ExclusiveLock; - class SharedLock; - - template - class Map; - - class CloseGuard; - class UnlockGuard; - class UnmapGuard; - - class Streambuf; - - // Exceptions - class AccessError; - class PermissionDenied; - class NotFound; - class Exists; - -private: -#ifdef _WIN32 - void* m_fd; - bool m_have_lock; // Only valid when m_fd is not null -#else - int m_fd; -#endif - std::unique_ptr m_encryption_key = nullptr; - std::string m_path; - - bool lock(bool exclusive, bool non_blocking); - void open_internal(const std::string& path, AccessMode, CreateMode, int flags, bool* success); - - struct MapBase { - void* m_addr = nullptr; - size_t m_size = 0; - FileDesc m_fd; - - MapBase() noexcept; - ~MapBase() noexcept; - - // Disable copying. Copying an opened MapBase will create a scenario - // where the same memory will be mapped once but unmapped twice. - MapBase(const MapBase&) = delete; - MapBase& operator=(const MapBase&) = delete; - - void map(const File&, AccessMode, size_t size, int map_flags, size_t offset = 0); - void remap(const File&, AccessMode, size_t size, int map_flags); - void unmap() noexcept; - void sync(); -#if REALM_ENABLE_ENCRYPTION - util::EncryptedFileMapping* m_encrypted_mapping = nullptr; - inline util::EncryptedFileMapping* get_encrypted_mapping() const - { - return m_encrypted_mapping; - } -#else - inline util::EncryptedFileMapping* get_encrypted_mapping() const - { - return nullptr; - } -#endif - }; -}; - - -class File::ExclusiveLock { -public: - ExclusiveLock(File& f) - : m_file(f) - { - f.lock_exclusive(); - } - ~ExclusiveLock() noexcept - { - m_file.unlock(); - } - // Disable copying. It is not how this class should be used. - ExclusiveLock(const ExclusiveLock&) = delete; - ExclusiveLock& operator=(const ExclusiveLock&) = delete; - -private: - File& m_file; -}; - -class File::SharedLock { -public: - SharedLock(File& f) - : m_file(f) - { - f.lock_shared(); - } - ~SharedLock() noexcept - { - m_file.unlock(); - } - // Disable copying. It is not how this class should be used. - SharedLock(const SharedLock&) = delete; - SharedLock& operator=(const SharedLock&) = delete; - -private: - File& m_file; -}; - - -/// This class provides a RAII abstraction over the concept of a -/// memory mapped file. -/// -/// Once created, the Map instance makes no reference to the File -/// instance that it was based upon, and that File instance may be -/// destroyed before the Map instance is destroyed. -/// -/// Multiple concurrent mappings may be created from the same File -/// instance. -/// -/// You can use UnmapGuard to acheive exception-safe unmapping prior -/// to the Map instance being detroyed. -/// -/// A single Map instance must never be accessed concurrently by -/// multiple threads. -template -class File::Map : private MapBase { -public: - /// Equivalent to calling map() on a default constructed instance. - explicit Map(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0); - - explicit Map(const File&, size_t offset, AccessMode = access_ReadOnly, size_t size = sizeof(T), - int map_flags = 0); - - /// Create an instance that is not initially attached to a memory - /// mapped file. - Map() noexcept; - - ~Map() noexcept; - - // Disable copying. Copying an opened Map will create a scenario - // where the same memory will be mapped once but unmapped twice. - Map(const Map&) = delete; - Map& operator=(const Map&) = delete; - - /// Move the mapping from another Map object to this Map object - File::Map& operator=(File::Map&& other) - { - if (m_addr) - unmap(); - m_addr = other.get_addr(); - m_size = other.m_size; - other.m_addr = 0; - other.m_size = 0; -#if REALM_ENABLE_ENCRYPTION - m_encrypted_mapping = other.m_encrypted_mapping; - other.m_encrypted_mapping = nullptr; -#endif - return *this; - } - - /// See File::map(). - /// - /// Calling this function on a Map instance that is already - /// attached to a memory mapped file has undefined behavior. The - /// returned pointer is the same as what will subsequently be - /// returned by get_addr(). - T* map(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0, size_t offset = 0); - - /// See File::unmap(). This function is idempotent, that is, it is - /// valid to call it regardless of whether this instance is - /// currently attached to a memory mapped file. - void unmap() noexcept; - - /// See File::remap(). - /// - /// Calling this function on a Map instance that is not currently - /// attached to a memory mapped file has undefined behavior. The - /// returned pointer is the same as what will subsequently be - /// returned by get_addr(). - T* remap(const File&, AccessMode = access_ReadOnly, size_t size = sizeof(T), int map_flags = 0); - - /// See File::sync_map(). - /// - /// Calling this function on an instance that is not currently - /// attached to a memory mapped file, has undefined behavior. - void sync(); - - /// Check whether this Map instance is currently attached to a - /// memory mapped file. - bool is_attached() const noexcept; - - /// Returns a pointer to the beginning of the memory mapped file, - /// or null if this instance is not currently attached. - T* get_addr() const noexcept; - - /// Returns the size of the mapped region, or zero if this - /// instance does not currently refer to a memory mapped - /// file. When this instance refers to a memory mapped file, the - /// returned value will always be identical to the size passed to - /// the constructor or to map(). - size_t get_size() const noexcept; - - /// Release the currently attached memory mapped file from this - /// Map instance. The address range may then be unmapped later by - /// a call to File::unmap(). - T* release() noexcept; - -#if REALM_ENABLE_ENCRYPTION - /// Get the encrypted file mapping corresponding to this mapping - inline EncryptedFileMapping* get_encrypted_mapping() const - { - return m_encrypted_mapping; - } -#else - inline EncryptedFileMapping* get_encrypted_mapping() const - { - return nullptr; - } -#endif - - friend class UnmapGuard; -}; - - -class File::CloseGuard { -public: - CloseGuard(File& f) noexcept - : m_file(&f) - { - } - ~CloseGuard() noexcept - { - if (m_file) - m_file->close(); - } - void release() noexcept - { - m_file = nullptr; - } - // Disallow the default implementation of copy/assign, this is not how this - // class is intended to be used. For example we could get unexpected - // behaviour if one CloseGuard is copied and released but the other is not. - CloseGuard(const CloseGuard&) = delete; - CloseGuard& operator=(const CloseGuard&) = delete; - -private: - File* m_file; -}; - - -class File::UnlockGuard { -public: - UnlockGuard(File& f) noexcept - : m_file(&f) - { - } - ~UnlockGuard() noexcept - { - if (m_file) - m_file->unlock(); - } - void release() noexcept - { - m_file = nullptr; - } - // Disallow the default implementation of copy/assign, this is not how this - // class is intended to be used. For example we could get unexpected - // behaviour if one UnlockGuard is copied and released but the other is not. - UnlockGuard(const UnlockGuard&) = delete; - UnlockGuard& operator=(const UnlockGuard&) = delete; - -private: - File* m_file; -}; - - -class File::UnmapGuard { -public: - template - UnmapGuard(Map& m) noexcept - : m_map(&m) - { - } - ~UnmapGuard() noexcept - { - if (m_map) - m_map->unmap(); - } - void release() noexcept - { - m_map = nullptr; - } - // Disallow the default implementation of copy/assign, this is not how this - // class is intended to be used. For example we could get unexpected - // behaviour if one UnmapGuard is copied and released but the other is not. - UnmapGuard(const UnmapGuard&) = delete; - UnmapGuard& operator=(const UnmapGuard&) = delete; - -private: - MapBase* m_map; -}; - - -/// Only output is supported at this point. -class File::Streambuf : public std::streambuf { -public: - explicit Streambuf(File*, size_t = 4096); - ~Streambuf() noexcept; - - // Disable copying - Streambuf(const Streambuf&) = delete; - Streambuf& operator=(const Streambuf&) = delete; - -private: - File& m_file; - std::unique_ptr const m_buffer; - - int_type overflow(int_type) override; - int sync() override; - pos_type seekpos(pos_type, std::ios_base::openmode) override; - void flush(); -}; - -/// Used for any I/O related exception. Note the derived exception -/// types that are used for various specific types of errors. -class File::AccessError : public ExceptionWithBacktrace { -public: - AccessError(const std::string& msg, const std::string& path); - - /// Return the associated file system path, or the empty string if there is - /// no associated file system path, or if the file system path is unknown. - std::string get_path() const; - - const char* message() const noexcept - { - m_buffer = std::runtime_error::what(); - if (m_path.size() > 0) - m_buffer += (std::string(" Path: ") + m_path); - return m_buffer.c_str(); - } - -private: - std::string m_path; - mutable std::string m_buffer; -}; - - -/// Thrown if the user does not have permission to open or create -/// the specified file in the specified access mode. -class File::PermissionDenied : public AccessError { -public: - PermissionDenied(const std::string& msg, const std::string& path); -}; - - -/// Thrown if the directory part of the specified path was not -/// found, or create_Never was specified and the file did no -/// exist. -class File::NotFound : public AccessError { -public: - NotFound(const std::string& msg, const std::string& path); -}; - - -/// Thrown if create_Always was specified and the file did already -/// exist. -class File::Exists : public AccessError { -public: - Exists(const std::string& msg, const std::string& path); -}; - - -class DirScanner { -public: - DirScanner(const std::string& path, bool allow_missing = false); - ~DirScanner() noexcept; - bool next(std::string& name); - -private: -#ifndef _WIN32 - DIR* m_dirp; -#elif REALM_HAVE_STD_FILESYSTEM - std::filesystem::directory_iterator m_iterator; -#endif -}; - - -// Implementation: - -inline File::File(const std::string& path, Mode m) -{ -#ifdef _WIN32 - m_fd = nullptr; -#else - m_fd = -1; -#endif - - open(path, m); -} - -inline File::File() noexcept -{ -#ifdef _WIN32 - m_fd = nullptr; -#else - m_fd = -1; -#endif -} - -inline File::~File() noexcept -{ - close(); -} - -inline File::File(File&& f) noexcept -{ -#ifdef _WIN32 - m_fd = f.m_fd; - m_have_lock = f.m_have_lock; - f.m_fd = nullptr; -#else - m_fd = f.m_fd; - f.m_fd = -1; -#endif - m_encryption_key = std::move(f.m_encryption_key); -} - -inline File& File::operator=(File&& f) noexcept -{ - close(); -#ifdef _WIN32 - m_fd = f.m_fd; - m_have_lock = f.m_have_lock; - f.m_fd = nullptr; -#else - m_fd = f.m_fd; - f.m_fd = -1; -#endif - m_encryption_key = std::move(f.m_encryption_key); - return *this; -} - -inline void File::open(const std::string& path, Mode m) -{ - AccessMode a = access_ReadWrite; - CreateMode c = create_Auto; - int flags = 0; - switch (m) { - case mode_Read: - a = access_ReadOnly; - c = create_Never; - break; - case mode_Update: - c = create_Never; - break; - case mode_Write: - flags = flag_Trunc; - break; - case mode_Append: - flags = flag_Append; - break; - } - open(path, a, c, flags); -} - -inline void File::open(const std::string& path, AccessMode am, CreateMode cm, int flags) -{ - open_internal(path, am, cm, flags, nullptr); -} - - -inline void File::open(const std::string& path, bool& was_created) -{ - while (1) { - bool success; - open_internal(path, access_ReadWrite, create_Must, 0, &success); - if (success) { - was_created = true; - return; - } - open_internal(path, access_ReadWrite, create_Never, 0, &success); - if (success) { - was_created = false; - return; - } - } -} - -inline bool File::is_attached() const noexcept -{ -#ifdef _WIN32 - return (m_fd != nullptr); -#else - return 0 <= m_fd; -#endif -} - -inline void File::lock_exclusive() -{ - lock(true, false); -} - -inline void File::lock_shared() -{ - lock(false, false); -} - -inline bool File::try_lock_exclusive() -{ - return lock(true, true); -} - -inline bool File::try_lock_shared() -{ - return lock(false, true); -} - -inline File::MapBase::MapBase() noexcept -{ - m_addr = nullptr; -} - -inline File::MapBase::~MapBase() noexcept -{ - unmap(); -} - -inline void File::MapBase::map(const File& f, AccessMode a, size_t size, int map_flags, size_t offset) -{ - REALM_ASSERT(!m_addr); -#if REALM_ENABLE_ENCRYPTION - m_addr = f.map(a, size, m_encrypted_mapping, map_flags, offset); -#else - m_addr = f.map(a, size, map_flags, offset); -#endif - m_size = size; - m_fd = f.m_fd; -} - -inline void File::MapBase::unmap() noexcept -{ - if (!m_addr) - return; - File::unmap(m_addr, m_size); - m_addr = nullptr; -#if REALM_ENABLE_ENCRYPTION - m_encrypted_mapping = nullptr; -#endif - m_fd = 0; -} - -inline void File::MapBase::remap(const File& f, AccessMode a, size_t size, int map_flags) -{ - REALM_ASSERT(m_addr); - - //m_addr = f.remap(m_addr, m_size, a, size, map_flags); - // missing sync() here? - unmap(); - map(f, a, size, map_flags); - m_size = size; - m_fd = f.m_fd; -} - -inline void File::MapBase::sync() -{ - REALM_ASSERT(m_addr); - - File::sync_map(m_fd, m_addr, m_size); -} - -template -inline File::Map::Map(const File& f, AccessMode a, size_t size, int map_flags) -{ - map(f, a, size, map_flags); -} - -template -inline File::Map::Map(const File& f, size_t offset, AccessMode a, size_t size, int map_flags) -{ - map(f, a, size, map_flags, offset); -} - -template -inline File::Map::Map() noexcept -{ -} - -template -inline File::Map::~Map() noexcept -{ -} - -template -inline T* File::Map::map(const File& f, AccessMode a, size_t size, int map_flags, size_t offset) -{ - MapBase::map(f, a, size, map_flags, offset); - return static_cast(m_addr); -} - -template -inline void File::Map::unmap() noexcept -{ - MapBase::unmap(); -} - -template -inline T* File::Map::remap(const File& f, AccessMode a, size_t size, int map_flags) -{ - MapBase::remap(f, a, size, map_flags); - return static_cast(m_addr); -} - -template -inline void File::Map::sync() -{ - MapBase::sync(); -} - -template -inline bool File::Map::is_attached() const noexcept -{ - return (m_addr != nullptr); -} - -template -inline T* File::Map::get_addr() const noexcept -{ - return static_cast(m_addr); -} - -template -inline size_t File::Map::get_size() const noexcept -{ - return m_addr ? m_size : 0; -} - -template -inline T* File::Map::release() noexcept -{ - T* addr = static_cast(m_addr); - m_addr = nullptr; - m_fd = 0; - return addr; -} - - -inline File::Streambuf::Streambuf(File* f, size_t buffer_size) - : m_file(*f) - , m_buffer(new char[buffer_size]) -{ - char* b = m_buffer.get(); - setp(b, b + buffer_size); -} - -inline File::Streambuf::~Streambuf() noexcept -{ - try { - if (m_file.is_attached()) - flush(); - } - catch (...) { - // Errors deliberately ignored - } -} - -inline File::Streambuf::int_type File::Streambuf::overflow(int_type c) -{ - flush(); - if (c == traits_type::eof()) - return traits_type::not_eof(c); - *pptr() = traits_type::to_char_type(c); - pbump(1); - return c; -} - -inline int File::Streambuf::sync() -{ - flush(); - return 0; -} - -inline File::Streambuf::pos_type File::Streambuf::seekpos(pos_type pos, std::ios_base::openmode) -{ - flush(); - SizeType pos2 = 0; - if (int_cast_with_overflow_detect(std::streamsize(pos), pos2)) - throw util::overflow_error("Seek position overflow"); - m_file.seek(pos2); - return pos; -} - -inline void File::Streambuf::flush() -{ - size_t n = pptr() - pbase(); - if (n > 0) { - m_file.write(pbase(), n); - setp(m_buffer.get(), epptr()); - } -} - -inline File::AccessError::AccessError(const std::string& msg, const std::string& path) - : ExceptionWithBacktrace(msg) - , m_path(path) -{ -} - -inline std::string File::AccessError::get_path() const -{ - return m_path; -} - -inline File::PermissionDenied::PermissionDenied(const std::string& msg, const std::string& path) - : AccessError(msg, path) -{ -} - -inline File::NotFound::NotFound(const std::string& msg, const std::string& path) - : AccessError(msg, path) -{ -} - -inline File::Exists::Exists(const std::string& msg, const std::string& path) - : AccessError(msg, path) -{ -} - -inline bool operator==(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ -#ifdef _WIN32 // Windows version - throw util::runtime_error("Not yet supported"); -#else // POSIX version - return lhs.device == rhs.device && lhs.inode == rhs.inode; -#endif -} - -inline bool operator!=(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ - return !(lhs == rhs); -} - -inline bool operator<(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ -#ifdef _WIN32 // Windows version - throw util::runtime_error("Not yet supported"); -#else // POSIX version - if (lhs.device < rhs.device) - return true; - if (lhs.device > rhs.device) - return false; - if (lhs.inode < rhs.inode) - return true; - return false; -#endif -} - -inline bool operator>(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ - return rhs < lhs; -} - -inline bool operator<=(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ - return !(lhs > rhs); -} - -inline bool operator>=(const File::UniqueID& lhs, const File::UniqueID& rhs) -{ - return !(lhs < rhs); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_FILE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/file_mapper.hpp b/Lesson14/Pods/Realm/include/core/realm/util/file_mapper.hpp deleted file mode 100644 index d02f15d..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/file_mapper.hpp +++ /dev/null @@ -1,179 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_FILE_MAPPER_HPP -#define REALM_UTIL_FILE_MAPPER_HPP - -#include -#include -#include -#include - -#include - -namespace realm { -namespace util { - -void* mmap(FileDesc fd, size_t size, File::AccessMode access, size_t offset, const char* encryption_key); -void munmap(void* addr, size_t size); -void* mremap(FileDesc fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size, - const char* encryption_key); -void msync(FileDesc fd, void* addr, size_t size); - -// A function which may be given to encryption_read_barrier. If present, the read barrier is a -// a barrier for a full array. If absent, the read barrier is a barrier only for the address -// range give as argument. If the barrier is for a full array, it will read the array header -// and determine the address range from the header. -using HeaderToSize = size_t (*)(const char* addr); -class EncryptedFileMapping; - -class PageReclaimGovernor { -public: - // Called by the page reclaimer with the current load (in bytes) and - // must return the target load (also in bytes). Returns no_match if no - // target can be set - static constexpr int64_t no_match = -1; - virtual std::function current_target_getter(size_t load) = 0; - virtual void report_target_result(int64_t) = 0; -}; - -// Set a page reclaim governor. The governor is an object with a method which will be called periodically -// and must return a 'target' amount of memory to hold decrypted pages. The page reclaim daemon -// will then try to release pages to meet the target. The governor is called with the current -// amount of data used, for the purpose of logging - or possibly for computing the target -// -// The governor is called approximately once per second. -// -// If no governor is installed, the page reclaim daemon will not start. -void set_page_reclaim_governor(PageReclaimGovernor* governor); - -// Use the default governor. The default governor is used automatically if nothing else is set, so -// this funciton is mostly useful for tests where changing back to the default could be desirable. -inline void set_page_reclaim_governor_to_default() -{ - set_page_reclaim_governor(nullptr); -} - -// Retrieves the number of in memory decrypted pages, across all open files. -size_t get_num_decrypted_pages(); - -// Retrieves the -// - amount of memory used for decrypted pages, across all open files. -// - current target for the reclaimer (desired number of decrypted pages) -// - current workload size for the reclaimer, across all open files. -struct decrypted_memory_stats_t { - size_t memory_size; - size_t reclaimer_target; - size_t reclaimer_workload; -}; - -decrypted_memory_stats_t get_decrypted_memory_stats(); - -#if REALM_ENABLE_ENCRYPTION - -void encryption_note_reader_start(SharedFileInfo& info, const void* reader_id); -void encryption_note_reader_end(SharedFileInfo& info, const void* reader_id) noexcept; - -SharedFileInfo* get_file_info_for_file(File& file); - -// This variant allows the caller to obtain direct access to the encrypted file mapping -// for optimization purposes. -void* mmap(FileDesc fd, size_t size, File::AccessMode access, size_t offset, const char* encryption_key, - EncryptedFileMapping*& mapping); - -void do_encryption_read_barrier(const void* addr, size_t size, HeaderToSize header_to_size, - EncryptedFileMapping* mapping); - -void do_encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping); - -void inline encryption_read_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping, - HeaderToSize header_to_size = nullptr) -{ - if (mapping) - do_encryption_read_barrier(addr, size, header_to_size, mapping); -} - -void inline encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping) -{ - if (mapping) - do_encryption_write_barrier(addr, size, mapping); -} - - -extern util::Mutex& mapping_mutex; - -inline void do_encryption_read_barrier(const void* addr, size_t size, HeaderToSize header_to_size, - EncryptedFileMapping* mapping) -{ - UniqueLock lock(mapping_mutex); - mapping->read_barrier(addr, size, header_to_size); -} - -inline void do_encryption_write_barrier(const void* addr, size_t size, EncryptedFileMapping* mapping) -{ - LockGuard lock(mapping_mutex); - mapping->write_barrier(addr, size); -} - -#else - -void inline set_page_reclaim_governor(PageReclaimGovernor*) -{ -} - -size_t inline get_num_decrypted_pages() -{ - return 0; -} - -void inline encryption_read_barrier(const void*, size_t, EncryptedFileMapping*, HeaderToSize = nullptr) -{ -} - -void inline encryption_write_barrier(const void*, size_t) -{ -} - -void inline encryption_write_barrier(const void*, size_t, EncryptedFileMapping*) -{ -} - -#endif - -// helpers for encrypted Maps -template -void encryption_read_barrier(File::Map& map, size_t index, size_t num_elements = 1) -{ - T* addr = map.get_addr(); - encryption_read_barrier(addr + index, sizeof(T) * num_elements, map.get_encrypted_mapping()); -} - -template -void encryption_write_barrier(File::Map& map, size_t index, size_t num_elements = 1) -{ - T* addr = map.get_addr(); - encryption_write_barrier(addr + index, sizeof(T) * num_elements, map.get_encrypted_mapping()); -} - -File::SizeType encrypted_size_to_data_size(File::SizeType size) noexcept; -File::SizeType data_size_to_encrypted_size(File::SizeType size) noexcept; - -size_t round_up_to_page_size(size_t size) noexcept; -} -} -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp b/Lesson14/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp deleted file mode 100644 index 8a512ee..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/fixed_size_buffer.hpp +++ /dev/null @@ -1,135 +0,0 @@ -/************************************************************************* - * - * Copyright 2019 Realm Inc. - * - * 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 REALM_UTIL_FIXED_SIZE_BUFFER_HPP -#define REALM_UTIL_FIXED_SIZE_BUFFER_HPP - -#include -#include -#include - -namespace realm { -namespace util { - -/// This is a buffer with a fixed size. You can only insert elements. -/// When the number of elements inserted matches the size of the buffer, -/// additional insertions will overwrite the oldest elements. -template -class FixedSizeBuffer { -public: - class iterator; - - FixedSizeBuffer(size_t sz) - : m_size(sz) - { - if (sz == 0) - throw std::runtime_error("FixedSizeBuffer size cannot be 0"); - m_buffer.reserve(sz); - } - size_t size() - { - return m_buffer.size(); - } - void insert(const T& val) - { - if (m_buffer.size() < m_size) { - m_buffer.emplace_back(val); - } - else { - m_buffer[m_oldest] = val; - ++m_oldest; - if (m_oldest == m_size) - m_oldest = 0; - } - } - T& at(size_t n) - { - auto idx = (n + m_oldest) % m_size; - return m_buffer[idx]; - } - T& operator[](size_t n) - { - return at(n); - } - iterator begin() - { - return iterator(*this, 0); - } - iterator end() - { - return iterator(*this, m_buffer.size()); - } - -private: - std::vector m_buffer; - size_t m_size; - size_t m_oldest = 0; -}; - -template -class FixedSizeBuffer::iterator { -public: - typedef std::forward_iterator_tag iterator_category; - typedef T value_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef T& reference; - - iterator(FixedSizeBuffer& b, size_t ndx) - : m_cb(b) - , m_ndx(ndx) - { - } - pointer operator->() - { - return &m_cb[m_ndx]; - } - reference operator*() - { - return m_cb[m_ndx]; - } - iterator& operator++() - { - ++m_ndx; - return *this; - } - iterator operator++(int) - { - iterator tmp(*this); - operator++(); - return tmp; - } - bool operator!=(const iterator& rhs) - { - return m_ndx != rhs.m_ndx; - } - bool operator==(const iterator& rhs) - { - return m_ndx == rhs.m_ndx; - } - -private: - FixedSizeBuffer& m_cb; - size_t m_ndx; -}; - -} // namespace util -} // namespace realm - - -#endif /* REALM_UTIL_FIXED_SIZE_BUFFER_HPP */ diff --git a/Lesson14/Pods/Realm/include/core/realm/util/flat_map.hpp b/Lesson14/Pods/Realm/include/core/realm/util/flat_map.hpp deleted file mode 100644 index a3d6b54..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/flat_map.hpp +++ /dev/null @@ -1,201 +0,0 @@ - -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2017] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_FLAT_MAP_HPP -#define REALM_UTIL_FLAT_MAP_HPP - -#include -#include // std::pair -#include // std::lower_bound etc. -#include - -#include - -namespace realm { -namespace util { - -template >, class Cmp = std::less<>> -struct FlatMap { - using value_type = std::pair; - using key_type = K; - using mapped_type = V; - FlatMap() {} - FlatMap(const FlatMap&) = default; - FlatMap(FlatMap&&) = default; - FlatMap& operator=(const FlatMap&) = default; - FlatMap& operator=(FlatMap&&) = default; - - V& at(K key) - { - auto it = lower_bound(key); - if (it == end() || it->first != key) - it = m_data.emplace(it, std::move(key), V{}); // Throws - return it->second; - } - - const V& at(const K& key) const - { - auto it = find(key); - if (it == end()) - throw util::out_of_range("no such key"); - return it->second; - } - - V& operator[](const K& key) - { - return at(key); // Throws - } - - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - iterator begin() noexcept { return m_data.begin(); } - iterator end() noexcept { return m_data.end(); } - const_iterator begin() const noexcept { return m_data.begin(); } - const_iterator end() const noexcept { return m_data.end(); } - - - bool empty() const noexcept { return m_data.empty(); } - size_t size() const noexcept { return m_data.size(); } - void clear() noexcept { m_data.clear(); } - - std::pair insert(value_type value) - { - auto it = lower_bound(value.first); - if (it != end() && it->first == value.first) { - return std::make_pair(it, false); - } - return std::make_pair(m_data.emplace(it, std::move(value)), true); // Throws - } - - template - std::pair insert(P pair) - { - return insert(value_type{std::get<0>(pair), std::get<1>(pair)}); - } - - template - void insert(InputIt first, InputIt last) - { - for (auto it = first; it != last; ++it) { - insert(*it); - } - } - - template - std::pair emplace(Args&&... args) - { - value_type value{std::forward(args)...}; - return insert(std::move(value)); - } - - template - std::pair emplace_hint(const_iterator pos, Args&&... args) - { - static_cast(pos); // FIXME: TODO - return emplace(std::forward(args)...); - } - - iterator erase(const_iterator pos) noexcept(std::is_nothrow_move_assignable::value) - { - return m_data.erase(pos); - } - - iterator erase(const_iterator first, const_iterator last) noexcept(std::is_nothrow_move_assignable::value) - { - return m_data.erase(first, last); - } - - size_t erase(const K& key) noexcept(std::is_nothrow_move_assignable::value) - { - auto it = find(key); - if (it != end()) { - erase(it); - return 1; - } - return 0; - } - - void swap(FlatMap& other) - { - m_data.swap(other.m_data); - } - - template - size_t count(const Key& key) const noexcept - { - return find(key) == end() ? 0 : 1; - } - - template - iterator find(const Key& key) noexcept - { - const FlatMap* This = this; - const_iterator pos = This->find(key); - return iterator{begin() + (pos - This->begin())}; - } - - template - const_iterator find(const Key& key) const noexcept - { - auto it = lower_bound(key); - if (it != end() && it->first != key) { - return end(); - } - return it; - } - - template - iterator lower_bound(const Key& key) noexcept - { - const FlatMap* This = this; - const_iterator pos = This->lower_bound(key); - return iterator{begin() + (pos - This->begin())}; - } - - template - const_iterator lower_bound(const Key& key) const noexcept - { - auto it = std::lower_bound(begin(), end(), key, [](const value_type& a, const Key& b) { - return Cmp{}(a.first, b); - }); - return it; - } - - // FIXME: Not implemented yet. - template - iterator upper_bound(const Key&) noexcept; - // FIXME: Not implemented yet. - template - const_iterator upper_bound(const Key&) const noexcept; - - void reserve(size_t size) - { - m_data.reserve(size); // Throws - } - -private: - Container m_data; -}; - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_FLAT_MAP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/get_file_size.hpp b/Lesson14/Pods/Realm/include/core/realm/util/get_file_size.hpp deleted file mode 100644 index 29ca1a7..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/get_file_size.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_GET_FILE_SIZE_HPP -#define REALM_UTIL_GET_FILE_SIZE_HPP - -#include - -namespace realm { -namespace util { - -/// FIXME: This function ought to be moved to in the -/// realm-core repository. -util::File::SizeType get_file_size(const std::string& path); - - - -// Implementation - -inline util::File::SizeType get_file_size(const std::string& path) -{ - util::File file{path}; // Throws - return file.get_size(); // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_GET_FILE_SIZE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/hex_dump.hpp b/Lesson14/Pods/Realm/include/core/realm/util/hex_dump.hpp deleted file mode 100644 index 08f5d2b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/hex_dump.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_HEX_DUMP_HPP -#define REALM_UTIL_HEX_DUMP_HPP - -#include -#include -#include -#include -#include -#include - -#include - -namespace realm { -namespace util { - -template -std::string hex_dump(const T* data, size_t size, const char* separator = " ", int min_digits = -1) -{ - using U = typename std::make_unsigned::type; - - if (min_digits < 0) - min_digits = (std::numeric_limits::digits + 3) / 4; - - std::ostringstream out; - for (const T* i = data; i != data + size; ++i) { - if (i != data) - out << separator; - out << std::setw(min_digits) << std::setfill('0') << std::hex << std::uppercase << util::promote(U(*i)); - } - return out.str(); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_HEX_DUMP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/http.hpp b/Lesson14/Pods/Realm/include/core/realm/util/http.hpp deleted file mode 100644 index 91da876..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/http.hpp +++ /dev/null @@ -1,541 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_HTTP_HPP -#define REALM_UTIL_HTTP_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace realm { -namespace util { -enum class HTTPParserError { - None = 0, - ContentTooLong, - HeaderLineTooLong, - MalformedResponse, - MalformedRequest, - BadRequest, -}; -std::error_code make_error_code(HTTPParserError); -} // namespace util -} // namespace realm - -namespace std { -template<> struct is_error_code_enum : std::true_type {}; -} - -namespace realm { -namespace util { - -/// See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html -/// -/// It is guaranteed that the backing integer value of this enum corresponds -/// to the numerical code representing the status. -enum class HTTPStatus { - Unknown = 0, - - Continue = 100, - SwitchingProtocols = 101, - - Ok = 200, - Created = 201, - Accepted = 202, - NonAuthoritative = 203, - NoContent = 204, - ResetContent = 205, - PartialContent = 206, - - MultipleChoices = 300, - MovedPermanently = 301, - Found = 302, - SeeOther = 303, - NotModified = 304, - UseProxy = 305, - SwitchProxy = 306, - TemporaryRedirect = 307, - PermanentRedirect = 308, - - BadRequest = 400, - Unauthorized = 401, - PaymentRequired = 402, - Forbidden = 403, - NotFound = 404, - MethodNotAllowed = 405, - NotAcceptable = 406, - ProxyAuthenticationRequired = 407, - RequestTimeout = 408, - Conflict = 409, - Gone = 410, - LengthRequired = 411, - PreconditionFailed = 412, - PayloadTooLarge = 413, - UriTooLong = 414, - UnsupportedMediaType = 415, - RangeNotSatisfiable = 416, - ExpectationFailed = 417, - ImATeapot = 418, - MisdirectedRequest = 421, - UpgradeRequired = 426, - PreconditionRequired = 428, - TooManyRequests = 429, - RequestHeaderFieldsTooLarge = 431, - UnavailableForLegalReasons = 451, - - InternalServerError = 500, - NotImplemented = 501, - BadGateway = 502, - ServiceUnavailable = 503, - GatewayTimeout = 504, - HttpVersionNotSupported = 505, - VariantAlsoNegotiates = 506, - NotExtended = 510, - NetworkAuthenticationRequired = 511, -}; - -bool valid_http_status_code(unsigned int code); - -/// See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html -enum class HTTPMethod { - Options, - Get, - Head, - Post, - Put, - Delete, - Trace, - Connect, -}; - -struct HTTPAuthorization { - std::string scheme; - std::map values; -}; - -HTTPAuthorization parse_authorization(const std::string&); - -class HeterogeneousCaseInsensitiveCompare { -public: - using is_transparent = std::true_type; - template bool operator()(const A& a, const B& b) const noexcept - { - return comp(StringView(a), StringView(b)); - } -private: - bool comp(StringView a, StringView b) const noexcept - { - auto cmp = [](char lhs, char rhs) { - return std::tolower(lhs, std::locale::classic()) < - std::tolower(rhs, std::locale::classic()); - }; - return std::lexicographical_compare(begin(a), end(a), begin(b), end(b), cmp); - } -}; - -/// Case-insensitive map suitable for storing HTTP headers. -using HTTPHeaders = std::map; - -struct HTTPRequest { - HTTPMethod method = HTTPMethod::Get; - HTTPHeaders headers; - std::string path; - - /// If the request object has a body, the Content-Length header MUST be - /// set to a string representation of the number of bytes in the body. - /// FIXME: Relax this restriction, and also support Transfer-Encoding - /// and other HTTP/1.1 features. - Optional body; -}; - -struct HTTPResponse { - HTTPStatus status = HTTPStatus::Unknown; - std::string reason; - HTTPHeaders headers; - - // A body is only read from the response stream if the server sent the - // Content-Length header. - // FIXME: Support other transfer methods, including Transfer-Encoding and - // HTTP/1.1 features. - Optional body; -}; - - -/// Serialize HTTP request to output stream. -std::ostream& operator<<(std::ostream&, const HTTPRequest&); -/// Serialize HTTP response to output stream. -std::ostream& operator<<(std::ostream&, const HTTPResponse&); -/// Serialize HTTP method to output stream ("GET", "POST", etc.). -std::ostream& operator<<(std::ostream&, HTTPMethod); -/// Serialize HTTP status to output stream, include reason string ("200 OK" etc.) -std::ostream& operator<<(std::ostream&, HTTPStatus); - - -struct HTTPParserBase { - util::Logger& logger; - - // FIXME: Generally useful? - struct CallocDeleter { - void operator()(void* ptr) - { - std::free(ptr); - } - }; - - HTTPParserBase(util::Logger& logger_2): - logger {logger_2} - { - // Allocating read buffer with calloc to avoid accidentally spilling - // data from other sessions in case of a buffer overflow exploit. - m_read_buffer.reset(static_cast(std::calloc(read_buffer_size, 1))); - } - virtual ~HTTPParserBase() {} - - std::string m_write_buffer; - std::unique_ptr m_read_buffer; - Optional m_found_content_length; - static const size_t read_buffer_size = 8192; - static const size_t max_header_line_length = read_buffer_size; - - /// Parses the contents of m_read_buffer as a HTTP header line, - /// and calls on_header() as appropriate. on_header() will be called at - /// most once per invocation. - /// Returns false if the contents of m_read_buffer is not a valid HTTP - /// header line. - bool parse_header_line(size_t len); - - virtual std::error_code on_first_line(StringData line) = 0; - virtual void on_header(StringData key, StringData value) = 0; - virtual void on_body(StringData body) = 0; - virtual void on_complete(std::error_code = std::error_code{}) = 0; - - /// If the input matches a known HTTP method string, return the appropriate - /// HTTPMethod enum value. Otherwise, returns none. - static Optional parse_method_string(StringData method); - - /// Interpret line as the first line of an HTTP request. If the return value - /// is true, out_method and out_uri have been assigned the appropriate - /// values found in the request line. - static bool parse_first_line_of_request(StringData line, HTTPMethod& out_method, - StringData& out_uri); - - /// Interpret line as the first line of an HTTP response. If the return - /// value is true, out_status and out_reason have been assigned the - /// appropriate values found in the response line. - static bool parse_first_line_of_response(StringData line, HTTPStatus& out_status, - StringData& out_reason, util::Logger& logger); - - void set_write_buffer(const HTTPRequest&); - void set_write_buffer(const HTTPResponse&); -}; - - -template -struct HTTPParser: protected HTTPParserBase { - explicit HTTPParser(Socket& socket, util::Logger& logger): - HTTPParserBase(logger), - m_socket(socket) - {} - - void read_first_line() - { - auto handler = [this](std::error_code ec, size_t n) { - if (ec == error::operation_aborted) { - return; - } - if (ec) { - on_complete(ec); - return; - } - ec = on_first_line(StringData(m_read_buffer.get(), n)); - if (ec) { - on_complete(ec); - return; - } - read_headers(); - }; - m_socket.async_read_until(m_read_buffer.get(), max_header_line_length, '\n', - std::move(handler)); - } - - void read_headers() - { - auto handler = [this](std::error_code ec, size_t n) { - if (ec == error::operation_aborted) { - return; - } - if (ec) { - on_complete(ec); - return; - } - if (n <= 2) { - read_body(); - return; - } - if (!parse_header_line(n)) { - on_complete(HTTPParserError::BadRequest); - return; - } - - // FIXME: Limit the total size of headers. Apache uses 8K. - read_headers(); - }; - m_socket.async_read_until(m_read_buffer.get(), max_header_line_length, '\n', - std::move(handler)); - } - - void read_body() - { - if (m_found_content_length) { - // FIXME: Support longer bodies. - // FIXME: Support multipart and other body types (no body shaming). - if (*m_found_content_length > read_buffer_size) { - on_complete(HTTPParserError::ContentTooLong); - return; - } - - auto handler = [this](std::error_code ec, size_t n) { - if (ec == error::operation_aborted) { - return; - } - if (!ec) { - on_body(StringData(m_read_buffer.get(), n)); - } - on_complete(ec); - }; - m_socket.async_read(m_read_buffer.get(), *m_found_content_length, - std::move(handler)); - } - else { - // No body, just finish. - on_complete(); - } - } - - void write_buffer(std::function handler) - { - m_socket.async_write(m_write_buffer.data(), m_write_buffer.size(), - std::move(handler)); - } - - Socket& m_socket; -}; - - -template -struct HTTPClient: protected HTTPParser { - using Handler = void(HTTPResponse, std::error_code); - - explicit HTTPClient(Socket& socket, util::Logger& logger) : HTTPParser(socket, logger) {} - - /// Serialize and send \a request over the connected socket asynchronously. - /// - /// When the response has been received, or an error occurs, \a handler will - /// be invoked with the appropriate parameters. The HTTPResponse object - /// passed to \a handler will only be complete in non-error conditions, but - /// may be partially populated. - /// - /// It is an error to start a request before the \a handler of a previous - /// request has been invoked. It is permitted to call async_request() from - /// the handler, unless an error has been reported representing a condition - /// where the underlying socket is no longer able to communicate (for - /// example, if it has been closed). - /// - /// If a request is already in progress, an exception will be thrown. - /// - /// This method is *NOT* thread-safe. - void async_request(const HTTPRequest& request, std::function handler) - { - if (REALM_UNLIKELY(m_handler)) { - throw util::runtime_error("Request already in progress."); - } - this->set_write_buffer(request); - m_handler = std::move(handler); - this->write_buffer([this](std::error_code ec, size_t bytes_written) { - static_cast(bytes_written); - if (ec == error::operation_aborted) { - return; - } - if (ec) { - this->on_complete(ec); - return; - } - this->read_first_line(); - }); - } - -private: - std::function m_handler; - HTTPResponse m_response; - - std::error_code on_first_line(StringData line) override final - { - HTTPStatus status; - StringData reason; - if (this->parse_first_line_of_response(line, status, reason, this->logger)) { - m_response.status = status; - m_response.reason = reason; - return std::error_code{}; - } - return HTTPParserError::MalformedResponse; - } - - void on_header(StringData key, StringData value) override final - { - // FIXME: Multiple headers with the same key should show up as a - // comma-separated list of their values, rather than overwriting. - m_response.headers[std::string(key)] = std::string(value); - } - - void on_body(StringData body) override final - { - m_response.body = std::string(body); - } - - void on_complete(std::error_code ec) override final - { - auto handler = std::move(m_handler); - m_handler = nullptr; - handler(std::move(m_response), ec); - } -}; - - -template -struct HTTPServer: protected HTTPParser { - using RequestHandler = void(HTTPRequest, std::error_code); - using RespondHandler = void(std::error_code); - - explicit HTTPServer(Socket& socket, util::Logger& logger): HTTPParser(socket, logger) - {} - - /// Receive a request on the underlying socket asynchronously. - /// - /// This function starts an asynchronous read operation and keeps reading - /// until an HTTP request has been received. \a handler is invoked when a - /// request has been received, or an error occurs. - /// - /// After a request is received, callers MUST invoke async_send_response() - /// to provide the client with a valid HTTP response, unless the error - /// passed to the handler represents a condition where the underlying socket - /// is no longer able to communicate (for example, if it has been closed). - /// - /// It is an error to attempt to receive a request before any previous - /// requests have been fully responded to, i.e. the \a handler argument of - /// async_send_response() must have been invoked before attempting to - /// receive the next request. - /// - /// This function is *NOT* thread-safe. - void async_receive_request(std::function handler) - { - if (REALM_UNLIKELY(m_request_handler)) { - throw util::runtime_error("Response already in progress."); - } - m_request_handler = std::move(handler); - this->read_first_line(); - } - - /// Send an HTTP response to a client asynchronously. - /// - /// This function starts an asynchronous write operation on the underlying - /// socket. \a handler is invoked when the response has been written to the - /// socket, or an error occurs. - /// - /// It is an error to call async_receive_request() again before \a handler - /// has been invoked, and it is an error to call async_send_response() - /// before the \a handler of a previous invocation has been invoked. - /// - /// This function is *NOT* thread-safe. - void async_send_response(const HTTPResponse& response, - std::function handler) - { - if (REALM_UNLIKELY(!m_request_handler)) { - throw util::runtime_error("No request in progress."); - } - if (m_respond_handler) { - // FIXME: Proper exception type. - throw util::runtime_error("Already responding to request"); - } - m_respond_handler = std::move(handler); - this->set_write_buffer(response); - this->write_buffer([this](std::error_code ec, size_t) { - if (ec == error::operation_aborted) { - return; - } - m_request_handler = nullptr; - auto handler = std::move(m_respond_handler); - handler(ec); - });; - } - -private: - std::function m_request_handler; - std::function m_respond_handler; - HTTPRequest m_request; - - std::error_code on_first_line(StringData line) override final - { - HTTPMethod method; - StringData uri; - if (this->parse_first_line_of_request(line, method, uri)) { - m_request.method = method; - m_request.path = uri; - return std::error_code{}; - } - return HTTPParserError::MalformedRequest; - } - - void on_header(StringData key, StringData value) override final - { - // FIXME: Multiple headers with the same key should show up as a - // comma-separated list of their values, rather than overwriting. - m_request.headers[std::string(key)] = std::string(value); - } - - void on_body(StringData body) override final - { - m_request.body = std::string(body); - } - - void on_complete(std::error_code ec) override final - { - // Deliberately not nullifying m_request_handler so that we can - // check for invariants in async_send_response. - m_request_handler(std::move(m_request), ec); - } -}; - - -std::string make_http_host(bool is_ssl, StringView address, std::uint_fast16_t port); - -} // namespace util -} // namespace realm - - -#endif // REALM_UTIL_HTTP_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/inspect.hpp b/Lesson14/Pods/Realm/include/core/realm/util/inspect.hpp deleted file mode 100644 index 84a669d..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/inspect.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_INSPECT_HPP -#define REALM_UTIL_INSPECT_HPP - -#include - -namespace realm { -namespace util { - -// LCOV_EXCL_START -// -// Because these are templated functions, every combination of output stream -// type and value(s) type(s) generates a new function. This makes LCOV/GCOVR -// report over 70 functions in this file, with only 6.6% function coverage, -// even though line coverage is at 100%. - -template -void inspect_value(OS& os, const T& value) -{ - os << value; -} - -template -void inspect_value(OS& os, const std::string& value) -{ - // FIXME: Escape the string. - os << "\"" << value << "\""; -} - -template -void inspect_value(OS& os, const char* value) -{ - // FIXME: Escape the string. - os << "\"" << value << "\""; -} - -template -void inspect_all(OS&) -{ - // No-op -} - -/// Convert all arguments to strings, and quote string arguments. -template -void inspect_all(OS& os, First&& first, Args&&... args) -{ - inspect_value(os, std::forward(first)); - if (sizeof...(Args) != 0) { - os << ", "; - } - inspect_all(os, std::forward(args)...); -} - -// LCOV_EXCL_STOP - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_INSPECT_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp b/Lesson14/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp deleted file mode 100644 index 0e5b586..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/interprocess_condvar.hpp +++ /dev/null @@ -1,151 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_INTERPROCESS_CONDVAR -#define REALM_UTIL_INTERPROCESS_CONDVAR - - -#include -#include -#include -#include -#include -#include -#include - -// Condvar Emulation is required if RobustMutex emulation is enabled -#if defined(REALM_ROBUST_MUTEX_EMULATION) || defined(_WIN32) -#define REALM_CONDVAR_EMULATION -#endif - -namespace realm { -namespace util { - - -/// Condition variable for use in synchronization monitors. -/// This condition variable uses emulation based on named pipes -/// for the inter-process case, if enabled by REALM_CONDVAR_EMULATION. -/// -/// FIXME: This implementation will never release/delete pipes. This is unlikely -/// to be a problem as long as only a modest number of different database names -/// are in use -/// -/// A InterprocessCondVar is always process shared. -class InterprocessCondVar { -public: - InterprocessCondVar(); - ~InterprocessCondVar() noexcept; - - // Disable copying. Copying an open file will create a scenario - // where the same file descriptor will be opened once but closed twice. - InterprocessCondVar(const InterprocessCondVar&) = delete; - InterprocessCondVar& operator=(const InterprocessCondVar&) = delete; - -/// To use the InterprocessCondVar, you also must place a structure of type -/// InterprocessCondVar::SharedPart in memory shared by multiple processes -/// or in a memory mapped file, and use set_shared_part() to associate -/// the condition variable with it's shared part. You must initialize -/// the shared part using InterprocessCondVar::init_shared_part(), but only before -/// first use and only when you have exclusive access to the shared part. - -#ifdef REALM_CONDVAR_EMULATION - struct SharedPart { -#ifdef _WIN32 - // Number of waiting threads. - int32_t m_waiters_count; - size_t m_was_broadcast; -#else - uint64_t signal_counter; - uint64_t wait_counter; -#endif - }; -#else - typedef CondVar SharedPart; -#endif - - /// You need to bind the emulation to a SharedPart in shared/mmapped memory. - /// The SharedPart is assumed to have been initialized (possibly by another process) - /// earlier through a call to init_shared_part. - void set_shared_part(SharedPart& shared_part, std::string path, std::string condvar_name, std::string tmp_path); - - /// Initialize the shared part of a process shared condition variable. - /// A process shared condition variables may be represented by any number of - /// InterprocessCondVar instances in any number of different processes, - /// all sharing a common SharedPart instance, which must be in shared memory. - static void init_shared_part(SharedPart& shared_part); - - /// Release any system resources allocated for the shared part. This should - /// be used *only* when you are certain, that nobody is using it. - void release_shared_part(); - - /// Wait for someone to call notify() or notify_all() on this condition - /// variable. The call to wait() may return spuriously, so the caller should - /// always re-evaluate the condition on which to wait and loop on wait() - /// if necessary. - void wait(InterprocessMutex& m, const struct timespec* tp); - - /// If any threads are waiting for this condition, wake up at least one. - /// (Current implementation may actually wake all :-O ). The caller must - /// hold the lock associated with the condvar at the time of calling notify() - void notify() noexcept; - - /// Wake up every thread that is currently waiting on this condition. - /// The caller must hold the lock associated with the condvar at the time - /// of calling notify_all(). - void notify_all() noexcept; - - /// Cleanup and release system resources if possible. - void close() noexcept; - -private: - // non-zero if a shared part has been registered (always 0 on process local instances) - SharedPart* m_shared_part = nullptr; -#ifdef REALM_CONDVAR_EMULATION - // keep the path to allocated system resource so we can remove them again - std::string m_resource_path; - // pipe used for emulation. When using a named pipe, m_fd_read is read-write and m_fd_write is unused. - // When using an anonymous pipe (currently only for tvOS) m_fd_read is read-only and m_fd_write is write-only. - int m_fd_read = -1; - int m_fd_write = -1; - -#ifdef _WIN32 - // Semaphore used to queue up threads waiting for the condition to - // become signaled. - HANDLE m_sema = 0; - // An auto-reset event used by the broadcast/signal thread to wait - // for all the waiting thread(s) to wake up and be released from the - // semaphore. - HANDLE m_waiters_done = 0; - std::string m_name; - - // Serialize access to m_waiters_count - InterprocessMutex m_waiters_lockcount; -#endif - -#endif -}; - - -// Implementation: - - -} // namespace util -} // namespace realm - - -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp b/Lesson14/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp deleted file mode 100644 index b3af1c6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/interprocess_mutex.hpp +++ /dev/null @@ -1,375 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_INTERPROCESS_MUTEX -#define REALM_UTIL_INTERPROCESS_MUTEX - -#include -#include -#include -#include -#include -#include -#include - -// Enable this only on platforms where it might be needed -#if REALM_PLATFORM_APPLE || REALM_ANDROID -#define REALM_ROBUST_MUTEX_EMULATION -#endif - -namespace realm { -namespace util { - -// fwd decl to support friend decl below -class InterprocessCondVar; - - -/// Emulation of a Robust Mutex. -/// A Robust Mutex is an interprocess mutex which will automatically -/// release any locks held by a process when it crashes. Contrary to -/// Posix robust mutexes, this robust mutex is not capable of informing -/// participants that they have been granted a lock after a crash of -/// the process holding it (though it could be added if needed). - -class InterprocessMutex { -public: - InterprocessMutex(); - ~InterprocessMutex() noexcept; - - // Disable copying. Copying a locked Mutex will create a scenario - // where the same file descriptor will be locked once but unlocked twice. - InterprocessMutex(const InterprocessMutex&) = delete; - InterprocessMutex& operator=(const InterprocessMutex&) = delete; - -#if defined(REALM_ROBUST_MUTEX_EMULATION) || defined(_WIN32) - struct SharedPart { - }; -#else - using SharedPart = RobustMutex; -#endif - - /// You need to bind the emulation to a SharedPart in shared/mmapped memory. - /// The SharedPart is assumed to have been initialized (possibly by another process) - /// elsewhere. - void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name); - void set_shared_part(SharedPart& shared_part, File&& lock_file); - - /// Destroy shared object. Potentially release system resources. Caller must - /// ensure that the shared_part is not in use at the point of call. - void release_shared_part(); - - /// Lock the mutex. If the mutex is already locked, wait for it to be unlocked. - void lock(); - - /// Non-blocking attempt to lock the mutex. Returns true if the lock is obtained. - /// If the lock can not be obtained return false immediately. - bool try_lock(); - - /// Unlock the mutex - void unlock(); - - /// Attempt to check if the mutex is valid (only relevant if not emulating) - bool is_valid() noexcept; - - static bool is_robust_on_this_platform() - { -#ifdef REALM_ROBUST_MUTEX_EMULATION - return true; // we're faking it! -#else - return RobustMutex::is_robust_on_this_platform(); -#endif - } - -private: -#ifdef REALM_ROBUST_MUTEX_EMULATION - struct LockInfo { - File m_file; - Mutex m_local_mutex; - LockInfo() {} - ~LockInfo() noexcept; - // Disable copying. - LockInfo(const LockInfo&) = delete; - LockInfo& operator=(const LockInfo&) = delete; - }; - /// InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo. - /// LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key. - /// Operations on the map need to be protected by s_mutex - static std::map>* s_info_map; - static Mutex* s_mutex; - /// We manually initialize these static variables when first needed, - /// creating them on the heap so that they last for the entire lifetime - /// of the process. The destructor of these is never called; the - /// process will clean up their memory when exiting. It is not enough - /// to count instances of InterprocessMutex and clean up these statics when - /// the count reaches zero because the program can create more - /// InterprocessMutex instances before the process ends, so we really need - /// these variables for the entire lifetime of the process. - static std::once_flag s_init_flag; - static void initialize_statics(); - - /// Only used for release_shared_part - std::string m_filename; - File::UniqueID m_fileuid; - std::shared_ptr m_lock_info; - - /// Free the lock info hold by this instance. - /// If it is the last reference, underly resources will be freed as well. - void free_lock_info(); -#else - SharedPart* m_shared_part = nullptr; - -#ifdef _WIN32 - HANDLE m_handle = 0; -#endif - -#endif - friend class InterprocessCondVar; -}; - -inline InterprocessMutex::InterprocessMutex() -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - std::call_once(s_init_flag, initialize_statics); -#endif -} - -inline InterprocessMutex::~InterprocessMutex() noexcept -{ -#ifdef _WIN32 - if (m_handle) { - bool b = CloseHandle(m_handle); - REALM_ASSERT_RELEASE(b); - } -#endif - -#ifdef REALM_ROBUST_MUTEX_EMULATION - free_lock_info(); -#endif -} - -#ifdef REALM_ROBUST_MUTEX_EMULATION -inline InterprocessMutex::LockInfo::~LockInfo() noexcept -{ - if (m_file.is_attached()) { - m_file.close(); - } -} - -inline void InterprocessMutex::free_lock_info() -{ - // It has not been initialized yet. - if (!m_lock_info) - return; - - std::lock_guard guard(*s_mutex); - - m_lock_info.reset(); - if ((*s_info_map)[m_fileuid].expired()) { - s_info_map->erase(m_fileuid); - } - m_filename.clear(); -} - -inline void InterprocessMutex::initialize_statics() -{ - s_mutex = new Mutex(); - s_info_map = new std::map>(); -} -#endif - -inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path, - const std::string& mutex_name) -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - static_cast(shared_part); - - free_lock_info(); - - m_filename = path + "." + mutex_name + ".mx"; - - std::lock_guard guard(*s_mutex); - - // Try to get the file uid if the file exists - if (File::get_unique_id(m_filename, m_fileuid)) { - auto result = s_info_map->find(m_fileuid); - if (result != s_info_map->end()) { - // File exists and the lock info has been created in the map. - m_lock_info = result->second.lock(); - return; - } - } - - // LockInfo has not been created yet. - m_lock_info = std::make_shared(); - // Always use mod_Write to open file and retreive the uid in case other process - // deletes the file. - m_lock_info->m_file.open(m_filename, File::mode_Write); - m_fileuid = m_lock_info->m_file.get_unique_id(); - - (*s_info_map)[m_fileuid] = m_lock_info; -#elif defined(_WIN32) - if (m_handle) { - bool b = CloseHandle(m_handle); - REALM_ASSERT_RELEASE(b); - } - // replace backslashes because they're significant in object namespace names - std::string path_escaped = path; - std::replace(path_escaped.begin(), path_escaped.end(), '\\', '/'); - std::string name = "Local\\realm_named_intermutex_" + path_escaped + mutex_name; - - std::wstring wname(name.begin(), name.end()); - m_handle = CreateMutexW(0, false, wname.c_str()); - if (!m_handle) { - throw std::system_error(GetLastError(), std::system_category(), "Error opening mutex"); - } -#else - m_shared_part = &shared_part; - static_cast(path); - static_cast(mutex_name); -#endif -} - -inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file) -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - static_cast(shared_part); - - free_lock_info(); - - std::lock_guard guard(*s_mutex); - - m_fileuid = lock_file.get_unique_id(); - auto result = s_info_map->find(m_fileuid); - if (result == s_info_map->end()) { - m_lock_info = std::make_shared(); - m_lock_info->m_file = std::move(lock_file); - (*s_info_map)[m_fileuid] = m_lock_info; - } - else { - // File exists and the lock info has been created in the map. - m_lock_info = result->second.lock(); - lock_file.close(); - } -#else - m_shared_part = &shared_part; - static_cast(lock_file); -#endif -} - -inline void InterprocessMutex::release_shared_part() -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - if (!m_filename.empty()) - File::try_remove(m_filename); - - free_lock_info(); -#else - m_shared_part = nullptr; -#endif -} - -inline void InterprocessMutex::lock() -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - std::unique_lock mutex_lock(m_lock_info->m_local_mutex); - m_lock_info->m_file.lock_exclusive(); - mutex_lock.release(); -#else - -#ifdef _WIN32 - DWORD d = WaitForSingleObject(m_handle, INFINITE); - REALM_ASSERT_RELEASE(d != WAIT_FAILED); -#else - REALM_ASSERT(m_shared_part); - m_shared_part->lock([]() {}); -#endif -#endif -} - -inline bool InterprocessMutex::try_lock() -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - std::unique_lock mutex_lock(m_lock_info->m_local_mutex, std::try_to_lock_t()); - if (!mutex_lock.owns_lock()) { - return false; - } - bool success = m_lock_info->m_file.try_lock_exclusive(); - if (success) { - mutex_lock.release(); - return true; - } - else { - return false; - } -#else - -#ifdef _WIN32 - DWORD ret = WaitForSingleObject(m_handle, 0); - REALM_ASSERT_RELEASE(ret != WAIT_FAILED); - - if (ret == WAIT_OBJECT_0) { - return true; - } - else { - return false; - } -#else - REALM_ASSERT(m_shared_part); - return m_shared_part->try_lock([]() {}); -#endif -#endif -} - - -inline void InterprocessMutex::unlock() -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - m_lock_info->m_file.unlock(); - m_lock_info->m_local_mutex.unlock(); -#else -#ifdef _WIN32 - bool b = ReleaseMutex(m_handle); - REALM_ASSERT_RELEASE(b); -#else - REALM_ASSERT(m_shared_part); - m_shared_part->unlock(); -#endif -#endif -} - - -inline bool InterprocessMutex::is_valid() noexcept -{ -#ifdef REALM_ROBUST_MUTEX_EMULATION - return true; -#elif defined(_WIN32) - // There is no safe way of testing if the m_handle mutex handle is valid on Windows, without having bad side effects - // for the cases where it is indeed invalid. If m_handle contains an arbitrary value, it might by coincidence be equal - // to a real live handle of another kind. This excludes a try_lock implementation and many other ideas. - return true; -#else - REALM_ASSERT(m_shared_part); - return m_shared_part->is_valid(); -#endif -} - - -} // namespace util -} // namespace realm - -#endif // #ifndef REALM_UTIL_INTERPROCESS_MUTEX diff --git a/Lesson14/Pods/Realm/include/core/realm/util/json_parser.hpp b/Lesson14/Pods/Realm/include/core/realm/util/json_parser.hpp deleted file mode 100644 index bc6664a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/json_parser.hpp +++ /dev/null @@ -1,545 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_JSON_PARSER_HPP -#define REALM_UTIL_JSON_PARSER_HPP - -#include -#include -#include -#include - -#include - -namespace realm { -namespace util { - -/// A JSON parser that neither allocates heap memory nor throws exceptions. -/// -/// The parser takes as input a range of characters, and emits a stream of events -/// representing the structure of the JSON document. -/// -/// Parser errors are represented as `std::error_condition`s. -class JSONParser { -public: - using InputIterator = const char*; - - enum class EventType { - number, - string, - boolean, - null, - array_begin, - array_end, - object_begin, - object_end - }; - - using Range = StringData; - - struct Event { - EventType type; - Range range; - Event(EventType type): type(type) {} - - union { - bool boolean; - double number; - }; - - StringData escaped_string_value() const noexcept; - - /// Unescape the string value into \a buffer. - /// The type of this event must be EventType::string. - /// - /// \param buffer is a pointer to a buffer big enough to hold the - /// unescaped string value. The unescaped string is guaranteed to be - /// shorter than the escaped string, so escaped_string_value().size() can - /// be used as an upper bound. Unicode sequences of the form "\uXXXX" - /// will be converted to UTF-8 sequences. Note that the escaped form of - /// a unicode point takes exactly 6 bytes, which is also the maximum - /// possible length of a UTF-8 encoded codepoint. - StringData unescape_string(char* buffer) const noexcept; - }; - - enum class Error { - unexpected_token = 1, - unexpected_end_of_stream = 2 - }; - - JSONParser(StringData); - - /// Parse the input data, and call f repeatedly with an argument of type Event - /// representing the token that the parser encountered. - /// - /// The stream of events is "flat", which is to say that it is the responsibility - /// of the function f to keep track of any nested object structures as it deems - /// appropriate. - /// - /// This function is guaranteed to never throw, as long as f never throws. - template - std::error_condition parse(F&& f) noexcept(noexcept(f(std::declval()))); - - class ErrorCategory: public std::error_category { - public: - const char* name() const noexcept final; - std::string message(int) const final; - }; - static const ErrorCategory error_category; -private: - enum Token: char { - object_begin = '{', - object_end = '}', - array_begin = '[', - array_end = ']', - colon = ':', - comma = ',', - dquote = '"', - escape = '\\', - minus = '-', - space = ' ', - tab = '\t', - cr = '\r', - lf = '\n', - }; - - InputIterator m_current; - InputIterator m_end; - - template - std::error_condition parse_object(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_pair(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_array(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_number(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_string(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_value(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_boolean(F&& f) noexcept(noexcept(f(std::declval()))); - template - std::error_condition parse_null(F&& f) noexcept(noexcept(f(std::declval()))); - - std::error_condition expect_token(char, Range& out_range) noexcept; - std::error_condition expect_token(Token, Range& out_range) noexcept; - - // Returns true unless EOF was reached. - bool peek_char(char& out_c) noexcept; - bool peek_token(Token& out_t) noexcept; - bool is_whitespace(Token t) noexcept; - void skip_whitespace() noexcept; -}; - -std::error_condition make_error_condition(JSONParser::Error e); - -} // namespace util -} // namespace realm - -namespace std { -template<> -struct is_error_condition_enum { - static const bool value = true; -}; -} - -namespace realm { -namespace util { - -/// Implementation: - - -inline JSONParser::JSONParser(StringData input): - m_current(input.data()), m_end(input.data() + input.size()) -{ -} - -template -std::error_condition JSONParser::parse(F&& f) noexcept(noexcept(f(std::declval()))) -{ - return parse_value(f); -} - -template -std::error_condition JSONParser::parse_object(F&& f) noexcept(noexcept(f(std::declval()))) -{ - Event event{EventType::object_begin}; - auto ec = expect_token(Token::object_begin, event.range); - if (ec) - return ec; - ec = f(event); - if (ec) - return ec; - - while (true) { - ec = expect_token(Token::object_end, event.range); - if (!ec) { - // End of object - event.type = EventType::object_end; - ec = f(event); - if (ec) - return ec; - break; - } - - if (ec != Error::unexpected_token) - return ec; - - ec = parse_pair(f); - if (ec) - return ec; - - skip_whitespace(); - - Token t; - if (peek_token(t)) { - if (t == Token::object_end) { - // Fine, will terminate on next iteration - } - else if (t == Token::comma) - ++m_current; // OK, because peek_char returned true - else - return Error::unexpected_token; - } - else { - return Error::unexpected_end_of_stream; - } - } - - return std::error_condition{}; -} - -template -std::error_condition JSONParser::parse_pair(F&& f) noexcept(noexcept(f(std::declval()))) -{ - skip_whitespace(); - - auto ec = parse_string(f); - if (ec) - return ec; - - skip_whitespace(); - - Token t; - if (peek_token(t)) { - if (t == Token::colon) { - ++m_current; - } - else { - return Error::unexpected_token; - } - } - - return parse_value(f); -} - -template -std::error_condition JSONParser::parse_array(F&& f) noexcept(noexcept(f(std::declval()))) -{ - Event event{EventType::array_begin}; - auto ec = expect_token(Token::array_begin, event.range); - if (ec) - return ec; - ec = f(event); - if (ec) - return ec; - - while (true) { - ec = expect_token(Token::array_end, event.range); - if (!ec) { - // End of array - event.type = EventType::array_end; - ec = f(event); - if (ec) - return ec; - break; - } - - if (ec != Error::unexpected_token) - return ec; - - ec = parse_value(f); - if (ec) - return ec; - - skip_whitespace(); - - Token t; - if (peek_token(t)) { - if (t == Token::array_end) { - // Fine, will terminate next iteration. - } - else if (t == Token::comma) - ++m_current; // OK, because peek_char returned true - else - return Error::unexpected_token; - } - else { - return Error::unexpected_end_of_stream; - } - } - - return std::error_condition{}; -} - -template -std::error_condition JSONParser::parse_number(F&& f) noexcept(noexcept(f(std::declval()))) -{ - static const size_t buffer_size = 64; - char buffer[buffer_size] = {0}; - size_t bytes_to_copy = std::min(m_end - m_current, buffer_size - 1); - if (bytes_to_copy == 0) - return Error::unexpected_end_of_stream; - - if (std::isspace(*m_current)) { - // JSON has a different idea of what constitutes whitespace than isspace(), - // but strtod() uses isspace() to skip initial whitespace. We have already - // skipped whitespace that JSON considers valid, so if there is any whitespace - // at m_current now, it is invalid according to JSON, and so is an error. - return Error::unexpected_token; - } - - switch (m_current[0]) { - case 'N': - // strtod() parses "NAN", JSON does not. - case 'I': - // strtod() parses "INF", JSON does not. - case 'p': - case 'P': - // strtod() may parse exponent notation, JSON does not. - return Error::unexpected_token; - case '0': - if (bytes_to_copy > 2 && (m_current[1] == 'x' || m_current[1] == 'X')) { - // strtod() parses hexadecimal, JSON does not. - return Error::unexpected_token; - } - } - - std::copy(m_current, m_current + bytes_to_copy, buffer); - - char* endp = nullptr; - Event event{EventType::number}; - event.number = std::strtod(buffer, &endp); - - if (endp == buffer) { - return Error::unexpected_token; - } - size_t num_bytes_consumed = endp - buffer; - m_current += num_bytes_consumed; - return f(event); -} - -template -std::error_condition JSONParser::parse_string(F&& f) noexcept(noexcept(f(std::declval()))) -{ - InputIterator p = m_current; - if (p >= m_end) - return Error::unexpected_end_of_stream; - - auto count_num_escapes_backwards = [](const char* p, const char* begin) -> size_t { - size_t result = 0; - for (; p > begin && *p == Token::escape; ++p) - ++result; - return result; - }; - - Token t = static_cast(*p); - InputIterator inner_end; - if (t == Token::dquote) { - inner_end = m_current; - do { - inner_end = std::find(inner_end + 1, m_end, Token::dquote); - if (inner_end == m_end) - return Error::unexpected_end_of_stream; - } while (count_num_escapes_backwards(inner_end - 1, m_current) % 2 == 1); - - Event event{EventType::string}; - event.range = Range(m_current, inner_end - m_current + 1); - m_current = inner_end + 1; - return f(event); - } - return Error::unexpected_token; -} - -template -std::error_condition JSONParser::parse_boolean(F&& f) noexcept(noexcept(f(std::declval()))) -{ - auto first_nonalpha = std::find_if_not(m_current, m_end, [](auto c) { return std::isalpha(c); }); - - Event event{EventType::boolean}; - event.range = Range(m_current, first_nonalpha - m_current); - if (event.range == "true") { - event.boolean = true; - m_current += 4; - return f(event); - } - else if (event.range == "false") { - event.boolean = false; - m_current += 5; - return f(event); - } - - return Error::unexpected_token; -} - -template -std::error_condition JSONParser::parse_null(F&& f) noexcept(noexcept(f(std::declval()))) -{ - auto first_nonalpha = std::find_if_not(m_current, m_end, [](auto c) { return std::isalpha(c); }); - - Event event{EventType::null}; - event.range = Range(m_current, first_nonalpha - m_current); - if (event.range == "null") { - m_current += 4; - return f(event); - } - - return Error::unexpected_token; -} - -template -std::error_condition JSONParser::parse_value(F&& f) noexcept(noexcept(f(std::declval()))) -{ - skip_whitespace(); - - if (m_current >= m_end) - return Error::unexpected_end_of_stream; - - if (*m_current == Token::object_begin) - return parse_object(f); - - if (*m_current == Token::array_begin) - return parse_array(f); - - if (*m_current == 't' || *m_current == 'f') - return parse_boolean(f); - - if (*m_current == 'n') - return parse_null(f); - - if (*m_current == Token::dquote) - return parse_string(f); - - return parse_number(f); -} - -inline -bool JSONParser::is_whitespace(Token t) noexcept -{ - switch (t) { - case Token::space: - case Token::tab: - case Token::cr: - case Token::lf: - return true; - default: - return false; - } -} - -inline -void JSONParser::skip_whitespace() noexcept -{ - while (m_current < m_end && is_whitespace(static_cast(*m_current))) - ++m_current; -} - -inline -std::error_condition JSONParser::expect_token(char c, Range& out_range) noexcept -{ - skip_whitespace(); - if (m_current == m_end) - return Error::unexpected_end_of_stream; - if (*m_current == c) { - out_range = Range(m_current, 1); - ++m_current; - return std::error_condition{}; - } - return Error::unexpected_token; -} - -inline -std::error_condition JSONParser::expect_token(Token t, Range& out_range) noexcept -{ - return expect_token(static_cast(t), out_range); -} - -inline -bool JSONParser::peek_char(char& out_c) noexcept -{ - if (m_current < m_end) { - out_c = *m_current; - return true; - } - return false; -} - -inline -bool JSONParser::peek_token(Token& out_t) noexcept -{ - if (m_current < m_end) { - out_t = static_cast(*m_current); - return true; - } - return false; -} - -inline -StringData JSONParser::Event::escaped_string_value() const noexcept -{ - REALM_ASSERT(type == EventType::string); - REALM_ASSERT(range.size() >= 2); - return StringData(range.data() + 1, range.size() - 2); -} - -template -OS& operator<<(OS& os, JSONParser::EventType type) -{ - switch (type) { - case JSONParser::EventType::number: os << "number"; return os; - case JSONParser::EventType::string: os << "string"; return os; - case JSONParser::EventType::boolean: os << "boolean"; return os; - case JSONParser::EventType::null: os << "null"; return os; - case JSONParser::EventType::array_begin: os << "["; return os; - case JSONParser::EventType::array_end: os << "]"; return os; - case JSONParser::EventType::object_begin: os << "{"; return os; - case JSONParser::EventType::object_end: os << "}"; return os; - } - REALM_UNREACHABLE(); -} - -template -OS& operator<<(OS& os, const JSONParser::Event& e) { - os << e.type; - switch (e.type) { - case JSONParser::EventType::number: return os << "(" << e.number << ")"; - case JSONParser::EventType::string: return os << "(" << e.range << ")"; - case JSONParser::EventType::boolean: return os << "(" << e.boolean << ")"; - default: return os; - } -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_JSON_PARSER_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/load_file.hpp b/Lesson14/Pods/Realm/include/core/realm/util/load_file.hpp deleted file mode 100644 index 14090fc..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/load_file.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_LOAD_FILE_HPP -#define REALM_UTIL_LOAD_FILE_HPP - -#include - -namespace realm { -namespace util { - -// FIXME: These functions ought to be moved to in the -// realm-core repository. -std::string load_file(const std::string& path); -std::string load_file_and_chomp(const std::string& path); - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_LOAD_FILE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/logger.hpp b/Lesson14/Pods/Realm/include/core/realm/util/logger.hpp deleted file mode 100644 index 0946208..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/logger.hpp +++ /dev/null @@ -1,511 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_LOGGER_HPP -#define REALM_UTIL_LOGGER_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace realm { -namespace util { - - -/// All Logger objects store a reference to a LevelThreshold object which it -/// uses to efficiently query about the current log level threshold -/// (`level_threshold.get()`). All messages logged with a level that is lower -/// than the current threshold will be dropped. For the sake of efficiency, this -/// test happens before the message is formatted. -/// -/// A logger is not inherently thread-safe, but specific implementations can be -/// (see ThreadSafeLogger). For a logger to be thread-safe, the implementation -/// of do_log() must be thread-safe and the referenced LevelThreshold object -/// must have a thread-safe get() method. -/// -/// Examples: -/// -/// logger.error("Overlong message from master coordinator"); -/// logger.info("Listening for peers on %1:%2", listen_address, listen_port); -class Logger { -public: - template - void trace(const char* message, Params&&...); - template - void debug(const char* message, Params&&...); - template - void detail(const char* message, Params&&...); - template - void info(const char* message, Params&&...); - template - void warn(const char* message, Params&&...); - template - void error(const char* message, Params&&...); - template - void fatal(const char* message, Params&&...); - - /// Specifies criticality when passed to log(). Functions as a criticality - /// threshold when returned from LevelThreshold::get(). - /// - /// error Be silent unless when there is an error. - /// warn Be silent unless when there is an error or a warning. - /// info Reveal information about what is going on, but in a - /// minimalistic fashion to avoid general overhead from logging - /// and to keep volume down. - /// detail Same as 'info', but prioritize completeness over minimalism. - /// debug Reveal information that can aid debugging, no longer paying - /// attention to efficiency. - /// trace A version of 'debug' that allows for very high volume - /// output. - enum class Level { all, trace, debug, detail, info, warn, error, fatal, off }; - - template - void log(Level, const char* message, Params&&...); - - /// Shorthand for `int(level) >= int(level_threshold.get())`. - bool would_log(Level level) const noexcept; - - class LevelThreshold; - - const LevelThreshold& level_threshold; - - virtual ~Logger() noexcept; - -protected: - Logger(const LevelThreshold&) noexcept; - - static void do_log(Logger&, Level, std::string message); - - virtual void do_log(Level, std::string message) = 0; - - static const char* get_level_prefix(Level) noexcept; - -private: - struct State; - - template - REALM_NOINLINE void do_log(Level, const char* message, Params&&...); - void log_impl(State&); - template - void log_impl(State&, Param&&, Params&&...); - template - static void subst(State&, Param&&); -}; - -template -std::basic_ostream& operator<<(std::basic_ostream&, Logger::Level); - -template -std::basic_istream& operator>>(std::basic_istream&, Logger::Level&); - -class Logger::LevelThreshold { -public: - virtual Level get() const noexcept = 0; -}; - - -/// A root logger that is not thread-safe and allows for the log level threshold -/// to be changed over time. The initial log level threshold is -/// Logger::Level::info. -class RootLogger : private Logger::LevelThreshold, public Logger { -public: - void set_level_threshold(Level) noexcept; - -protected: - RootLogger(); - -private: - Level m_level_threshold = Level::info; - Level get() const noexcept override final; -}; - - -/// A logger that writes to STDERR. This logger is not thread-safe. -/// -/// Since this class is a RootLogger, it contains modifiable a log level -/// threshold. -class StderrLogger : public RootLogger { -protected: - void do_log(Level, std::string) override final; -}; - - -/// A logger that writes to a stream. This logger is not thread-safe. -/// -/// Since this class is a RootLogger, it contains modifiable a log level -/// threshold. -class StreamLogger : public RootLogger { -public: - explicit StreamLogger(std::ostream&) noexcept; - -protected: - void do_log(Level, std::string) override final; - -private: - std::ostream& m_out; -}; - - -/// A logger that writes to a file. This logger is not thread-safe. -/// -/// Since this class is a RootLogger, it contains modifiable a log level -/// threshold. -class FileLogger : public StreamLogger { -public: - explicit FileLogger(std::string path); - explicit FileLogger(util::File); - -private: - util::File m_file; - util::File::Streambuf m_streambuf; - std::ostream m_out; -}; - - -/// A thread-safe logger. This logger ignores the level threshold of the base -/// logger. Instead, it introduces new a LevelThreshold object with a fixed -/// value to achieve thread safety. -class ThreadSafeLogger : private Logger::LevelThreshold, public Logger { -public: - explicit ThreadSafeLogger(Logger& base_logger, Level = Level::info); - -protected: - void do_log(Level, std::string) override final; - -private: - const Level m_level_threshold; // Immutable for thread safety - Logger& m_base_logger; - Mutex m_mutex; - Level get() const noexcept override final; -}; - - -/// A logger that adds a fixed prefix to each message. This logger inherits the -/// LevelThreshold object of the specified base logger. This logger is -/// thread-safe if, and only if the base logger is thread-safe. -class PrefixLogger : public Logger { -public: - PrefixLogger(std::string prefix, Logger& base_logger) noexcept; - -protected: - void do_log(Level, std::string) override final; - -private: - const std::string m_prefix; - Logger& m_base_logger; -}; - - -// Implementation - -struct Logger::State { - Logger::Level m_level; - std::string m_message; - std::string m_search; - int m_param_num = 1; - std::ostringstream m_formatter; - std::locale m_locale = std::locale::classic(); - State(Logger::Level level, const char* s) - : m_level(level) - , m_message(s) - , m_search(m_message) - { - m_formatter.imbue(m_locale); - } -}; - -template -inline void Logger::trace(const char* message, Params&&... params) -{ - log(Level::trace, message, std::forward(params)...); // Throws -} - -template -inline void Logger::debug(const char* message, Params&&... params) -{ - log(Level::debug, message, std::forward(params)...); // Throws -} - -template -inline void Logger::detail(const char* message, Params&&... params) -{ - log(Level::detail, message, std::forward(params)...); // Throws -} - -template -inline void Logger::info(const char* message, Params&&... params) -{ - log(Level::info, message, std::forward(params)...); // Throws -} - -template -inline void Logger::warn(const char* message, Params&&... params) -{ - log(Level::warn, message, std::forward(params)...); // Throws -} - -template -inline void Logger::error(const char* message, Params&&... params) -{ - log(Level::error, message, std::forward(params)...); // Throws -} - -template -inline void Logger::fatal(const char* message, Params&&... params) -{ - log(Level::fatal, message, std::forward(params)...); // Throws -} - -template -inline void Logger::log(Level level, const char* message, Params&&... params) -{ - if (would_log(level)) - do_log(level, message, std::forward(params)...); // Throws -} - -inline bool Logger::would_log(Level level) const noexcept -{ - return int(level) >= int(level_threshold.get()); -} - -inline Logger::~Logger() noexcept -{ -} - -inline Logger::Logger(const LevelThreshold& lt) noexcept - : level_threshold(lt) -{ -} - -inline void Logger::do_log(Logger& logger, Level level, std::string message) -{ - logger.do_log(level, std::move(message)); // Throws -} - -template -void Logger::do_log(Level level, const char* message, Params&&... params) -{ - State state(level, message); - log_impl(state, std::forward(params)...); // Throws -} - -inline void Logger::log_impl(State& state) -{ - do_log(state.m_level, std::move(state.m_message)); // Throws -} - -template -inline void Logger::log_impl(State& state, Param&& param, Params&&... params) -{ - subst(state, std::forward(param)); // Throws - log_impl(state, std::forward(params)...); // Throws -} - -template -void Logger::subst(State& state, Param&& param) -{ - state.m_formatter << "%" << state.m_param_num; - std::string key = state.m_formatter.str(); - state.m_formatter.str(std::string()); - std::string::size_type j = state.m_search.find(key); - if (j != std::string::npos) { - state.m_formatter << std::forward(param); - std::string str = state.m_formatter.str(); - state.m_formatter.str(std::string()); - state.m_message.replace(j, key.size(), str); - state.m_search.replace(j, key.size(), std::string(str.size(), '\0')); - } - ++state.m_param_num; -} - -template -std::basic_ostream& operator<<(std::basic_ostream& out, Logger::Level level) -{ - switch (level) { - case Logger::Level::all: - out << "all"; - return out; - case Logger::Level::trace: - out << "trace"; - return out; - case Logger::Level::debug: - out << "debug"; - return out; - case Logger::Level::detail: - out << "detail"; - return out; - case Logger::Level::info: - out << "info"; - return out; - case Logger::Level::warn: - out << "warn"; - return out; - case Logger::Level::error: - out << "error"; - return out; - case Logger::Level::fatal: - out << "fatal"; - return out; - case Logger::Level::off: - out << "off"; - return out; - } - REALM_ASSERT(false); - return out; -} - -template -std::basic_istream& operator>>(std::basic_istream& in, Logger::Level& level) -{ - std::basic_string str; - auto check = [&](const char* name) { - size_t n = strlen(name); - if (n != str.size()) - return false; - for (size_t i = 0; i < n; ++i) { - if (in.widen(name[i]) != str[i]) - return false; - } - return true; - }; - if (in >> str) { - if (check("all")) { - level = Logger::Level::all; - } - else if (check("trace")) { - level = Logger::Level::trace; - } - else if (check("debug")) { - level = Logger::Level::debug; - } - else if (check("detail")) { - level = Logger::Level::detail; - } - else if (check("info")) { - level = Logger::Level::info; - } - else if (check("warn")) { - level = Logger::Level::warn; - } - else if (check("error")) { - level = Logger::Level::error; - } - else if (check("fatal")) { - level = Logger::Level::fatal; - } - else if (check("off")) { - level = Logger::Level::off; - } - else { - in.setstate(std::ios_base::failbit); - } - } - return in; -} - -inline void RootLogger::set_level_threshold(Level new_level_threshold) noexcept -{ - m_level_threshold = new_level_threshold; -} - -inline RootLogger::RootLogger() - : Logger::LevelThreshold() - , Logger(static_cast(*this)) -{ -} - -inline Logger::Level RootLogger::get() const noexcept -{ - return m_level_threshold; -} - -inline void StderrLogger::do_log(Level level, std::string message) -{ - std::cerr << get_level_prefix(level) << message << '\n'; // Throws - std::cerr.flush(); // Throws -} - -inline StreamLogger::StreamLogger(std::ostream& out) noexcept - : m_out(out) -{ -} - -inline void StreamLogger::do_log(Level level, std::string message) -{ - m_out << get_level_prefix(level) << message << '\n'; // Throws - m_out.flush(); // Throws -} - -inline FileLogger::FileLogger(std::string path) - : StreamLogger(m_out) - , m_file(path, util::File::mode_Write) // Throws - , m_streambuf(&m_file) // Throws - , m_out(&m_streambuf) // Throws -{ -} - -inline FileLogger::FileLogger(util::File file) - : StreamLogger(m_out) - , m_file(std::move(file)) - , m_streambuf(&m_file) // Throws - , m_out(&m_streambuf) // Throws -{ -} - -inline ThreadSafeLogger::ThreadSafeLogger(Logger& base_logger, Level threshold) - : Logger::LevelThreshold() - , Logger(static_cast(*this)) - , m_level_threshold(threshold) - , m_base_logger(base_logger) -{ -} - -inline void ThreadSafeLogger::do_log(Level level, std::string message) -{ - LockGuard l(m_mutex); - Logger::do_log(m_base_logger, level, message); // Throws -} - -inline Logger::Level ThreadSafeLogger::get() const noexcept -{ - return m_level_threshold; -} - -inline PrefixLogger::PrefixLogger(std::string prefix, Logger& base_logger) noexcept - : Logger(base_logger.level_threshold) - , m_prefix(std::move(prefix)) - , m_base_logger(base_logger) -{ -} - -inline void PrefixLogger::do_log(Level level, std::string message) -{ - Logger::do_log(m_base_logger, level, m_prefix + message); // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_LOGGER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/memory_stream.hpp b/Lesson14/Pods/Realm/include/core/realm/util/memory_stream.hpp deleted file mode 100644 index 81a4852..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/memory_stream.hpp +++ /dev/null @@ -1,212 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_MEMORY_STREAM_HPP -#define REALM_UTIL_MEMORY_STREAM_HPP - -#include -#include -#include -#include - -namespace realm { -namespace util { - -class MemoryInputStreambuf : public std::streambuf { -public: - MemoryInputStreambuf(); - ~MemoryInputStreambuf() noexcept; - - /// Behavior is undefined if the size of the specified buffer exceeds - /// PTRDIFF_MAX. - void set_buffer(const char* begin, const char* end) noexcept; - -private: - const char* m_begin; - const char* m_end; - const char* m_curr; - - int_type underflow() override; - int_type uflow() override; - int_type pbackfail(int_type) override; - std::streamsize showmanyc() override; - pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) override; - pos_type seekpos(pos_type, std::ios_base::openmode) override; - - pos_type do_seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode); -}; - - -class MemoryOutputStreambuf : public std::streambuf { -public: - MemoryOutputStreambuf(); - ~MemoryOutputStreambuf() noexcept; - - /// Behavior is undefined if the size of the specified buffer exceeds - /// PTRDIFF_MAX. - void set_buffer(char* begin, char* end) noexcept; - - /// Returns the amount of data written to the buffer. - size_t size() const noexcept; -}; - - -class MemoryInputStream : public std::istream { -public: - MemoryInputStream(); - ~MemoryInputStream() noexcept; - - /// \{ Behavior is undefined if the size of the specified buffer exceeds - /// PTRDIFF_MAX. - void set_buffer(const char* begin, const char* end) noexcept; - template void set_buffer(const char (&buffer)[N]) noexcept; - void set_string(const std::string&) noexcept; - void set_c_string(const char* c_str) noexcept; - /// \} - -private: - MemoryInputStreambuf m_streambuf; -}; - - -class MemoryOutputStream : public std::ostream { -public: - MemoryOutputStream(); - ~MemoryOutputStream() noexcept; - - /// \{ Behavior is undefined if the size of the specified buffer exceeds - /// PTRDIFF_MAX. - void set_buffer(char* begin, char* end) noexcept; - template void set_buffer(char (&buffer)[N]) noexcept; - /// \} - - /// Returns the amount of data written to the underlying buffer. - size_t size() const noexcept; - -private: - MemoryOutputStreambuf m_streambuf; -}; - - -// Implementation - -inline MemoryInputStreambuf::MemoryInputStreambuf() - : m_begin(nullptr) - , m_end(nullptr) - , m_curr(nullptr) -{ -} - -inline MemoryInputStreambuf::~MemoryInputStreambuf() noexcept -{ -} - -inline void MemoryInputStreambuf::set_buffer(const char* b, const char* e) noexcept -{ - m_begin = b; - m_end = e; - m_curr = b; -} - - -inline MemoryOutputStreambuf::MemoryOutputStreambuf() -{ -} - -inline MemoryOutputStreambuf::~MemoryOutputStreambuf() noexcept -{ -} - -inline void MemoryOutputStreambuf::set_buffer(char* b, char* e) noexcept -{ - setp(b, e); -} - -inline size_t MemoryOutputStreambuf::size() const noexcept -{ - return pptr() - pbase(); -} - - -inline MemoryInputStream::MemoryInputStream() - : std::istream(&m_streambuf) -{ -} - -inline MemoryInputStream::~MemoryInputStream() noexcept -{ -} - -inline void MemoryInputStream::set_buffer(const char* b, const char* e) noexcept -{ - m_streambuf.set_buffer(b, e); - clear(); -} - -template inline void MemoryInputStream::set_buffer(const char (&buffer)[N]) noexcept -{ - const char* b = buffer; - const char* e = b + N; - set_buffer(b, e); -} - -inline void MemoryInputStream::set_string(const std::string& str) noexcept -{ - const char* b = str.data(); - const char* e = b + str.size(); - set_buffer(b, e); -} - -inline void MemoryInputStream::set_c_string(const char* c_str) noexcept -{ - const char* b = c_str; - const char* e = b + traits_type::length(c_str); - set_buffer(b, e); -} - - -inline MemoryOutputStream::MemoryOutputStream() - : std::ostream(&m_streambuf) -{ -} - -inline MemoryOutputStream::~MemoryOutputStream() noexcept -{ -} - -inline void MemoryOutputStream::set_buffer(char* b, char* e) noexcept -{ - m_streambuf.set_buffer(b, e); - clear(); -} - -template -inline void MemoryOutputStream::set_buffer(char (&buffer)[N]) noexcept -{ - set_buffer(buffer, buffer + N); -} - -inline size_t MemoryOutputStream::size() const noexcept -{ - return m_streambuf.size(); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_MEMORY_STREAM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/deque.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/deque.hpp deleted file mode 100644 index 41c1b71..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/deque.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_DEQUE_HPP -#define REALM_UTIL_METERED_DEQUE_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Vector with metered allocation -template > -using deque = std::deque; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_DEQUE_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/map.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/map.hpp deleted file mode 100644 index be03f9e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/map.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_MAP_HPP -#define REALM_UTIL_METERED_MAP_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Map with metered allocation. Additionally, the default Compare is changed to -/// `std::less<>` instead of `std::less`, which allows heterogenous lookup. -template , - class Alloc = MeteredSTLAllocator>> -using map = std::map; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_MAP_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/set.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/set.hpp deleted file mode 100644 index 95f1e73..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/set.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_SET_HPP -#define REALM_UTIL_METERED_SET_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Set with metered allocation. Additionally, the default Compare is changed to -/// `std::less<>` instead of `std::less`, which allows heterogenous lookup. -template , class Alloc = MeteredSTLAllocator> -using set = std::set; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_SET_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/string.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/string.hpp deleted file mode 100644 index b3a52db..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/string.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_STRING_HPP -#define REALM_UTIL_METERED_STRING_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// String with metered allocation -using string = std::basic_string, MeteredSTLAllocator>; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_STRING_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp deleted file mode 100644 index 8ead21a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_map.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_UNORDERED_MAP_HPP -#define REALM_UTIL_METERED_UNORDERED_MAP_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Unordered map with metered allocation -template , - class KeyEqual = std::equal_to, - class Alloc = MeteredSTLAllocator>> -using unordered_map = std::unordered_map; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_UNORDERED_MAP_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp deleted file mode 100644 index ad0dc5f..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/unordered_set.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_UNORDERED_SET_HPP -#define REALM_UTIL_METERED_UNORDERED_SET_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Unordered set with metered allocation -template , - class KeyEqual = std::equal_to, - class Alloc = MeteredSTLAllocator> -using unordered_set = std::unordered_set; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_UNORDERED_SET_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/metered/vector.hpp b/Lesson14/Pods/Realm/include/core/realm/util/metered/vector.hpp deleted file mode 100644 index cbbf177..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/metered/vector.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2018] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_METERED_VECTOR_HPP -#define REALM_UTIL_METERED_VECTOR_HPP - -#include -#include - -namespace realm { -namespace util { -namespace metered { -/// Vector with metered allocation -template > -using vector = std::vector; -} // namespace metered -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_METERED_VECTOR_HPP - diff --git a/Lesson14/Pods/Realm/include/core/realm/util/misc_errors.hpp b/Lesson14/Pods/Realm/include/core/realm/util/misc_errors.hpp deleted file mode 100644 index 9335ba9..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/misc_errors.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_MISC_ERRORS_HPP -#define REALM_UTIL_MISC_ERRORS_HPP - -#include - - -namespace realm { -namespace util { -namespace error { - -enum misc_errors { - unknown = 1, -}; - -std::error_code make_error_code(misc_errors); - -} // namespace error -} // namespace util -} // namespace realm - -namespace std { - -template <> -class is_error_code_enum { -public: - static const bool value = true; -}; - -} // namespace std - -#endif // REALM_UTIL_MISC_ERRORS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp b/Lesson14/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp deleted file mode 100644 index 6b70998..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/misc_ext_errors.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_MISC_EXT_ERRORS_HPP -#define REALM_UTIL_MISC_EXT_ERRORS_HPP - -#include - -namespace realm { -namespace util { - -/// FIXME: The intention is that this enum will be merged into, and subsumed by -/// util::MiscErrors in `` in the core library. -enum class MiscExtErrors { - /// End of input. - end_of_input = 1, - - /// Premature end of input. That is, end of input at an unexpected, or - /// illegal place in an input stream. - premature_end_of_input, - - /// Delimiter not found. - delim_not_found, - - /// Operation not supported - operation_not_supported, -}; - -class MiscExtErrorCategory : public std::error_category { -public: - const char* name() const noexcept override final; - std::string message(int) const override final; -}; - -/// The error category associated with MiscErrors. The name of this category is -/// `realm.util.misc_ext`. -extern MiscExtErrorCategory misc_ext_error_category; - -inline std::error_code make_error_code(MiscExtErrors err) -{ - return std::error_code(int(err), misc_ext_error_category); -} - -} // namespace util -} // namespace realm - -namespace std { - -template<> class is_error_code_enum { -public: - static const bool value = true; -}; - -} // namespace std - -#endif // REALM_UTIL_MISC_EXT_ERRORS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/miscellaneous.hpp b/Lesson14/Pods/Realm/include/core/realm/util/miscellaneous.hpp deleted file mode 100644 index c45e4f3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/miscellaneous.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_MISCELLANEOUS_HPP -#define REALM_UTIL_MISCELLANEOUS_HPP - -#include - -namespace realm { -namespace util { - -// FIXME: Replace this with std::add_const_t when we switch over to C++14 by -// default. -/// \brief Adds const qualifier, unless T already has the const qualifier -template -using add_const_t = typename std::add_const::type; - -// FIXME: Replace this with std::as_const when we switch over to C++17 by -// default. -/// \brief Forms an lvalue reference to const T -template -constexpr add_const_t& as_const(T& v) noexcept -{ - return v; -} - -/// \brief Disallows rvalue arguments -template -add_const_t& as_const(const T&&) = delete; - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_MISCELLANEOUS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/network.hpp b/Lesson14/Pods/Realm/include/core/realm/util/network.hpp deleted file mode 100644 index 6ff5b91..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/network.hpp +++ /dev/null @@ -1,3708 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_NETWORK_HPP -#define REALM_UTIL_NETWORK_HPP - -#include -#include -#include -#include -#include -#include - -#include - -#ifdef _WIN32 -# include -# include -# include -# include -# pragma comment(lib, "Ws2_32.lib") -#else -# include -# include -# include -#endif - -#include -#include -#include -#include -#include -#include -#include - -// Linux epoll -// -// Require Linux kernel version >= 2.6.27 such that we have epoll_create1(), -// `O_CLOEXEC`, and `EPOLLRDHUP`. -#if defined(__linux__) -# include -# if !defined(REALM_HAVE_EPOLL) -# if !defined(REALM_DISABLE_UTIL_NETWORK_EPOLL) -# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27) -# define REALM_HAVE_EPOLL 1 -# endif -# endif -# endif -#endif -#if !defined(REALM_HAVE_EPOLL) -# define REALM_HAVE_EPOLL 0 -#endif - -// FreeBSD Kqueue. -// -// Available on Mac OS X, FreeBSD, NetBSD, OpenBSD -#if (defined(__MACH__) && defined(__APPLE__)) || defined(__FreeBSD__) || \ - defined(__NetBSD__) || defined(__OpenBSD__) -# if !defined(REALM_HAVE_KQUEUE) -# if !defined(REALM_DISABLE_UTIL_NETWORK_KQUEUE) -# define REALM_HAVE_KQUEUE 1 -# endif -# endif -#endif -#if !defined(REALM_HAVE_KQUEUE) -# define REALM_HAVE_KQUEUE 0 -#endif - - - -// FIXME: Unfinished business around `Address::m_ip_v6_scope_id`. - - -namespace realm { -namespace util { - -/// \brief TCP/IP networking API. -/// -/// The design of this networking API is heavily inspired by the ASIO C++ -/// library (http://think-async.com). -/// -/// -/// ### Thread safety -/// -/// A *service context* is a set of objects consisting of an instance of -/// Service, and all the objects that are associated with that instance (\ref -/// Resolver, \ref Socket`, \ref Acceptor`, \ref DeadlineTimer, \ref Trigger, -/// and \ref ssl::Stream). -/// -/// In general, it is unsafe for two threads to call functions on the same -/// object, or on different objects in the same service context. This also -/// applies to destructors. Notable exceptions are the fully thread-safe -/// functions, such as Service::post(), Service::stop(), and Service::reset(). -/// -/// On the other hand, it is always safe for two threads to call functions on -/// objects belonging to different service contexts. -/// -/// One implication of these rules is that at most one thread must execute run() -/// at any given time, and if one thread is executing run(), then no other -/// thread is allowed to access objects in the same service context (with the -/// mentioned exceptions). -/// -/// Unless otherwise specified, free-standing objects, such as \ref -/// StreamProtocol, \ref Address, \ref Endpoint, and \ref Endpoint::List are -/// fully thread-safe as long as they are not mutated. If one thread is mutating -/// such an object, no other thread may access it. Note that these free-standing -/// objects are not associcated with an instance of Service, and are therefore -/// not part of a service context. -/// -/// -/// ### Comparison with ASIO -/// -/// There is a crucial difference between the two libraries in regards to the -/// guarantees that are provided about the cancelability of asynchronous -/// operations. The Realm networking library (this library) considers an -/// asynchronous operation to be complete precisely when the completion handler -/// starts to execute, and it guarantees that such an operation is cancelable up -/// until that point in time. In particular, if `cancel()` is called on a socket -/// or a deadline timer object before the completion handler starts to execute, -/// then that operation will be canceled, and will receive -/// `error::operation_aborted`. This guarantee is possible to provide (and free -/// of ambiguities) precisely because this library prohibits multiple threads -/// from executing the event loop concurrently, and because `cancel()` is -/// allowed to be called only from a completion handler (executed by the event -/// loop thread) or while no thread is executing the event loop. This guarantee -/// allows for safe destruction of sockets and deadline timers as long as the -/// completion handlers react appropriately to `error::operation_aborted`, in -/// particular, that they do not attempt to access the socket or deadline timer -/// object in such cases. -/// -/// ASIO, on the other hand, allows for an asynchronous operation to complete -/// and become **uncancellable** before the completion handler starts to -/// execute. For this reason, it is possible with ASIO to get the completion -/// handler of an asynchronous wait operation to start executing and receive an -/// error code other than "operation aborted" at a point in time where -/// `cancel()` has already been called on the deadline timer object, or even at -/// a point in timer where the deadline timer has been destroyed. This seems -/// like an inevitable consequence of the fact that ASIO allows for multiple -/// threads to execute the event loop concurrently. This generally forces ASIO -/// applications to invent ways of extending the lifetime of deadline timer and -/// socket objects until the completion handler starts executing. -/// -/// IMPORTANT: Even if ASIO is used in a way where at most one thread executes -/// the event loop, there is still no guarantee that an asynchronous operation -/// remains cancelable up until the point in time where the completion handler -/// starts to execute. -namespace network { - -std::string host_name(); - - -class StreamProtocol; -class Address; -class Endpoint; -class Service; -class Resolver; -class SocketBase; -class Socket; -class Acceptor; -class DeadlineTimer; -class Trigger; -class ReadAheadBuffer; -namespace ssl { -class Stream; -} // namespace ssl - - -/// \brief An IP protocol descriptor. -class StreamProtocol { -public: - static StreamProtocol ip_v4(); - static StreamProtocol ip_v6(); - - bool is_ip_v4() const; - bool is_ip_v6() const; - - int protocol() const; - int family() const; - - StreamProtocol(); - ~StreamProtocol() noexcept {} - -private: - int m_family; - int m_socktype; - int m_protocol; - - friend class Service; - friend class SocketBase; -}; - - -/// \brief An IP address (IPv4 or IPv6). -class Address { -public: - bool is_ip_v4() const; - bool is_ip_v6() const; - - template - friend std::basic_ostream& operator<<(std::basic_ostream&, const Address&); - - Address(); - ~Address() noexcept {} - -private: - using ip_v4_type = in_addr; - using ip_v6_type = in6_addr; - union union_type { - ip_v4_type m_ip_v4; - ip_v6_type m_ip_v6; - }; - union_type m_union; - std::uint_least32_t m_ip_v6_scope_id = 0; - bool m_is_ip_v6 = false; - - friend Address make_address(const char*, std::error_code&) noexcept; - friend class Endpoint; -}; - -Address make_address(const char* c_str); -Address make_address(const char* c_str, std::error_code& ec) noexcept; -Address make_address(const std::string&); -Address make_address(const std::string&, std::error_code& ec) noexcept; - - -/// \brief An IP endpoint. -/// -/// An IP endpoint is a triplet (`protocol`, `address`, `port`). -class Endpoint { -public: - using port_type = std::uint_fast16_t; - class List; - - StreamProtocol protocol() const; - Address address() const; - port_type port() const; - - Endpoint(); - Endpoint(const StreamProtocol&, port_type); - Endpoint(const Address&, port_type); - ~Endpoint() noexcept {} - - using data_type = sockaddr; - data_type* data(); - const data_type* data() const; - -private: - StreamProtocol m_protocol; - - using sockaddr_base_type = sockaddr; - using sockaddr_ip_v4_type = sockaddr_in; - using sockaddr_ip_v6_type = sockaddr_in6; - union sockaddr_union_type { - sockaddr_base_type m_base; - sockaddr_ip_v4_type m_ip_v4; - sockaddr_ip_v6_type m_ip_v6; - }; - sockaddr_union_type m_sockaddr_union; - - friend class Service; - friend class Resolver; - friend class SocketBase; - friend class Socket; -}; - - -/// \brief A list of IP endpoints. -class Endpoint::List { -public: - using iterator = const Endpoint*; - - iterator begin() const noexcept; - iterator end() const noexcept; - std::size_t size() const noexcept; - bool empty() const noexcept; - - List() noexcept = default; - List(List&&) noexcept = default; - ~List() noexcept = default; - - List& operator=(List&&) noexcept = default; - -private: - Buffer m_endpoints; - - friend class Service; -}; - - -/// \brief TCP/IP networking service. -class Service { -public: - Service(); - ~Service() noexcept; - - /// \brief Execute the event loop. - /// - /// Execute completion handlers of completed asynchronous operations, or - /// wait for more completion handlers to become ready for - /// execution. Handlers submitted via post() are considered immeditely - /// ready. If there are no completion handlers ready for execution, and - /// there are no asynchronous operations in progress, run() returns. - /// - /// All completion handlers, including handlers submitted via post() will be - /// executed from run(), that is, by the thread that executes run(). If no - /// thread executes run(), then the completion handlers will not be - /// executed. - /// - /// Exceptions thrown by completion handlers will always propagate back - /// through run(). - /// - /// Syncronous operations (e.g., Socket::connect()) execute independently of - /// the event loop, and do not require that any thread calls run(). - void run(); - - /// @{ \brief Stop event loop execution. - /// - /// stop() puts the event loop into the stopped mode. If a thread is - /// currently executing run(), it will be made to return in a timely - /// fashion, that is, without further blocking. If a thread is currently - /// blocked in run(), it will be unblocked. Handlers that can be executed - /// immediately, may, or may not be executed before run() returns, but new - /// handlers submitted by these, will not be executed before run() - /// returns. Also, if a handler is submitted by a call to post, and that - /// call happens after stop() returns, then that handler is guaranteed to - /// not be executed before run() returns (assuming that reset() is not called - /// before run() returns). - /// - /// The event loop will remain in the stopped mode until reset() is - /// called. If reset() is called before run() returns, it may, or may not - /// cause run() to resume normal operation without returning. - /// - /// Both stop() and reset() are thread-safe, that is, they may be called by - /// any thread. Also, both of these function may be called from completion - /// handlers (including posted handlers). - void stop() noexcept; - void reset() noexcept; - /// @} - - /// \brief Submit a handler to be executed by the event loop thread. - /// - /// Register the sepcified completion handler for immediate asynchronous - /// execution. The specified handler will be executed by an expression on - /// the form `handler()`. If the the handler object is movable, it will - /// never be copied. Otherwise, it will be copied as necessary. - /// - /// This function is thread-safe, that is, it may be called by any - /// thread. It may also be called from other completion handlers. - /// - /// The handler will never be called as part of the execution of post(). It - /// will always be called by a thread that is executing run(). If no thread - /// is currently executing run(), the handler will not be executed until a - /// thread starts executing run(). If post() is called while another thread - /// is executing run(), the handler may be called before post() returns. If - /// post() is called from another completion handler, the submitted handler - /// is guaranteed to not be called during the execution of post(). - /// - /// Completion handlers added through post() will be executed in the order - /// that they are added. More precisely, if post() is called twice to add - /// two handlers, A and B, and the execution of post(A) ends before the - /// beginning of the execution of post(B), then A is guaranteed to execute - /// before B. - template void post(H handler); - - /// Argument `saturation` is the fraction of time that is not spent - /// sleeping. Argument `inefficiency` is the fraction of time not spent - /// sleeping, and not spent executing completion handlers. Both values are - /// guaranteed to always be in the range 0 to 1 (both inclusive). The value - /// passed as `inefficiency` is guaranteed to always be less than, or equal - /// to the value passed as `saturation`. - using EventLoopMetricsHandler = void(double saturation, double inefficiency); - - /// \brief Report event loop metrics via the specified handler. - /// - /// The handler will be called approximately every 30 seconds. - /// - /// report_event_loop_metrics() must be called prior to any invocation of - /// run(). report_event_loop_metrics() is not thread-safe. - /// - /// This feature is only available if - /// `REALM_UTIL_NETWORK_EVENT_LOOP_METRICS` was defined during - /// compilation. When the feature is not available, the specified handler - /// will never be called. - void report_event_loop_metrics(std::function); - -private: - enum class Want { nothing = 0, read, write }; - - template class OperQueue; - class Descriptor; - class AsyncOper; - class ResolveOperBase; - class WaitOperBase; - class TriggerExecOperBase; - class PostOperBase; - template class PostOper; - class IoOper; - class UnusedOper; // Allocated, but currently unused memory - - template class BasicStreamOps; - - struct OwnersOperDeleter { - void operator()(AsyncOper*) const noexcept; - }; - struct LendersOperDeleter { - void operator()(AsyncOper*) const noexcept; - }; - using OwnersOperPtr = std::unique_ptr; - using LendersOperPtr = std::unique_ptr; - using LendersResolveOperPtr = std::unique_ptr; - using LendersWaitOperPtr = std::unique_ptr; - using LendersIoOperPtr = std::unique_ptr; - - class IoReactor; - class Impl; - const std::unique_ptr m_impl; - - template - static std::unique_ptr alloc(OwnersOperPtr&, Args&&...); - - using PostOperConstr = PostOperBase*(void* addr, std::size_t size, Impl&, void* cookie); - void do_post(PostOperConstr, std::size_t size, void* cookie); - template - static PostOperBase* post_oper_constr(void* addr, std::size_t size, Impl&, void* cookie); - static void recycle_post_oper(Impl&, PostOperBase*) noexcept; - static void trigger_exec(Impl&, TriggerExecOperBase&) noexcept; - static void reset_trigger_exec(Impl&, TriggerExecOperBase&) noexcept; - - using clock = std::chrono::steady_clock; - - friend class Resolver; - friend class SocketBase; - friend class Socket; - friend class Acceptor; - friend class DeadlineTimer; - friend class Trigger; - friend class ReadAheadBuffer; - friend class ssl::Stream; -}; - - -template class Service::OperQueue { -public: - using LendersOperPtr = std::unique_ptr; - bool empty() const noexcept; - void push_back(LendersOperPtr) noexcept; - template void push_back(OperQueue&) noexcept; - LendersOperPtr pop_front() noexcept; - void clear() noexcept; - OperQueue() noexcept = default; - OperQueue(OperQueue&&) noexcept; - ~OperQueue() noexcept; -private: - Oper* m_back = nullptr; - template friend class OperQueue; -}; - - -class Service::Descriptor { -public: -#ifdef _WIN32 - using native_handle_type = SOCKET; -#else - using native_handle_type = int; -#endif - - Impl& service_impl; - - Descriptor(Impl& service) noexcept; - ~Descriptor() noexcept; - - /// \param in_blocking_mode Must be true if, and only if the passed file - /// descriptor refers to a file description in which the file status flag - /// O_NONBLOCK is not set. - /// - /// The passed file descriptor must have the file descriptor flag FD_CLOEXEC - /// set. - void assign(native_handle_type fd, bool in_blocking_mode) noexcept; - void close() noexcept; - native_handle_type release() noexcept; - - bool is_open() const noexcept; - - native_handle_type native_handle() const noexcept; - bool in_blocking_mode() const noexcept; - - void accept(Descriptor&, StreamProtocol, Endpoint*, std::error_code&) noexcept; - std::size_t read_some(char* buffer, std::size_t size, std::error_code&) noexcept; - std::size_t write_some(const char* data, std::size_t size, std::error_code&) noexcept; - - /// \tparam Oper An operation type inherited from IoOper with an initate() - /// function that initiates the operation and figures out whether it needs - /// to read from, or write to the underlying descriptor to - /// proceed. `initiate()` must return Want::read if the operation needs to - /// read, or Want::write if the operation needs to write. If the operation - /// completes immediately (e.g. due to a failure during initialization), - /// `initiate()` must return Want::nothing. - template - void initiate_oper(std::unique_ptr, Args&&...); - - void ensure_blocking_mode(); - void ensure_nonblocking_mode(); - -private: - native_handle_type m_fd = -1; - bool m_in_blocking_mode; // Not in nonblocking mode - -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - bool m_read_ready; - bool m_write_ready; - bool m_imminent_end_of_input; // Kernel has seen the end of input - bool m_is_registered; - OperQueue m_suspended_read_ops, m_suspended_write_ops; - - void deregister_for_async() noexcept; -#endif - - bool assume_read_would_block() const noexcept; - bool assume_write_would_block() const noexcept; - - void set_read_ready(bool) noexcept; - void set_write_ready(bool) noexcept; - - void set_nonblock_flag(bool value); - void add_initiated_oper(LendersIoOperPtr, Want); - - void do_close() noexcept; - native_handle_type do_release() noexcept; - - friend class IoReactor; -}; - - -class Resolver { -public: - class Query; - - Resolver(Service&); - ~Resolver() noexcept; - - /// Thread-safe. - Service& get_service() noexcept; - - /// @{ \brief Resolve the specified query to one or more endpoints. - Endpoint::List resolve(const Query&); - Endpoint::List resolve(const Query&, std::error_code&); - /// @} - - /// \brief Perform an asynchronous resolve operation. - /// - /// Initiate an asynchronous resolve operation. The completion handler will - /// be called when the operation completes. The operation completes when it - /// succeeds, or an error occurs. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_resolve(), even when - /// async_resolve() is executed by the event loop thread. The completion - /// handler is guaranteed to be called eventually, as long as there is time - /// enough for the operation to complete or fail, and a thread is executing - /// Service::run() for long enough. - /// - /// The operation can be canceled by calling cancel(), and will be - /// automatically canceled if the resolver object is destroyed. If the - /// operation is canceled, it will fail with `error::operation_aborted`. The - /// operation remains cancelable up until the point in time where the - /// completion handler starts to execute. This means that if cancel() is - /// called before the completion handler starts to execute, then the - /// completion handler is guaranteed to have `error::operation_aborted` - /// passed to it. This is true regardless of whether cancel() is called - /// explicitly or implicitly, such as when the resolver is destroyed. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec, endpoints)` where `ec` is the error code and `endpoints` is - /// an object of type `Endpoint::List`. If the the handler object is - /// movable, it will never be copied. Otherwise, it will be copied as - /// necessary. - /// - /// It is an error to start a new resolve operation (synchronous or - /// asynchronous) while an asynchronous resolve operation is in progress via - /// the same resolver object. An asynchronous resolve operation is - /// considered complete as soon as the completion handler starts to - /// execute. This means that a new resolve operation can be started from the - /// completion handler. - template void async_resolve(Query, H handler); - - /// \brief Cancel all asynchronous operations. - /// - /// Cause all incomplete asynchronous operations, that are associated with - /// this resolver (at most one), to fail with `error::operation_aborted`. An - /// asynchronous operation is complete precisely when its completion handler - /// starts executing. - /// - /// Completion handlers of canceled operations will become immediately ready - /// to execute, but will never be executed directly as part of the execution - /// of cancel(). - /// - /// Cancellation happens automatically when the resolver object is destroyed. - void cancel() noexcept; - -private: - template class ResolveOper; - - Service::Impl& m_service_impl; - - Service::OwnersOperPtr m_resolve_oper; - - void initiate_oper(Service::LendersResolveOperPtr); -}; - - -class Resolver::Query { -public: - enum { - /// Locally bound socket endpoint (server side) - passive = AI_PASSIVE, - - /// Ignore families without a configured non-loopback address - address_configured = AI_ADDRCONFIG - }; - - Query(std::string service_port, int init_flags = passive|address_configured); - Query(const StreamProtocol&, std::string service_port, - int init_flags = passive|address_configured); - Query(std::string host_name, std::string service_port, - int init_flags = address_configured); - Query(const StreamProtocol&, std::string host_name, std::string service_port, - int init_flags = address_configured); - - ~Query() noexcept; - - int flags() const; - StreamProtocol protocol() const; - std::string host() const; - std::string service() const; - -private: - int m_flags; - StreamProtocol m_protocol; - std::string m_host; // hostname - std::string m_service; // port - - friend class Service; -}; - - -class SocketBase { -public: - using native_handle_type = Service::Descriptor::native_handle_type; - - ~SocketBase() noexcept; - - /// Thread-safe. - Service& get_service() noexcept; - - bool is_open() const noexcept; - native_handle_type native_handle() const noexcept; - - /// @{ \brief Open the socket for use with the specified protocol. - /// - /// It is an error to call open() on a socket that is already open. - void open(const StreamProtocol&); - std::error_code open(const StreamProtocol&, std::error_code&); - /// @} - - /// \brief Close this socket. - /// - /// If the socket is open, it will be closed. If it is already closed (or - /// never opened), this function does nothing (idempotency). - /// - /// A socket is automatically closed when destroyed. - /// - /// When the socket is closed, any incomplete asynchronous operation will be - /// canceled (as if cancel() was called). - void close() noexcept; - - /// \brief Cancel all asynchronous operations. - /// - /// Cause all incomplete asynchronous operations, that are associated with - /// this socket, to fail with `error::operation_aborted`. An asynchronous - /// operation is complete precisely when its completion handler starts - /// executing. - /// - /// Completion handlers of canceled operations will become immediately ready - /// to execute, but will never be executed directly as part of the execution - /// of cancel(). - void cancel() noexcept; - - template - void get_option(O& opt) const; - - template - std::error_code get_option(O& opt, std::error_code&) const; - - template - void set_option(const O& opt); - - template - std::error_code set_option(const O& opt, std::error_code&); - - void bind(const Endpoint&); - std::error_code bind(const Endpoint&, std::error_code&); - - Endpoint local_endpoint() const; - Endpoint local_endpoint(std::error_code&) const; - - /// Release the ownership of this socket object over the native handle and - /// return the native handle to the caller. The caller assumes ownership - /// over the returned handle. The socket is left in a closed - /// state. Incomplete asynchronous operations will be canceled as if close() - /// had been called. - /// - /// If called on a closed socket, this function is a no-op, and returns the - /// same value as would be returned by native_handle() - native_handle_type release_native_handle() noexcept; - -private: - enum opt_enum { - opt_ReuseAddr, ///< `SOL_SOCKET`, `SO_REUSEADDR` - opt_Linger, ///< `SOL_SOCKET`, `SO_LINGER` - opt_NoDelay, ///< `IPPROTO_TCP`, `TCP_NODELAY` (disable the Nagle algorithm) - }; - - template class Option; - -public: - using reuse_address = Option; - using no_delay = Option; - - // linger struct defined by POSIX sys/socket.h. - struct linger_opt; - using linger = Option; - -protected: - Service::Descriptor m_desc; - -private: - StreamProtocol m_protocol; - -protected: - Service::OwnersOperPtr m_read_oper; // Read or accept - Service::OwnersOperPtr m_write_oper; // Write or connect - - SocketBase(Service&); - - const StreamProtocol& get_protocol() const noexcept; - std::error_code do_assign(const StreamProtocol&, native_handle_type, std::error_code&); - void do_close() noexcept; - - void get_option(opt_enum, void* value_data, std::size_t& value_size, std::error_code&) const; - void set_option(opt_enum, const void* value_data, std::size_t value_size, std::error_code&); - void map_option(opt_enum, int& level, int& option_name) const; - - friend class Acceptor; -}; - - -template class SocketBase::Option { -public: - Option(T value = T()); - T value() const; - -private: - T m_value; - - void get(const SocketBase&, std::error_code&); - void set(SocketBase&, std::error_code&) const; - - friend class SocketBase; -}; - -struct SocketBase::linger_opt { - linger_opt(bool enable, int timeout_seconds = 0) - { - m_linger.l_onoff = enable ? 1 : 0; - m_linger.l_linger = timeout_seconds; - } - - ::linger m_linger; - - operator ::linger() const { return m_linger; } - - bool enabled() const { return m_linger.l_onoff != 0; } - int timeout() const { return m_linger.l_linger; } -}; - - -/// Switching between synchronous and asynchronous operations is allowed, but -/// only in a nonoverlapping fashion. That is, a synchronous operation is not -/// allowed to run concurrently with an asynchronous one on the same -/// socket. Note that an asynchronous operation is considered to be running -/// until its completion handler starts executing. -class Socket : public SocketBase { -public: - Socket(Service&); - - /// \brief Create a socket with an already-connected native socket handle. - /// - /// This constructor is shorthand for creating the socket with the - /// one-argument constructor, and then calling the two-argument assign() - /// with the specified protocol and native handle. - Socket(Service&, const StreamProtocol&, native_handle_type); - - ~Socket() noexcept; - - void connect(const Endpoint&); - std::error_code connect(const Endpoint&, std::error_code&); - - /// @{ \brief Perform a synchronous read operation. - /// - /// read() will not return until the specified buffer is full, or an error - /// occurs. Reaching the end of input before the buffer is filled, is - /// considered an error, and will cause the operation to fail with - /// MiscExtErrors::end_of_input. - /// - /// read_until() will not return until the specified buffer contains the - /// specified delimiter, or an error occurs. If the buffer is filled before - /// the delimiter is found, the operation fails with - /// MiscExtErrors::delim_not_found. Otherwise, if the end of input is - /// reached before the delimiter is found, the operation fails with - /// MiscExtErrors::end_of_input. If the operation succeeds, the last byte - /// placed in the buffer is the delimiter. - /// - /// The versions that take a ReadAheadBuffer argument will read through that - /// buffer. This allows for fewer larger reads on the underlying - /// socket. Since unconsumed data may be left in the read-ahead buffer after - /// a read operation returns, it is important that the same read-ahead - /// buffer is passed to the next read operation. - /// - /// The versions of read() and read_until() that do not take an - /// `std::error_code&` argument will throw std::system_error on failure. - /// - /// The versions that do take an `std::error_code&` argument will set \a ec - /// to `std::error_code()` on success, and to something else on failure. On - /// failure they will return the number of bytes placed in the specified - /// buffer before the error occured. - /// - /// \return The number of bytes places in the specified buffer upon return. - std::size_t read(char* buffer, std::size_t size); - std::size_t read(char* buffer, std::size_t size, std::error_code& ec); - std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&); - std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&, std::error_code& ec); - std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&); - std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&, - std::error_code& ec); - /// @} - - /// @{ \brief Perform a synchronous write operation. - /// - /// write() will not return until all the specified bytes have been written - /// to the socket, or an error occurs. - /// - /// The versions of write() that does not take an `std::error_code&` - /// argument will throw std::system_error on failure. When it succeeds, it - /// always returns \a size. - /// - /// The versions that does take an `std::error_code&` argument will set \a - /// ec to `std::error_code()` on success, and to something else on - /// failure. On success it returns \a size. On faulure it returns the number - /// of bytes written before the failure occured. - std::size_t write(const char* data, std::size_t size); - std::size_t write(const char* data, std::size_t size, std::error_code& ec); - /// @} - - /// @{ \brief Read at least one byte from this socket. - /// - /// If \a size is zero, both versions of read_some() will return zero - /// without blocking. Read errors may or may not be detected in this case. - /// - /// Otherwise, if \a size is greater than zero, and at least one byte is - /// immediately available, that is, without blocking, then both versions - /// will read at least one byte (but generally as many immediately available - /// bytes as will fit into the specified buffer), and return without - /// blocking. - /// - /// Otherwise, both versions will block the calling thread until at least one - /// byte becomes available, or an error occurs. - /// - /// In this context, it counts as an error, if the end of input is reached - /// before at least one byte becomes available (see - /// MiscExtErrors::end_of_input). - /// - /// If no error occurs, both versions will return the number of bytes placed - /// in the specified buffer, which is generally as many as are immediately - /// available at the time when the first byte becomes available, although - /// never more than \a size. - /// - /// If no error occurs, the three-argument version will set \a ec to - /// indicate success. - /// - /// If an error occurs, the two-argument version will throw - /// `std::system_error`, while the three-argument version will set \a ec to - /// indicate the error, and return zero. - /// - /// As long as \a size is greater than zero, the two argument version will - /// always return a value that is greater than zero, while the three - /// argument version will return a value greater than zero when, and only - /// when \a ec is set to indicate success (no error, and no end of input). - std::size_t read_some(char* buffer, std::size_t size); - std::size_t read_some(char* buffer, std::size_t size, std::error_code& ec); - /// @} - - /// @{ \brief Write at least one byte to this socket. - /// - /// If \a size is zero, both versions of write_some() will return zero - /// without blocking. Write errors may or may not be detected in this case. - /// - /// Otherwise, if \a size is greater than zero, and at least one byte can be - /// written immediately, that is, without blocking, then both versions will - /// write at least one byte (but generally as many as can be written - /// immediately), and return without blocking. - /// - /// Otherwise, both versions will block the calling thread until at least one - /// byte can be written, or an error occurs. - /// - /// If no error occurs, both versions will return the number of bytes - /// written, which is generally as many as can be written immediately at the - /// time when the first byte can be written. - /// - /// If no error occurs, the three-argument version will set \a ec to - /// indicate success. - /// - /// If an error occurs, the two-argument version will throw - /// `std::system_error`, while the three-argument version will set \a ec to - /// indicate the error, and return zero. - /// - /// As long as \a size is greater than zero, the two argument version will - /// always return a value that is greater than zero, while the three - /// argument version will return a value greater than zero when, and only - /// when \a ec is set to indicate success. - std::size_t write_some(const char* data, std::size_t size); - std::size_t write_some(const char* data, std::size_t size, std::error_code&); - /// @} - - /// \brief Perform an asynchronous connect operation. - /// - /// Initiate an asynchronous connect operation. The completion handler is - /// called when the operation completes. The operation completes when the - /// connection is established, or an error occurs. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_connect(), even when - /// async_connect() is executed by the event loop thread. The completion - /// handler is guaranteed to be called eventually, as long as there is time - /// enough for the operation to complete or fail, and a thread is executing - /// Service::run() for long enough. - /// - /// The operation can be canceled by calling cancel(), and will be - /// automatically canceled if the socket is closed. If the operation is - /// canceled, it will fail with `error::operation_aborted`. The operation - /// remains cancelable up until the point in time where the completion - /// handler starts to execute. This means that if cancel() is called before - /// the completion handler starts to execute, then the completion handler is - /// guaranteed to have `error::operation_aborted` passed to it. This is true - /// regardless of whether cancel() is called explicitly or implicitly, such - /// as when the socket is destroyed. - /// - /// If the socket is not already open, it will be opened as part of the - /// connect operation as if by calling `open(ep.protocol())`. If the opening - /// operation succeeds, but the connect operation fails, the socket will be - /// left in the opened state. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec)` where `ec` is the error code. If the the handler object is - /// movable, it will never be copied. Otherwise, it will be copied as - /// necessary. - /// - /// It is an error to start a new connect operation (synchronous or - /// asynchronous) while an asynchronous connect operation is in progress. An - /// asynchronous connect operation is considered complete as soon as the - /// completion handler starts to execute. - /// - /// \param ep The remote endpoint of the connection to be established. - template void async_connect(const Endpoint& ep, H handler); - - /// @{ \brief Perform an asynchronous read operation. - /// - /// Initiate an asynchronous buffered read operation on the associated - /// socket. The completion handler will be called when the operation - /// completes, or an error occurs. - /// - /// async_read() will continue reading until the specified buffer is full, - /// or an error occurs. If the end of input is reached before the buffer is - /// filled, the operation fails with MiscExtErrors::end_of_input. - /// - /// async_read_until() will continue reading until the specified buffer - /// contains the specified delimiter, or an error occurs. If the buffer is - /// filled before a delimiter is found, the operation fails with - /// MiscExtErrors::delim_not_found. Otherwise, if the end of input is - /// reached before a delimiter is found, the operation fails with - /// MiscExtErrors::end_of_input. Otherwise, if the operation succeeds, the - /// last byte placed in the buffer is the delimiter. - /// - /// The versions that take a ReadAheadBuffer argument will read through that - /// buffer. This allows for fewer larger reads on the underlying - /// socket. Since unconsumed data may be left in the read-ahead buffer after - /// a read operation completes, it is important that the same read-ahead - /// buffer is passed to the next read operation. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_read() or - /// async_read_until(), even when async_read() or async_read_until() is - /// executed by the event loop thread. The completion handler is guaranteed - /// to be called eventually, as long as there is time enough for the - /// operation to complete or fail, and a thread is executing Service::run() - /// for long enough. - /// - /// The operation can be canceled by calling cancel() on the associated - /// socket, and will be automatically canceled if the associated socket is - /// closed. If the operation is canceled, it will fail with - /// `error::operation_aborted`. The operation remains cancelable up until - /// the point in time where the completion handler starts to execute. This - /// means that if cancel() is called before the completion handler starts to - /// execute, then the completion handler is guaranteed to have - /// `error::operation_aborted` passed to it. This is true regardless of - /// whether cancel() is called explicitly or implicitly, such as when the - /// socket is destroyed. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec, n)` where `ec` is the error code, and `n` is the number of - /// bytes placed in the buffer (of type `std::size_t`). `n` is guaranteed to - /// be less than, or equal to \a size. If the the handler object is movable, - /// it will never be copied. Otherwise, it will be copied as necessary. - /// - /// It is an error to start a read operation before the associated socket is - /// connected. - /// - /// It is an error to start a new read operation (synchronous or - /// asynchronous) while an asynchronous read operation is in progress. An - /// asynchronous read operation is considered complete as soon as the - /// completion handler starts executing. This means that a new read - /// operation can be started from the completion handler of another - /// asynchronous buffered read operation. - template void async_read(char* buffer, std::size_t size, H handler); - template void async_read(char* buffer, std::size_t size, ReadAheadBuffer&, H handler); - template void async_read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer&, H handler); - /// @} - - /// \brief Perform an asynchronous write operation. - /// - /// Initiate an asynchronous write operation. The completion handler is - /// called when the operation completes. The operation completes when all - /// the specified bytes have been written to the socket, or an error occurs. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_write(), even when - /// async_write() is executed by the event loop thread. The completion - /// handler is guaranteed to be called eventually, as long as there is time - /// enough for the operation to complete or fail, and a thread is executing - /// Service::run() for long enough. - /// - /// The operation can be canceled by calling cancel(), and will be - /// automatically canceled if the socket is closed. If the operation is - /// canceled, it will fail with `error::operation_aborted`. The operation - /// remains cancelable up until the point in time where the completion - /// handler starts to execute. This means that if cancel() is called before - /// the completion handler starts to execute, then the completion handler is - /// guaranteed to have `error::operation_aborted` passed to it. This is true - /// regardless of whether cancel() is called explicitly or implicitly, such - /// as when the socket is destroyed. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec, n)` where `ec` is the error code, and `n` is the number of - /// bytes written (of type `std::size_t`). If the the handler object is - /// movable, it will never be copied. Otherwise, it will be copied as - /// necessary. - /// - /// It is an error to start an asynchronous write operation before the - /// socket is connected. - /// - /// It is an error to start a new write operation (synchronous or - /// asynchronous) while an asynchronous write operation is in progress. An - /// asynchronous write operation is considered complete as soon as the - /// completion handler starts to execute. This means that a new write - /// operation can be started from the completion handler of another - /// asynchronous write operation. - template void async_write(const char* data, std::size_t size, H handler); - - template void async_read_some(char* buffer, std::size_t size, H handler); - template void async_write_some(const char* data, std::size_t size, H handler); - - enum shutdown_type { -#ifdef _WIN32 - /// Shutdown the receiving side of the socket. - shutdown_receive = SD_RECEIVE, - - /// Shutdown the sending side of the socket. - shutdown_send = SD_SEND, - - /// Shutdown both sending and receiving side of the socket. - shutdown_both = SD_BOTH -#else - shutdown_receive = SHUT_RD, - shutdown_send = SHUT_WR, - shutdown_both = SHUT_RDWR -#endif - }; - - /// @{ \brief Shut down the connected sockets sending and/or receiving - /// side. - /// - /// It is an error to call this function when the socket is not both open - /// and connected. - void shutdown(shutdown_type); - std::error_code shutdown(shutdown_type, std::error_code&); - /// @} - - /// @{ \brief Initialize socket with an already-connected native socket - /// handle. - /// - /// The specified native handle must refer to a socket that is already fully - /// open and connected. - /// - /// If the assignment operation succeeds, this socket object has taken - /// ownership of the specified native handle, and the handle will be closed - /// when the socket object is destroyed, (or when close() is called). If the - /// operation fails, the caller still owns the specified native handle. - /// - /// It is an error to call connect() or async_connect() on a socket object - /// that is initialized this way (unless it is first closed). - /// - /// It is an error to call this function on a socket object that is already - /// open. - void assign(const StreamProtocol&, native_handle_type); - std::error_code assign(const StreamProtocol&, native_handle_type, std::error_code&); - /// @} - - /// Returns a reference to this socket, as this socket is the lowest layer - /// of a stream. - Socket& lowest_layer() noexcept; - -private: - using Want = Service::Want; - using StreamOps = Service::BasicStreamOps; - - class ConnectOperBase; - template class ConnectOper; - - using LendersConnectOperPtr = std::unique_ptr; - - // `ec` untouched on success, but no immediate completion - bool initiate_async_connect(const Endpoint&, std::error_code& ec); - // `ec` untouched on success - std::error_code finalize_async_connect(std::error_code& ec) noexcept; - - // See Service::BasicStreamOps for details on these these 6 functions. - void do_init_read_async(std::error_code&, Want&) noexcept; - void do_init_write_async(std::error_code&, Want&) noexcept; - std::size_t do_read_some_sync(char* buffer, std::size_t size, - std::error_code&) noexcept; - std::size_t do_write_some_sync(const char* data, std::size_t size, - std::error_code&) noexcept; - std::size_t do_read_some_async(char* buffer, std::size_t size, - std::error_code&, Want&) noexcept; - std::size_t do_write_some_async(const char* data, std::size_t size, - std::error_code&, Want&) noexcept; - - friend class Service::BasicStreamOps; - friend class Service::BasicStreamOps; - friend class ReadAheadBuffer; - friend class ssl::Stream; -}; - - -/// Switching between synchronous and asynchronous operations is allowed, but -/// only in a nonoverlapping fashion. That is, a synchronous operation is not -/// allowed to run concurrently with an asynchronous one on the same -/// acceptor. Note that an asynchronous operation is considered to be running -/// until its completion handler starts executing. -class Acceptor : public SocketBase { -public: - Acceptor(Service&); - ~Acceptor() noexcept; - - static constexpr int max_connections = SOMAXCONN; - - void listen(int backlog = max_connections); - std::error_code listen(int backlog, std::error_code&); - - void accept(Socket&); - void accept(Socket&, Endpoint&); - std::error_code accept(Socket&, std::error_code&); - std::error_code accept(Socket&, Endpoint&, std::error_code&); - - /// @{ \brief Perform an asynchronous accept operation. - /// - /// Initiate an asynchronous accept operation. The completion handler will - /// be called when the operation completes. The operation completes when the - /// connection is accepted, or an error occurs. If the operation succeeds, - /// the specified local socket will have become connected to a remote - /// socket. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_accept(), even when - /// async_accept() is executed by the event loop thread. The completion - /// handler is guaranteed to be called eventually, as long as there is time - /// enough for the operation to complete or fail, and a thread is executing - /// Service::run() for long enough. - /// - /// The operation can be canceled by calling cancel(), and will be - /// automatically canceled if the acceptor is closed. If the operation is - /// canceled, it will fail with `error::operation_aborted`. The operation - /// remains cancelable up until the point in time where the completion - /// handler starts to execute. This means that if cancel() is called before - /// the completion handler starts to execute, then the completion handler is - /// guaranteed to have `error::operation_aborted` passed to it. This is true - /// regardless of whether cancel() is called explicitly or implicitly, such - /// as when the acceptor is destroyed. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec)` where `ec` is the error code. If the the handler object is - /// movable, it will never be copied. Otherwise, it will be copied as - /// necessary. - /// - /// It is an error to start a new accept operation (synchronous or - /// asynchronous) while an asynchronous accept operation is in progress. An - /// asynchronous accept operation is considered complete as soon as the - /// completion handler starts executing. This means that a new accept - /// operation can be started from the completion handler. - /// - /// \param sock This is the local socket, that upon successful completion - /// will have become connected to the remote socket. It must be in the - /// closed state (Socket::is_open()) when async_accept() is called. - /// - /// \param ep Upon completion, the remote peer endpoint will have been - /// assigned to this variable. - template void async_accept(Socket& sock, H handler); - template void async_accept(Socket& sock, Endpoint& ep, H handler); - /// @} - -private: - using Want = Service::Want; - - class AcceptOperBase; - template class AcceptOper; - - using LendersAcceptOperPtr = std::unique_ptr; - - std::error_code accept(Socket&, Endpoint*, std::error_code&); - Want do_accept_async(Socket&, Endpoint*, std::error_code&) noexcept; - - template void async_accept(Socket&, Endpoint*, H); -}; - - -/// \brief A timer object supporting asynchronous wait operations. -class DeadlineTimer { -public: - DeadlineTimer(Service&); - ~DeadlineTimer() noexcept; - - /// Thread-safe. - Service& get_service() noexcept; - - /// \brief Perform an asynchronous wait operation. - /// - /// Initiate an asynchronous wait operation. The completion handler becomes - /// ready to execute when the expiration time is reached, or an error occurs - /// (cancellation counts as an error here). The expiration time is the time - /// of initiation plus the specified delay. The error code passed to the - /// complition handler will **never** indicate success, unless the - /// expiration time was reached. - /// - /// The completion handler is always executed by the event loop thread, - /// i.e., by a thread that is executing Service::run(). Conversely, the - /// completion handler is guaranteed to not be called while no thread is - /// executing Service::run(). The execution of the completion handler is - /// always deferred to the event loop, meaning that it never happens as a - /// synchronous side effect of the execution of async_wait(), even when - /// async_wait() is executed by the event loop thread. The completion - /// handler is guaranteed to be called eventually, as long as there is time - /// enough for the operation to complete or fail, and a thread is executing - /// Service::run() for long enough. - /// - /// The operation can be canceled by calling cancel(), and will be - /// automatically canceled if the timer is destroyed. If the operation is - /// canceled, it will fail with `error::operation_aborted`. The operation - /// remains cancelable up until the point in time where the completion - /// handler starts to execute. This means that if cancel() is called before - /// the completion handler starts to execute, then the completion handler is - /// guaranteed to have `error::operation_aborted` passed to it. This is true - /// regardless of whether cancel() is called explicitly or implicitly, such - /// as when the timer is destroyed. - /// - /// The specified handler will be executed by an expression on the form - /// `handler(ec)` where `ec` is the error code. If the the handler object is - /// movable, it will never be copied. Otherwise, it will be copied as - /// necessary. - /// - /// It is an error to start a new asynchronous wait operation while an - /// another one is in progress. An asynchronous wait operation is in - /// progress until its completion handler starts executing. - template - void async_wait(std::chrono::duration delay, H handler); - - /// \brief Cancel an asynchronous wait operation. - /// - /// If an asynchronous wait operation, that is associated with this deadline - /// timer, is in progress, cause it to fail with - /// `error::operation_aborted`. An asynchronous wait operation is in - /// progress until its completion handler starts executing. - /// - /// Completion handlers of canceled operations will become immediately ready - /// to execute, but will never be executed directly as part of the execution - /// of cancel(). - /// - /// Cancellation happens automatically when the timer object is destroyed. - void cancel() noexcept; - -private: - template class WaitOper; - - using clock = Service::clock; - - Service::Impl& m_service_impl; - Service::OwnersOperPtr m_wait_oper; - - void initiate_oper(Service::LendersWaitOperPtr); -}; - - -/// \brief Register a function whose invocation can be triggered repeatedly. -/// -/// While the function is always executed by the event loop thread, the -/// triggering of its execution can be done by any thread, and the triggering -/// operation is guaranteed to never throw. -/// -/// The function is guaranteed to not be called after the Trigger object is -/// destroyed. -/// -/// It is safe to destroy the Trigger object during execution of the function. -/// -/// Note that even though the trigger() function is thread-safe, the Trigger -/// object, as a whole, is not. In particular, construction and destruction must -/// not be considered thread-safe. -/// -/// ### Relation to post() -/// -/// For a particular execution of trigger() and a particular invocation of -/// Service::post(), if the execution of trigger() ends before the execution of -/// Service::post() begins, then it is guaranteed that the function associated -/// with the trigger gets to execute at least once after the execution of -/// trigger() begins, and before the post handler gets to execute. -class Trigger { -public: - template Trigger(Service&, F func); - ~Trigger() noexcept; - - Trigger() noexcept = default; - Trigger(Trigger&&) noexcept = default; - Trigger& operator=(Trigger&&) noexcept = default; - - /// \brief Trigger another invocation of the associated function. - /// - /// An invocation of trigger() puts the Trigger object into the triggered - /// state. It remains in the triggered state until shortly before the - /// function starts to execute. While the Trigger object is in the triggered - /// state, trigger() has no effect. This means that the number of executions - /// of the function will generally be less that the number of times - /// trigger() is invoked(). - /// - /// A particular invocation of trigger() ensures that there will be at least - /// one invocation of the associated function whose execution begins after - /// the beginning of the execution of trigger(), so long as the event loop - /// thread does not exit prematurely from run(). - /// - /// If trigger() is invoked from the event loop thread, the next execution - /// of the associated function will not begin until after trigger returns(), - /// effectively preventing reentrancy for the associated function. - /// - /// If trigger() is invoked from another thread, the associated function may - /// start to execute before trigger() returns. - /// - /// Note that the associated function can retrigger itself, i.e., if the - /// associated function calls trigger(), then that will lead to another - /// invocation of the associated function, but not until the first - /// invocation ends (no reentrance). - /// - /// This function is thread-safe. - void trigger() noexcept; - -private: - template class ExecOper; - - util::bind_ptr m_exec_oper; -}; - - -class ReadAheadBuffer { -public: - ReadAheadBuffer(); - - /// Discard any buffered data. - void clear() noexcept; - -private: - using Want = Service::Want; - - char* m_begin = nullptr; - char* m_end = nullptr; - static constexpr std::size_t s_size = 1024; - const std::unique_ptr m_buffer; - - bool empty() const noexcept; - bool read(char*& begin, char* end, int delim, std::error_code&) noexcept; - template void refill_sync(S& stream, std::error_code&) noexcept; - template bool refill_async(S& stream, std::error_code&, Want&) noexcept; - - template friend class Service::BasicStreamOps; -}; - - -enum class ResolveErrors { - /// Host not found (authoritative). - host_not_found = 1, - - /// Host not found (non-authoritative). - host_not_found_try_again, - - /// The query is valid but does not have associated address data. - no_data, - - /// A non-recoverable error occurred. - no_recovery, - - /// The service is not supported for the given socket type. - service_not_found, - - /// The socket type is not supported. - socket_type_not_supported -}; - -class ResolveErrorCategory : public std::error_category { -public: - const char* name() const noexcept override final; - std::string message(int) const override final; -}; - -/// The error category associated with ResolveErrors. The name of this category is -/// `realm.util.network.resolve`. -extern ResolveErrorCategory resolve_error_category; - -inline std::error_code make_error_code(ResolveErrors err) -{ - return std::error_code(int(err), resolve_error_category); -} - -} // namespace network -} // namespace util -} // namespace realm - -namespace std { - -template<> class is_error_code_enum { -public: - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace util { -namespace network { - - - - - -// Implementation - -// ---------------- StreamProtocol ---------------- - -inline StreamProtocol StreamProtocol::ip_v4() -{ - StreamProtocol prot; - prot.m_family = AF_INET; - return prot; -} - -inline StreamProtocol StreamProtocol::ip_v6() -{ - StreamProtocol prot; - prot.m_family = AF_INET6; - return prot; -} - -inline bool StreamProtocol::is_ip_v4() const -{ - return m_family == AF_INET; -} - -inline bool StreamProtocol::is_ip_v6() const -{ - return m_family == AF_INET6; -} - -inline int StreamProtocol::family() const -{ - return m_family; -} - -inline int StreamProtocol::protocol() const -{ - return m_protocol; -} - -inline StreamProtocol::StreamProtocol() : - m_family{AF_UNSPEC}, // Allow both IPv4 and IPv6 - m_socktype{SOCK_STREAM}, // Or SOCK_DGRAM for UDP - m_protocol{0} // Any protocol -{ -} - -// ---------------- Address ---------------- - -inline bool Address::is_ip_v4() const -{ - return !m_is_ip_v6; -} - -inline bool Address::is_ip_v6() const -{ - return m_is_ip_v6; -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, const Address& addr) -{ - // FIXME: Not taking `addr.m_ip_v6_scope_id` into account. What does ASIO - // do? - union buffer_union { - char ip_v4[INET_ADDRSTRLEN]; - char ip_v6[INET6_ADDRSTRLEN]; - }; - char buffer[sizeof (buffer_union)]; - int af = addr.m_is_ip_v6 ? AF_INET6 : AF_INET; -#ifdef _WIN32 - void* src = const_cast(reinterpret_cast(&addr.m_union)); -#else - const void* src = &addr.m_union; -#endif - const char* ret = ::inet_ntop(af, src, buffer, sizeof buffer); - if (ret == 0) { - std::error_code ec = make_basic_system_error_code(errno); - throw std::system_error(ec); - } - out << ret; - return out; -} - -inline Address::Address() -{ - m_union.m_ip_v4 = ip_v4_type(); -} - -inline Address make_address(const char* c_str) -{ - std::error_code ec; - Address addr = make_address(c_str, ec); - if (ec) - throw std::system_error(ec); - return addr; -} - -inline Address make_address(const std::string& str) -{ - std::error_code ec; - Address addr = make_address(str, ec); - if (ec) - throw std::system_error(ec); - return addr; -} - -inline Address make_address(const std::string& str, std::error_code& ec) noexcept -{ - return make_address(str.c_str(), ec); -} - -// ---------------- Endpoint ---------------- - -inline StreamProtocol Endpoint::protocol() const -{ - return m_protocol; -} - -inline Address Endpoint::address() const -{ - Address addr; - if (m_protocol.is_ip_v4()) { - addr.m_union.m_ip_v4 = m_sockaddr_union.m_ip_v4.sin_addr; - } - else { - addr.m_union.m_ip_v6 = m_sockaddr_union.m_ip_v6.sin6_addr; - addr.m_ip_v6_scope_id = m_sockaddr_union.m_ip_v6.sin6_scope_id; - addr.m_is_ip_v6 = true; - } - return addr; -} - -inline Endpoint::port_type Endpoint::port() const -{ - return ntohs(m_protocol.is_ip_v4() ? m_sockaddr_union.m_ip_v4.sin_port : - m_sockaddr_union.m_ip_v6.sin6_port); -} - -inline Endpoint::data_type* Endpoint::data() -{ - return &m_sockaddr_union.m_base; -} - -inline const Endpoint::data_type* Endpoint::data() const -{ - return &m_sockaddr_union.m_base; -} - -inline Endpoint::Endpoint() : - Endpoint{StreamProtocol::ip_v4(), 0} -{ -} - -inline Endpoint::Endpoint(const StreamProtocol& protocol, port_type port) : - m_protocol{protocol} -{ - int family = m_protocol.family(); - if (family == AF_INET) { - m_sockaddr_union.m_ip_v4 = sockaddr_ip_v4_type(); // Clear - m_sockaddr_union.m_ip_v4.sin_family = AF_INET; - m_sockaddr_union.m_ip_v4.sin_port = htons(port); - m_sockaddr_union.m_ip_v4.sin_addr.s_addr = INADDR_ANY; - } - else if (family == AF_INET6) { - m_sockaddr_union.m_ip_v6 = sockaddr_ip_v6_type(); // Clear - m_sockaddr_union.m_ip_v6.sin6_family = AF_INET6; - m_sockaddr_union.m_ip_v6.sin6_port = htons(port); - } - else { - m_sockaddr_union.m_ip_v4 = sockaddr_ip_v4_type(); // Clear - m_sockaddr_union.m_ip_v4.sin_family = AF_UNSPEC; - m_sockaddr_union.m_ip_v4.sin_port = htons(port); - m_sockaddr_union.m_ip_v4.sin_addr.s_addr = INADDR_ANY; - } -} - -inline Endpoint::Endpoint(const Address& addr, port_type port) -{ - if (addr.m_is_ip_v6) { - m_protocol = StreamProtocol::ip_v6(); - m_sockaddr_union.m_ip_v6.sin6_family = AF_INET6; - m_sockaddr_union.m_ip_v6.sin6_port = htons(port); - m_sockaddr_union.m_ip_v6.sin6_flowinfo = 0; - m_sockaddr_union.m_ip_v6.sin6_addr = addr.m_union.m_ip_v6; - m_sockaddr_union.m_ip_v6.sin6_scope_id = addr.m_ip_v6_scope_id; - } - else { - m_protocol = StreamProtocol::ip_v4(); - m_sockaddr_union.m_ip_v4.sin_family = AF_INET; - m_sockaddr_union.m_ip_v4.sin_port = htons(port); - m_sockaddr_union.m_ip_v4.sin_addr = addr.m_union.m_ip_v4; - } -} - -inline Endpoint::List::iterator Endpoint::List::begin() const noexcept -{ - return m_endpoints.data(); -} - -inline Endpoint::List::iterator Endpoint::List::end() const noexcept -{ - return m_endpoints.data() + m_endpoints.size(); -} - -inline std::size_t Endpoint::List::size() const noexcept -{ - return m_endpoints.size(); -} - -inline bool Endpoint::List::empty() const noexcept -{ - return m_endpoints.size() == 0; -} - -// ---------------- Service::OperQueue ---------------- - -template inline bool Service::OperQueue::empty() const noexcept -{ - return !m_back; -} - -template inline void Service::OperQueue::push_back(LendersOperPtr op) noexcept -{ - REALM_ASSERT(!op->m_next); - if (m_back) { - op->m_next = m_back->m_next; - m_back->m_next = op.get(); - } - else { - op->m_next = op.get(); - } - m_back = op.release(); -} - -template template -inline void Service::OperQueue::push_back(OperQueue& q) noexcept -{ - if (!q.m_back) - return; - if (m_back) - std::swap(m_back->m_next, q.m_back->m_next); - m_back = q.m_back; - q.m_back = nullptr; -} - -template inline auto Service::OperQueue::pop_front() noexcept -> LendersOperPtr -{ - Oper* op = nullptr; - if (m_back) { - op = static_cast(m_back->m_next); - if (op != m_back) { - m_back->m_next = op->m_next; - } - else { - m_back = nullptr; - } - op->m_next = nullptr; - } - return LendersOperPtr(op); -} - -template inline void Service::OperQueue::clear() noexcept -{ - if (m_back) { - LendersOperPtr op(m_back); - while (op->m_next != m_back) - op.reset(static_cast(op->m_next)); - m_back = nullptr; - } -} - -template inline Service::OperQueue::OperQueue(OperQueue&& q) noexcept : - m_back{q.m_back} -{ - q.m_back = nullptr; -} - -template inline Service::OperQueue::~OperQueue() noexcept -{ - clear(); -} - -// ---------------- Service::Descriptor ---------------- - -inline Service::Descriptor::Descriptor(Impl& s) noexcept : - service_impl{s} -{ -} - -inline Service::Descriptor::~Descriptor() noexcept -{ - if (is_open()) - close(); -} - -inline void Service::Descriptor::assign(native_handle_type fd, bool in_blocking_mode) noexcept -{ - REALM_ASSERT(!is_open()); - m_fd = fd; - m_in_blocking_mode = in_blocking_mode; -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - m_read_ready = false; - m_write_ready = false; - m_imminent_end_of_input = false; - m_is_registered = false; -#endif -} - -inline void Service::Descriptor::close() noexcept -{ - REALM_ASSERT(is_open()); -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - if (m_is_registered) - deregister_for_async(); - m_is_registered = false; -#endif - do_close(); -} - -inline auto Service::Descriptor::release() noexcept -> native_handle_type -{ - REALM_ASSERT(is_open()); -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - if (m_is_registered) - deregister_for_async(); - m_is_registered = false; -#endif - return do_release(); -} - -inline bool Service::Descriptor::is_open() const noexcept -{ - return (m_fd != -1); -} - -inline auto Service::Descriptor::native_handle() const noexcept -> native_handle_type -{ - return m_fd; -} - -inline bool Service::Descriptor::in_blocking_mode() const noexcept -{ - return m_in_blocking_mode; -} - -template -inline void Service::Descriptor::initiate_oper(std::unique_ptr op, - Args&&... args) -{ - Service::Want want = op->initiate(std::forward(args)...); // Throws - add_initiated_oper(std::move(op), want); // Throws -} - -inline void Service::Descriptor::ensure_blocking_mode() -{ - // Assuming that descriptors are either used mostly in blocking mode, or - // mostly in nonblocking mode. - if (REALM_UNLIKELY(!m_in_blocking_mode)) { - bool value = false; - set_nonblock_flag(value); // Throws - m_in_blocking_mode = true; - } -} - -inline void Service::Descriptor::ensure_nonblocking_mode() -{ - // Assuming that descriptors are either used mostly in blocking mode, or - // mostly in nonblocking mode. - if (REALM_UNLIKELY(m_in_blocking_mode)) { - bool value = true; - set_nonblock_flag(value); // Throws - m_in_blocking_mode = false; - } -} - -inline bool Service::Descriptor::assume_read_would_block() const noexcept -{ -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - return !m_in_blocking_mode && !m_read_ready; -#else - return false; -#endif -} - -inline bool Service::Descriptor::assume_write_would_block() const noexcept -{ -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - return !m_in_blocking_mode && !m_write_ready; -#else - return false; -#endif -} - -inline void Service::Descriptor::set_read_ready(bool value) noexcept -{ -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - m_read_ready = value; -#else - // No-op - static_cast(value); -#endif -} - -inline void Service::Descriptor::set_write_ready(bool value) noexcept -{ -#if REALM_HAVE_EPOLL || REALM_HAVE_KQUEUE - m_write_ready = value; -#else - // No-op - static_cast(value); -#endif -} - -// ---------------- Service ---------------- - -class Service::AsyncOper { -public: - bool in_use() const noexcept; - bool is_complete() const noexcept; - bool is_canceled() const noexcept; - void cancel() noexcept; - /// Every object of type \ref AsyncOper must be destroyed either by a call - /// to this function or to recycle(). This function recycles the operation - /// object (commits suicide), even if it throws. - virtual void recycle_and_execute() = 0; - /// Every object of type \ref AsyncOper must be destroyed either by a call - /// to recycle_and_execute() or to this function. This function destroys the - /// object (commits suicide). - virtual void recycle() noexcept = 0; - /// Must be called when the owner dies, and the object is in use (not an - /// instance of UnusedOper). - virtual void orphan() noexcept = 0; -protected: - AsyncOper(std::size_t size, bool in_use) noexcept; - virtual ~AsyncOper() noexcept {} - void set_is_complete(bool value) noexcept; - template - void do_recycle_and_execute(bool orphaned, H& handler, Args&&...); - void do_recycle(bool orphaned) noexcept; -private: - std::size_t m_size; // Allocated number of bytes - bool m_in_use = false; - // Set to true when the operation completes successfully or fails. If the - // operation is canceled before this happens, it will never be set to - // true. Always false when not in use - bool m_complete = false; - // Set to true when the operation is canceled. Always false when not in use. - bool m_canceled = false; - AsyncOper* m_next = nullptr; // Always null when not in use - template - void do_recycle_and_execute_helper(bool orphaned, bool& was_recycled, H handler, Args...); - friend class Service; -}; - -class Service::ResolveOperBase : public AsyncOper { -public: - ResolveOperBase(std::size_t size, Resolver& resolver, Resolver::Query query) noexcept : - AsyncOper{size, true}, - m_resolver{&resolver}, - m_query{std::move(query)} - { - } - void complete() noexcept - { - set_is_complete(true); - } - void recycle() noexcept override final - { - bool orphaned = !m_resolver; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_resolver = nullptr; - } -protected: - Resolver* m_resolver; - Resolver::Query m_query; - Endpoint::List m_endpoints; - std::error_code m_error_code; - friend class Service; -}; - -class Service::WaitOperBase : public AsyncOper { -public: - WaitOperBase(std::size_t size, DeadlineTimer& timer, - clock::time_point expiration_time) noexcept : - AsyncOper{size, true}, // Second argument is `in_use` - m_timer{&timer}, - m_expiration_time{expiration_time} - { - } - void complete() noexcept - { - set_is_complete(true); - } - void recycle() noexcept override final - { - bool orphaned = !m_timer; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_timer = nullptr; - } -protected: - DeadlineTimer* m_timer; - clock::time_point m_expiration_time; - friend class Service; -}; - -class Service::TriggerExecOperBase : public AsyncOper, public AtomicRefCountBase { -public: - TriggerExecOperBase(Impl& service) noexcept : - AsyncOper{0, false}, // First arg is `size` (unused), second arg is `in_use` - m_service{&service} - { - } - void recycle() noexcept override final - { - REALM_ASSERT(in_use()); - REALM_ASSERT(!m_service); - // Note: Potential suicide when `self` goes out of scope - util::bind_ptr self{this, bind_ptr_base::adopt_tag{}}; - } - void orphan() noexcept override final - { - REALM_ASSERT(m_service); - m_service = nullptr; - } - void trigger() noexcept - { - REALM_ASSERT(m_service); - Service::trigger_exec(*m_service, *this); - } -protected: - Impl* m_service; -}; - -class Service::PostOperBase : public AsyncOper { -public: - PostOperBase(std::size_t size, Impl& service) noexcept : - AsyncOper{size, true}, // Second argument is `in_use` - m_service{service} - { - } - void recycle() noexcept override final - { - // Service::recycle_post_oper() destroys this operation object - Service::recycle_post_oper(m_service, this); - } - void orphan() noexcept override final - { - REALM_ASSERT(false); // Never called - } -protected: - Impl& m_service; -}; - -template class Service::PostOper : public PostOperBase { -public: - PostOper(std::size_t size, Impl& service, H handler) : - PostOperBase{size, service}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - // Recycle the operation object before the handler is exceuted, such - // that the memory is available for a new post operation that might be - // initiated during the execution of the handler. - bool was_recycled = false; - try { - H handler = std::move(m_handler); // Throws - // Service::recycle_post_oper() destroys this operation object - Service::recycle_post_oper(m_service, this); - was_recycled = true; - handler(); // Throws - } - catch (...) { - if (!was_recycled) { - // Service::recycle_post_oper() destroys this operation object - Service::recycle_post_oper(m_service, this); - } - throw; - } - } -private: - H m_handler; -}; - -class Service::IoOper : public AsyncOper { -public: - IoOper(std::size_t size) noexcept : - AsyncOper{size, true} // Second argument is `in_use` - { - } - virtual Descriptor& descriptor() noexcept = 0; - /// Advance this operation and figure out out whether it needs to read from, - /// or write to the underlying descriptor to advance further. This function - /// must return Want::read if the operation needs to read, or Want::write if - /// the operation needs to write to advance further. If the operation - /// completes (due to success or failure), this function must return - /// Want::nothing. - virtual Want advance() noexcept = 0; -}; - -class Service::UnusedOper : public AsyncOper { -public: - UnusedOper(std::size_t size) noexcept : - AsyncOper{size, false} // Second argument is `in_use` - { - } - void recycle_and_execute() override final - { - // Must never be called - REALM_ASSERT(false); - } - void recycle() noexcept override final - { - // Must never be called - REALM_ASSERT(false); - } - void orphan() noexcept override final - { - // Must never be called - REALM_ASSERT(false); - } -}; - -// `S` must be a stream class with the following member functions: -// -// Socket& lowest_layer() noexcept; -// -// void do_init_read_async(std::error_code& ec, Want& want) noexcept; -// void do_init_write_async(std::error_code& ec, Want& want) noexcept; -// -// std::size_t do_read_some_sync(char* buffer, std::size_t size, -// std::error_code& ec) noexcept; -// std::size_t do_write_some_sync(const char* data, std::size_t size, -// std::error_code& ec) noexcept; -// std::size_t do_read_some_async(char* buffer, std::size_t size, -// std::error_code& ec, Want& want) noexcept; -// std::size_t do_write_some_async(const char* data, std::size_t size, -// std::error_code& ec, Want& want) noexcept; -// -// If an error occurs during any of these 6 functions, the `ec` argument must be -// set accordingly. Otherwise the `ec` argument must be set to -// `std::error_code()`. -// -// The do_init_*_async() functions must update the `want` argument to indicate -// how the operation must be initiated: -// -// Want::read Wait for read readiness, then call do_*_some_async(). -// Want::write Wait for write readiness, then call do_*_some_async(). -// Want::nothing Call do_*_some_async() immediately without waiting for -// read or write readiness. -// -// If end-of-input occurs while reading, do_read_some_*() must fail, set `ec` to -// MiscExtErrors::end_of_input, and return zero. -// -// If an error occurs during reading or writing, do_*_some_sync() must set `ec` -// accordingly (to something other than `std::system_error()`) and return -// zero. Otherwise they must set `ec` to `std::system_error()` and return the -// number of bytes read or written, which **must** be at least 1. If the -// underlying socket is in nonblocking mode, and no bytes could be immediately -// read or written, these functions must fail with -// `error::resource_unavailable_try_again`. -// -// If an error occurs during reading or writing, do_*_some_async() must set `ec` -// accordingly (to something other than `std::system_error()`), `want` to -// `Want::nothing`, and return zero. Otherwise they must set `ec` to -// `std::system_error()` and return the number of bytes read or written, which -// must be zero if no bytes could be immediately read or written. Note, in this -// case it is not an error if the underlying socket is in nonblocking mode, and -// no bytes could be immediately read or written. When these functions succeed, -// but return zero because no bytes could be immediately read or written, they -// must set `want` to something other than `Want::nothing`. -// -// If no error occurs, do_*_some_async() must set `want` to indicate how the -// operation should proceed if additional data needs to be read or written, or -// if no bytes were transferred: -// -// Want::read Wait for read readiness, then call do_*_some_async() again. -// Want::write Wait for write readiness, then call do_*_some_async() again. -// Want::nothing Call do_*_some_async() again without waiting for read or -// write readiness. -// -// NOTE: If, for example, do_read_some_async() sets `want` to `Want::write`, it -// means that the stream needs to write data to the underlying TCP socket before -// it is able to deliver any additional data to the caller. While such a -// situation will never occur on a raw TCP socket, it can occur on an SSL stream -// (Secure Socket Layer). -// -// When do_*_some_async() returns `n`, at least one of the following conditions -// must be true: -// -// n > 0 Bytes were transferred. -// ec != std::error_code() An error occured. -// want != Want::nothing Wait for read/write readiness. -// -// This is of critical importance, as it is the only way we can avoid falling -// into a busy loop of repeated invocations of do_*_some_async(). -// -// NOTE: do_*_some_async() are allowed to set `want` to `Want::read` or -// `Want::write`, even when they succesfully transfer a nonzero number of bytes. -template class Service::BasicStreamOps { -public: - class StreamOper; - class ReadOperBase; - class WriteOperBase; - class BufferedReadOperBase; - template class ReadOper; - template class WriteOper; - template class BufferedReadOper; - - using LendersReadOperPtr = std::unique_ptr; - using LendersWriteOperPtr = std::unique_ptr; - using LendersBufferedReadOperPtr = std::unique_ptr; - - // Synchronous read - static std::size_t read(S& stream, char* buffer, std::size_t size, - std::error_code& ec) - { - REALM_ASSERT(!stream.lowest_layer().m_read_oper || - !stream.lowest_layer().m_read_oper->in_use()); - stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws - char* begin = buffer; - char* end = buffer + size; - char* curr = begin; - for (;;) { - if (curr == end) { - ec = std::error_code(); // Success - break; - } - char* buffer_2 = curr; - std::size_t size_2 = std::size_t(end - curr); - std::size_t n = stream.do_read_some_sync(buffer_2, size_2, ec); - if (REALM_UNLIKELY(ec)) - break; - REALM_ASSERT(n > 0); - REALM_ASSERT(n <= size_2); - curr += n; - } - std::size_t n = std::size_t(curr - begin); - return n; - } - - // Synchronous write - static std::size_t write(S& stream, const char* data, std::size_t size, - std::error_code& ec) - { - REALM_ASSERT(!stream.lowest_layer().m_write_oper || - !stream.lowest_layer().m_write_oper->in_use()); - stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws - const char* begin = data; - const char* end = data + size; - const char* curr = begin; - for (;;) { - if (curr == end) { - ec = std::error_code(); // Success - break; - } - const char* data_2 = curr; - std::size_t size_2 = std::size_t(end - curr); - std::size_t n = stream.do_write_some_sync(data_2, size_2, ec); - if (REALM_UNLIKELY(ec)) - break; - REALM_ASSERT(n > 0); - REALM_ASSERT(n <= size_2); - curr += n; - } - std::size_t n = std::size_t(curr - begin); - return n; - } - - // Synchronous read - static std::size_t buffered_read(S& stream, char* buffer, std::size_t size, int delim, - ReadAheadBuffer& rab, std::error_code& ec) - { - REALM_ASSERT(!stream.lowest_layer().m_read_oper || - !stream.lowest_layer().m_read_oper->in_use()); - stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws - char* begin = buffer; - char* end = buffer + size; - char* curr = begin; - for (;;) { - bool complete = rab.read(curr, end, delim, ec); - if (complete) - break; - - rab.refill_sync(stream, ec); - if (REALM_UNLIKELY(ec)) - break; - } - std::size_t n = (curr - begin); - return n; - } - - // Synchronous read - static std::size_t read_some(S& stream, char* buffer, std::size_t size, - std::error_code& ec) - { - REALM_ASSERT(!stream.lowest_layer().m_read_oper || - !stream.lowest_layer().m_read_oper->in_use()); - stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws - return stream.do_read_some_sync(buffer, size, ec); - } - - // Synchronous write - static std::size_t write_some(S& stream, const char* data, std::size_t size, - std::error_code& ec) - { - REALM_ASSERT(!stream.lowest_layer().m_write_oper || - !stream.lowest_layer().m_write_oper->in_use()); - stream.lowest_layer().m_desc.ensure_blocking_mode(); // Throws - return stream.do_write_some_sync(data, size, ec); - } - - template - static void async_read(S& stream, char* buffer, std::size_t size, bool is_read_some, H handler) - { - char* begin = buffer; - char* end = buffer + size; - LendersReadOperPtr op = - Service::alloc>(stream.lowest_layer().m_read_oper, stream, is_read_some, - begin, end, std::move(handler)); // Throws - stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws - } - - template - static void async_write(S& stream, const char* data, std::size_t size, bool is_write_some, - H handler) - { - const char* begin = data; - const char* end = data + size; - LendersWriteOperPtr op = - Service::alloc>(stream.lowest_layer().m_write_oper, stream, is_write_some, - begin, end, std::move(handler)); // Throws - stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws - } - - template - static void async_buffered_read(S& stream, char* buffer, std::size_t size, int delim, - ReadAheadBuffer& rab, H handler) - { - char* begin = buffer; - char* end = buffer + size; - LendersBufferedReadOperPtr op = - Service::alloc>(stream.lowest_layer().m_read_oper, stream, - begin, end, delim, rab, - std::move(handler)); // Throws - stream.lowest_layer().m_desc.initiate_oper(std::move(op)); // Throws - } -}; - -template class Service::BasicStreamOps::StreamOper : public IoOper { -public: - StreamOper(std::size_t size, S& stream) noexcept : - IoOper{size}, - m_stream{&stream} - { - } - void recycle() noexcept override final - { - bool orphaned = !m_stream; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_stream = nullptr; - } - Descriptor& descriptor() noexcept override final - { - return m_stream->lowest_layer().m_desc; - } -protected: - S* m_stream; - std::error_code m_error_code; -}; - -template class Service::BasicStreamOps::ReadOperBase : public StreamOper { -public: - ReadOperBase(std::size_t size, S& stream, bool is_read_some, char* begin, char* end) noexcept : - StreamOper{size, stream}, - m_is_read_some{is_read_some}, - m_begin{begin}, - m_end{end} - { - } - Want initiate() - { - auto& s = *this; - REALM_ASSERT(this == s.m_stream->lowest_layer().m_read_oper.get()); - REALM_ASSERT(!s.is_complete()); - REALM_ASSERT(s.m_curr <= s.m_end); - Want want = Want::nothing; - if (REALM_UNLIKELY(s.m_curr == s.m_end)) { - s.set_is_complete(true); // Success - } - else { - s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws - s.m_stream->do_init_read_async(s.m_error_code, want); - if (want == Want::nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - } - else { - want = advance(); - } - } - } - return want; - } - Want advance() noexcept override final - { - auto& s = *this; - REALM_ASSERT(!s.is_complete()); - REALM_ASSERT(!s.is_canceled()); - REALM_ASSERT(!s.m_error_code); - REALM_ASSERT(s.m_curr < s.m_end); - REALM_ASSERT(!s.m_is_read_some || s.m_curr == m_begin); - for (;;) { - // Read into callers buffer - char* buffer = s.m_curr; - std::size_t size = std::size_t(s.m_end - s.m_curr); - Want want = Want::nothing; - std::size_t n = s.m_stream->do_read_some_async(buffer, size, s.m_error_code, want); - REALM_ASSERT(n > 0 || s.m_error_code || want != Want::nothing); // No busy loop, please - bool got_nothing = (n == 0); - if (got_nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - return Want::nothing; - } - // Got nothing, but want something - return want; - } - REALM_ASSERT(!s.m_error_code); - // Check for completion - REALM_ASSERT(n <= size); - s.m_curr += n; - if (s.m_is_read_some || s.m_curr == s.m_end) { - s.set_is_complete(true); // Success - return Want::nothing; - } - if (want != Want::nothing) - return want; - REALM_ASSERT(n < size); - } - } -protected: - const bool m_is_read_some; - char* const m_begin; // May be dangling after cancellation - char* const m_end; // May be dangling after cancellation - char* m_curr = m_begin; // May be dangling after cancellation -}; - -template class Service::BasicStreamOps::WriteOperBase : public StreamOper { -public: - WriteOperBase(std::size_t size, S& stream, bool is_write_some, - const char* begin, const char* end) noexcept : - StreamOper{size, stream}, - m_is_write_some{is_write_some}, - m_begin{begin}, - m_end{end} - { - } - Want initiate() - { - auto& s = *this; - REALM_ASSERT(this == s.m_stream->lowest_layer().m_write_oper.get()); - REALM_ASSERT(!s.is_complete()); - REALM_ASSERT(s.m_curr <= s.m_end); - Want want = Want::nothing; - if (REALM_UNLIKELY(s.m_curr == s.m_end)) { - s.set_is_complete(true); // Success - } - else { - s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws - s.m_stream->do_init_write_async(s.m_error_code, want); - if (want == Want::nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - } - else { - want = advance(); - } - } - } - return want; - } - Want advance() noexcept override final - { - auto& s = *this; - REALM_ASSERT(!s.is_complete()); - REALM_ASSERT(!s.is_canceled()); - REALM_ASSERT(!s.m_error_code); - REALM_ASSERT(s.m_curr < s.m_end); - REALM_ASSERT(!s.m_is_write_some || s.m_curr == s.m_begin); - for (;;) { - // Write from callers buffer - const char* data = s.m_curr; - std::size_t size = std::size_t(s.m_end - s.m_curr); - Want want = Want::nothing; - std::size_t n = s.m_stream->do_write_some_async(data, size, s.m_error_code, want); - REALM_ASSERT(n > 0 || s.m_error_code || want != Want::nothing); // No busy loop, please - bool wrote_nothing = (n == 0); - if (wrote_nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - return Want::nothing; - } - // Wrote nothing, but want something written - return want; - } - REALM_ASSERT(!s.m_error_code); - // Check for completion - REALM_ASSERT(n <= size); - s.m_curr += n; - if (s.m_is_write_some || s.m_curr == s.m_end) { - s.set_is_complete(true); // Success - return Want::nothing; - } - if (want != Want::nothing) - return want; - REALM_ASSERT(n < size); - } - } -protected: - const bool m_is_write_some; - const char* const m_begin; // May be dangling after cancellation - const char* const m_end; // May be dangling after cancellation - const char* m_curr = m_begin; // May be dangling after cancellation -}; - -template class Service::BasicStreamOps::BufferedReadOperBase : public StreamOper { -public: - BufferedReadOperBase(std::size_t size, S& stream, char* begin, char* end, int delim, - ReadAheadBuffer& rab) noexcept : - StreamOper{size, stream}, - m_read_ahead_buffer{rab}, - m_begin{begin}, - m_end{end}, - m_delim{delim} - { - } - Want initiate() - { - auto& s = *this; - REALM_ASSERT(this == s.m_stream->lowest_layer().m_read_oper.get()); - REALM_ASSERT(!s.is_complete()); - Want want = Want::nothing; - bool complete = s.m_read_ahead_buffer.read(s.m_curr, s.m_end, s.m_delim, s.m_error_code); - if (complete) { - s.set_is_complete(true); // Success or failure - } - else { - s.m_stream->lowest_layer().m_desc.ensure_nonblocking_mode(); // Throws - s.m_stream->do_init_read_async(s.m_error_code, want); - if (want == Want::nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - } - else { - want = advance(); - } - } - } - return want; - } - Want advance() noexcept override final - { - auto& s = *this; - REALM_ASSERT(!s.is_complete()); - REALM_ASSERT(!s.is_canceled()); - REALM_ASSERT(!s.m_error_code); - REALM_ASSERT(s.m_read_ahead_buffer.empty()); - REALM_ASSERT(s.m_curr < s.m_end); - for (;;) { - // Fill read-ahead buffer from stream (is empty now) - Want want = Want::nothing; - bool nonempty = s.m_read_ahead_buffer.refill_async(*s.m_stream, s.m_error_code, want); - REALM_ASSERT(nonempty || s.m_error_code || - want != Want::nothing); // No busy loop, please - bool got_nothing = !nonempty; - if (got_nothing) { - if (REALM_UNLIKELY(s.m_error_code)) { - s.set_is_complete(true); // Failure - return Want::nothing; - } - // Got nothing, but want something - return want; - } - // Transfer buffered data to callers buffer - bool complete = - s.m_read_ahead_buffer.read(s.m_curr, s.m_end, s.m_delim, s.m_error_code); - if (complete) { - s.set_is_complete(true); // Success or failure (delim_not_found) - return Want::nothing; - } - if (want != Want::nothing) - return want; - } - } -protected: - ReadAheadBuffer& m_read_ahead_buffer; // May be dangling after cancellation - char* const m_begin; // May be dangling after cancellation - char* const m_end; // May be dangling after cancellation - char* m_curr = m_begin; // May be dangling after cancellation - const int m_delim; -}; - -template template -class Service::BasicStreamOps::ReadOper : public ReadOperBase { -public: - ReadOper(std::size_t size, S& stream, bool is_read_some, char* begin, char* end, H handler) : - ReadOperBase{size, stream, is_read_some, begin, end}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - auto& s = *this; - REALM_ASSERT(s.is_complete() || s.is_canceled()); - REALM_ASSERT(s.is_complete() == (s.m_error_code || s.m_curr == s.m_end || - (s.m_is_read_some && s.m_curr != s.m_begin))); - REALM_ASSERT(s.m_curr >= s.m_begin); - bool orphaned = !s.m_stream; - std::error_code ec = s.m_error_code; - if (s.is_canceled()) - ec = error::operation_aborted; - std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); - // Note: do_recycle_and_execute() commits suicide. - s.template do_recycle_and_execute(orphaned, s.m_handler, ec, - num_bytes_transferred); // Throws - } -private: - H m_handler; -}; - -template template -class Service::BasicStreamOps::WriteOper : public WriteOperBase { -public: - WriteOper(std::size_t size, S& stream, bool is_write_some, - const char* begin, const char* end, H handler) : - WriteOperBase{size, stream, is_write_some, begin, end}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - auto& s = *this; - REALM_ASSERT(s.is_complete() || s.is_canceled()); - REALM_ASSERT(s.is_complete() == (s.m_error_code || s.m_curr == s.m_end || - (s.m_is_write_some && s.m_curr != s.m_begin))); - REALM_ASSERT(s.m_curr >= s.m_begin); - bool orphaned = !s.m_stream; - std::error_code ec = s.m_error_code; - if (s.is_canceled()) - ec = error::operation_aborted; - std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); - // Note: do_recycle_and_execute() commits suicide. - s.template do_recycle_and_execute(orphaned, s.m_handler, ec, - num_bytes_transferred); // Throws - } -private: - H m_handler; -}; - -template template -class Service::BasicStreamOps::BufferedReadOper : public BufferedReadOperBase { -public: - BufferedReadOper(std::size_t size, S& stream, char* begin, char* end, int delim, - ReadAheadBuffer& rab, H handler) : - BufferedReadOperBase{size, stream, begin, end, delim, rab}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - auto& s = *this; - REALM_ASSERT(s.is_complete() || (s.is_canceled() && !s.m_error_code)); - REALM_ASSERT(s.is_canceled() || s.m_error_code || - (s.m_delim != std::char_traits::eof() ? - s.m_curr > s.m_begin && s.m_curr[-1] == - std::char_traits::to_char_type(s.m_delim) : - s.m_curr == s.m_end)); - REALM_ASSERT(s.m_curr >= s.m_begin); - bool orphaned = !s.m_stream; - std::error_code ec = s.m_error_code; - if (s.is_canceled()) - ec = error::operation_aborted; - std::size_t num_bytes_transferred = std::size_t(s.m_curr - s.m_begin); - // Note: do_recycle_and_execute() commits suicide. - s.template do_recycle_and_execute(orphaned, s.m_handler, ec, - num_bytes_transferred); // Throws - } -private: - H m_handler; -}; - -template inline void Service::post(H handler) -{ - do_post(&Service::post_oper_constr, sizeof (PostOper), &handler); -} - -inline void Service::OwnersOperDeleter::operator()(AsyncOper* op) const noexcept -{ - if (op->in_use()) { - op->orphan(); - } - else { - void* addr = op; - op->~AsyncOper(); - delete[] static_cast(addr); - } -} - -inline void Service::LendersOperDeleter::operator()(AsyncOper* op) const noexcept -{ - op->recycle(); // Suicide -} - -template std::unique_ptr -Service::alloc(OwnersOperPtr& owners_ptr, Args&&... args) -{ - void* addr = owners_ptr.get(); - std::size_t size; - if (REALM_LIKELY(addr)) { - REALM_ASSERT(!owners_ptr->in_use()); - size = owners_ptr->m_size; - // We can use static dispatch in the destructor call here, since an - // object, that is not in use, is always an instance of UnusedOper. - REALM_ASSERT(dynamic_cast(owners_ptr.get())); - static_cast(owners_ptr.get())->UnusedOper::~UnusedOper(); - if (REALM_UNLIKELY(size < sizeof (Oper))) { - owners_ptr.release(); - delete[] static_cast(addr); - goto no_object; - } - } - else { - no_object: - addr = new char[sizeof (Oper)]; // Throws - size = sizeof (Oper); - owners_ptr.reset(static_cast(addr)); - } - std::unique_ptr lenders_ptr; - try { - lenders_ptr.reset(new (addr) Oper(size, std::forward(args)...)); // Throws - } - catch (...) { - new (addr) UnusedOper(size); // Does not throw - throw; - } - return lenders_ptr; -} - -template inline Service::PostOperBase* -Service::post_oper_constr(void* addr, std::size_t size, Impl& service, void* cookie) -{ - H& handler = *static_cast(cookie); - return new (addr) PostOper(size, service, std::move(handler)); // Throws -} - -inline bool Service::AsyncOper::in_use() const noexcept -{ - return m_in_use; -} - -inline bool Service::AsyncOper::is_complete() const noexcept -{ - return m_complete; -} - -inline void Service::AsyncOper::cancel() noexcept -{ - REALM_ASSERT(m_in_use); - REALM_ASSERT(!m_canceled); - m_canceled = true; -} - -inline Service::AsyncOper::AsyncOper(std::size_t size, bool is_in_use) noexcept : - m_size{size}, - m_in_use{is_in_use} -{ -} - -inline bool Service::AsyncOper::is_canceled() const noexcept -{ - return m_canceled; -} - -inline void Service::AsyncOper::set_is_complete(bool value) noexcept -{ - REALM_ASSERT(!m_complete); - REALM_ASSERT(!value || m_in_use); - m_complete = value; -} - -template -inline void Service::AsyncOper::do_recycle_and_execute(bool orphaned, H& handler, Args&&... args) -{ - // Recycle the operation object before the handler is exceuted, such that - // the memory is available for a new post operation that might be initiated - // during the execution of the handler. - bool was_recycled = false; - try { - // We need to copy or move all arguments to be passed to the handler, - // such that there is no risk of references to the recycled operation - // object being passed to the handler (the passed arguments may be - // references to members of the recycled operation object). The easiest - // way to achive this, is by forwarding the reference arguments (passed - // to this function) to a helper function whose arguments have - // nonreference type (`Args...` rather than `Args&&...`). - // - // Note that the copying and moving of arguments may throw, and it is - // important that the operation is still recycled even if that - // happens. For that reason, copying and moving of arguments must not - // happen until we are in a scope (this scope) that catches and deals - // correctly with such exceptions. - do_recycle_and_execute_helper(orphaned, was_recycled, std::move(handler), - std::forward(args)...); // Throws - } - catch (...) { - if (!was_recycled) - do_recycle(orphaned); - throw; - } -} - -template -inline void Service::AsyncOper::do_recycle_and_execute_helper(bool orphaned, bool& was_recycled, - H handler, Args... args) -{ - do_recycle(orphaned); - was_recycled = true; - handler(std::move(args)...); // Throws -} - -inline void Service::AsyncOper::do_recycle(bool orphaned) noexcept -{ - REALM_ASSERT(in_use()); - void* addr = this; - std::size_t size = m_size; - this->~AsyncOper(); // Suicide - if (orphaned) { - delete[] static_cast(addr); - } - else { - new (addr) UnusedOper(size); - } -} - -// ---------------- Resolver ---------------- - -template class Resolver::ResolveOper : public Service::ResolveOperBase { -public: - ResolveOper(std::size_t size, Resolver& r, Query q, H handler) : - ResolveOperBase{size, r, std::move(q)}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); - REALM_ASSERT(is_canceled() || m_error_code || !m_endpoints.empty()); - bool orphaned = !m_resolver; - std::error_code ec = m_error_code; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec, std::move(m_endpoints)); // Throws - } -private: - H m_handler; -}; - -inline Resolver::Resolver(Service& service) : - m_service_impl{*service.m_impl} -{ -} - -inline Resolver::~Resolver() noexcept -{ - cancel(); -} - -inline Endpoint::List Resolver::resolve(const Query& q) -{ - std::error_code ec; - Endpoint::List list = resolve(q, ec); - if (REALM_UNLIKELY(ec)) - throw std::system_error(ec); - return list; -} - -template void Resolver::async_resolve(Query query, H handler) -{ - Service::LendersResolveOperPtr op = - Service::alloc>(m_resolve_oper, *this, - std::move(query), - std::move(handler)); // Throws - initiate_oper(std::move(op)); // Throws -} - -inline Resolver::Query::Query(std::string service_port, int init_flags) : - m_flags{init_flags}, - m_service{service_port} -{ -} - -inline Resolver::Query::Query(const StreamProtocol& prot, std::string service_port, - int init_flags) : - m_flags{init_flags}, - m_protocol{prot}, - m_service{service_port} -{ -} - -inline Resolver::Query::Query(std::string host_name, std::string service_port, int init_flags) : - m_flags{init_flags}, - m_host{host_name}, - m_service{service_port} -{ -} - -inline Resolver::Query::Query(const StreamProtocol& prot, std::string host_name, - std::string service_port, int init_flags) : - m_flags{init_flags}, - m_protocol{prot}, - m_host{host_name}, - m_service{service_port} -{ -} - -inline Resolver::Query::~Query() noexcept -{ -} - -inline int Resolver::Query::flags() const -{ - return m_flags; -} - -inline StreamProtocol Resolver::Query::protocol() const -{ - return m_protocol; -} - -inline std::string Resolver::Query::host() const -{ - return m_host; -} - -inline std::string Resolver::Query::service() const -{ - return m_service; -} - -// ---------------- SocketBase ---------------- - -inline SocketBase::SocketBase(Service& service) : - m_desc{*service.m_impl} -{ -} - -inline SocketBase::~SocketBase() noexcept -{ - close(); -} - -inline bool SocketBase::is_open() const noexcept -{ - return m_desc.is_open(); -} - -inline auto SocketBase::native_handle() const noexcept -> native_handle_type -{ - return m_desc.native_handle(); -} - -inline void SocketBase::open(const StreamProtocol& prot) -{ - std::error_code ec; - if (open(prot, ec)) - throw std::system_error(ec); -} - -inline void SocketBase::close() noexcept -{ - if (!is_open()) - return; - cancel(); - m_desc.close(); -} - -template -inline void SocketBase::get_option(O& opt) const -{ - std::error_code ec; - if (get_option(opt, ec)) - throw std::system_error(ec); -} - -template -inline std::error_code SocketBase::get_option(O& opt, std::error_code& ec) const -{ - opt.get(*this, ec); - return ec; -} - -template -inline void SocketBase::set_option(const O& opt) -{ - std::error_code ec; - if (set_option(opt, ec)) - throw std::system_error(ec); -} - -template -inline std::error_code SocketBase::set_option(const O& opt, std::error_code& ec) -{ - opt.set(*this, ec); - return ec; -} - -inline void SocketBase::bind(const Endpoint& ep) -{ - std::error_code ec; - if (bind(ep, ec)) - throw std::system_error(ec); -} - -inline Endpoint SocketBase::local_endpoint() const -{ - std::error_code ec; - Endpoint ep = local_endpoint(ec); - if (ec) - throw std::system_error(ec); - return ep; -} - -inline auto SocketBase::release_native_handle() noexcept -> native_handle_type -{ - if (is_open()) { - cancel(); - return m_desc.release(); - } - return m_desc.native_handle(); -} - -inline const StreamProtocol& SocketBase::get_protocol() const noexcept -{ - return m_protocol; -} - -template -inline SocketBase::Option::Option(T init_value) : - m_value{init_value} -{ -} - -template -inline T SocketBase::Option::value() const -{ - return m_value; -} - -template -inline void SocketBase::Option::get(const SocketBase& sock, std::error_code& ec) -{ - union { - U value; - char strut[sizeof (U) + 1]; - }; - std::size_t value_size = sizeof strut; - sock.get_option(opt_enum(opt), &value, value_size, ec); - if (!ec) { - REALM_ASSERT(value_size == sizeof value); - m_value = T(value); - } -} - -template -inline void SocketBase::Option::set(SocketBase& sock, std::error_code& ec) const -{ - U value_to_set = U(m_value); - sock.set_option(opt_enum(opt), &value_to_set, sizeof value_to_set, ec); -} - -// ---------------- Socket ---------------- - -class Socket::ConnectOperBase : public Service::IoOper { -public: - ConnectOperBase(std::size_t size, Socket& sock) noexcept : - IoOper{size}, - m_socket{&sock} - { - } - Want initiate(const Endpoint& ep) - { - REALM_ASSERT(this == m_socket->m_write_oper.get()); - if (m_socket->initiate_async_connect(ep, m_error_code)) { // Throws - set_is_complete(true); // Failure, or immediate completion - return Want::nothing; - } - return Want::write; - } - Want advance() noexcept override final - { - REALM_ASSERT(!is_complete()); - REALM_ASSERT(!is_canceled()); - REALM_ASSERT(!m_error_code); - m_socket->finalize_async_connect(m_error_code); - set_is_complete(true); - return Want::nothing; - } - void recycle() noexcept override final - { - bool orphaned = !m_socket; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_socket = nullptr; - } - Service::Descriptor& descriptor() noexcept override final - { - return m_socket->m_desc; - } -protected: - Socket* m_socket; - std::error_code m_error_code; -}; - -template class Socket::ConnectOper : public ConnectOperBase { -public: - ConnectOper(std::size_t size, Socket& sock, H handler) : - ConnectOperBase{size, sock}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); - bool orphaned = !m_socket; - std::error_code ec = m_error_code; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec); // Throws - } -private: - H m_handler; -}; - -inline Socket::Socket(Service& service) : - SocketBase{service} -{ -} - -inline Socket::Socket(Service& service, const StreamProtocol& prot, - native_handle_type native_socket) : - SocketBase{service} -{ - assign(prot, native_socket); // Throws -} - -inline Socket::~Socket() noexcept -{ -} - -inline void Socket::connect(const Endpoint& ep) -{ - std::error_code ec; - if (connect(ep, ec)) // Throws - throw std::system_error(ec); -} - -inline std::size_t Socket::read(char* buffer, std::size_t size) -{ - std::error_code ec; - read(buffer, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Socket::read(char* buffer, std::size_t size, std::error_code& ec) -{ - return StreamOps::read(*this, buffer, size, ec); // Throws -} - -inline std::size_t Socket::read(char* buffer, std::size_t size, ReadAheadBuffer& rab) -{ - std::error_code ec; - read(buffer, size, rab, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Socket::read(char* buffer, std::size_t size, ReadAheadBuffer& rab, - std::error_code& ec) -{ - int delim = std::char_traits::eof(); - return StreamOps::buffered_read(*this, buffer, size, delim, rab, ec); // Throws -} - -inline std::size_t Socket::read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab) -{ - std::error_code ec; - std::size_t n = read_until(buffer, size, delim, rab, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Socket::read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab, std::error_code& ec) -{ - int delim_2 = std::char_traits::to_int_type(delim); - return StreamOps::buffered_read(*this, buffer, size, delim_2, rab, ec); // Throws -} - -inline std::size_t Socket::write(const char* data, std::size_t size) -{ - std::error_code ec; - write(data, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Socket::write(const char* data, std::size_t size, std::error_code& ec) -{ - return StreamOps::write(*this, data, size, ec); // Throws -} - -inline std::size_t Socket::read_some(char* buffer, std::size_t size) -{ - std::error_code ec; - std::size_t n = read_some(buffer, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Socket::read_some(char* buffer, std::size_t size, std::error_code& ec) -{ - return StreamOps::read_some(*this, buffer, size, ec); // Throws -} - -inline std::size_t Socket::write_some(const char* data, std::size_t size) -{ - std::error_code ec; - std::size_t n = write_some(data, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Socket::write_some(const char* data, std::size_t size, std::error_code& ec) -{ - return StreamOps::write_some(*this, data, size, ec); // Throws -} - -template inline void Socket::async_connect(const Endpoint& ep, H handler) -{ - LendersConnectOperPtr op = - Service::alloc>(m_write_oper, *this, std::move(handler)); // Throws - m_desc.initiate_oper(std::move(op), ep); // Throws -} - -template inline void Socket::async_read(char* buffer, std::size_t size, H handler) -{ - bool is_read_some = false; - StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws -} - -template -inline void Socket::async_read(char* buffer, std::size_t size, ReadAheadBuffer& rab, H handler) -{ - int delim = std::char_traits::eof(); - StreamOps::async_buffered_read(*this, buffer, size, delim, rab, std::move(handler)); // Throws -} - -template -inline void Socket::async_read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab, H handler) -{ - int delim_2 = std::char_traits::to_int_type(delim); - StreamOps::async_buffered_read(*this, buffer, size, delim_2, rab, std::move(handler)); // Throws -} - -template inline void Socket::async_write(const char* data, std::size_t size, H handler) -{ - bool is_write_some = false; - StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws -} - -template inline void Socket::async_read_some(char* buffer, std::size_t size, H handler) -{ - bool is_read_some = true; - StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws -} - -template -inline void Socket::async_write_some(const char* data, std::size_t size, H handler) -{ - bool is_write_some = true; - StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws -} - -inline void Socket::shutdown(shutdown_type what) -{ - std::error_code ec; - if (shutdown(what, ec)) // Throws - throw std::system_error(ec); -} - -inline void Socket::assign(const StreamProtocol& prot, native_handle_type native_socket) -{ - std::error_code ec; - if (assign(prot, native_socket, ec)) // Throws - throw std::system_error(ec); -} - -inline std::error_code Socket::assign(const StreamProtocol& prot, - native_handle_type native_socket, std::error_code& ec) -{ - return do_assign(prot, native_socket, ec); // Throws -} - -inline Socket& Socket::lowest_layer() noexcept -{ - return *this; -} - -inline void Socket::do_init_read_async(std::error_code&, Want& want) noexcept -{ - want = Want::read; // Wait for read readiness before proceeding -} - -inline void Socket::do_init_write_async(std::error_code&, Want& want) noexcept -{ - want = Want::write; // Wait for write readiness before proceeding -} - -inline std::size_t Socket::do_read_some_sync(char* buffer, std::size_t size, - std::error_code& ec) noexcept -{ - return m_desc.read_some(buffer, size, ec); -} - -inline std::size_t Socket::do_write_some_sync(const char* data, std::size_t size, - std::error_code& ec) noexcept -{ - return m_desc.write_some(data, size, ec); -} - -inline std::size_t Socket::do_read_some_async(char* buffer, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - std::error_code ec_2; - std::size_t n = m_desc.read_some(buffer, size, ec_2); - bool success = (!ec_2 || ec_2 == error::resource_unavailable_try_again); - if (REALM_UNLIKELY(!success)) { - ec = ec_2; - want = Want::nothing; // Failure - return 0; - } - ec = std::error_code(); - want = Want::read; // Success - return n; -} - -inline std::size_t Socket::do_write_some_async(const char* data, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - std::error_code ec_2; - std::size_t n = m_desc.write_some(data, size, ec_2); - bool success = (!ec_2 || ec_2 == error::resource_unavailable_try_again); - if (REALM_UNLIKELY(!success)) { - ec = ec_2; - want = Want::nothing; // Failure - return 0; - } - ec = std::error_code(); - want = Want::write; // Success - return n; -} - -// ---------------- Acceptor ---------------- - -class Acceptor::AcceptOperBase : public Service::IoOper { -public: - AcceptOperBase(std::size_t size, Acceptor& a, Socket& s, Endpoint* e) : - IoOper{size}, - m_acceptor{&a}, - m_socket{s}, - m_endpoint{e} - { - } - Want initiate() - { - REALM_ASSERT(this == m_acceptor->m_read_oper.get()); - REALM_ASSERT(!is_complete()); - m_acceptor->m_desc.ensure_nonblocking_mode(); // Throws - return Want::read; - } - Want advance() noexcept override final - { - REALM_ASSERT(!is_complete()); - REALM_ASSERT(!is_canceled()); - REALM_ASSERT(!m_error_code); - REALM_ASSERT(!m_socket.is_open()); - Want want = m_acceptor->do_accept_async(m_socket, m_endpoint, m_error_code); - if (want == Want::nothing) - set_is_complete(true); // Success or failure - return want; - } - void recycle() noexcept override final - { - bool orphaned = !m_acceptor; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_acceptor = nullptr; - } - Service::Descriptor& descriptor() noexcept override final - { - return m_acceptor->m_desc; - } -protected: - Acceptor* m_acceptor; - Socket& m_socket; // May be dangling after cancellation - Endpoint* const m_endpoint; // May be dangling after cancellation - std::error_code m_error_code; -}; - -template class Acceptor::AcceptOper : public AcceptOperBase { -public: - AcceptOper(std::size_t size, Acceptor& a, Socket& s, Endpoint* e, H handler) : - AcceptOperBase{size, a, s, e}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(is_complete() || (is_canceled() && !m_error_code)); - REALM_ASSERT(is_canceled() || m_error_code || m_socket.is_open()); - bool orphaned = !m_acceptor; - std::error_code ec = m_error_code; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec); // Throws - } -private: - H m_handler; -}; - -inline Acceptor::Acceptor(Service& service) : - SocketBase{service} -{ -} - -inline Acceptor::~Acceptor() noexcept -{ -} - -inline void Acceptor::listen(int backlog) -{ - std::error_code ec; - if (listen(backlog, ec)) // Throws - throw std::system_error(ec); -} - -inline void Acceptor::accept(Socket& sock) -{ - std::error_code ec; - if (accept(sock, ec)) // Throws - throw std::system_error(ec); -} - -inline void Acceptor::accept(Socket& sock, Endpoint& ep) -{ - std::error_code ec; - if (accept(sock, ep, ec)) // Throws - throw std::system_error(ec); -} - -inline std::error_code Acceptor::accept(Socket& sock, std::error_code& ec) -{ - Endpoint* ep = nullptr; - return accept(sock, ep, ec); // Throws -} - -inline std::error_code Acceptor::accept(Socket& sock, Endpoint& ep, std::error_code& ec) -{ - return accept(sock, &ep, ec); // Throws -} - -template inline void Acceptor::async_accept(Socket& sock, H handler) -{ - Endpoint* ep = nullptr; - async_accept(sock, ep, std::move(handler)); // Throws -} - -template inline void Acceptor::async_accept(Socket& sock, Endpoint& ep, H handler) -{ - async_accept(sock, &ep, std::move(handler)); // Throws -} - -inline std::error_code Acceptor::accept(Socket& socket, Endpoint* ep, std::error_code& ec) -{ - REALM_ASSERT(!m_read_oper || !m_read_oper->in_use()); - if (REALM_UNLIKELY(socket.is_open())) - throw util::runtime_error("Socket is already open"); - m_desc.ensure_blocking_mode(); // Throws - m_desc.accept(socket.m_desc, m_protocol, ep, ec); - return ec; -} - -inline Acceptor::Want Acceptor::do_accept_async(Socket& socket, Endpoint* ep, - std::error_code& ec) noexcept -{ - std::error_code ec_2; - m_desc.accept(socket.m_desc, m_protocol, ep, ec_2); - if (ec_2 == error::resource_unavailable_try_again) - return Want::read; - ec = ec_2; - return Want::nothing; -} - -template inline void Acceptor::async_accept(Socket& sock, Endpoint* ep, H handler) -{ - if (REALM_UNLIKELY(sock.is_open())) - throw util::runtime_error("Socket is already open"); - LendersAcceptOperPtr op = Service::alloc>(m_read_oper, *this, sock, ep, - std::move(handler)); // Throws - m_desc.initiate_oper(std::move(op)); // Throws -} - -// ---------------- DeadlineTimer ---------------- - -template -class DeadlineTimer::WaitOper : public Service::WaitOperBase { -public: - WaitOper(std::size_t size, DeadlineTimer& timer, clock::time_point expiration_time, - H handler) : - Service::WaitOperBase{size, timer, expiration_time}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - bool orphaned = !m_timer; - std::error_code ec; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec); // Throws - } -private: - H m_handler; -}; - -inline DeadlineTimer::DeadlineTimer(Service& service) : - m_service_impl{*service.m_impl} -{ -} - -inline DeadlineTimer::~DeadlineTimer() noexcept -{ - cancel(); -} - -template -inline void DeadlineTimer::async_wait(std::chrono::duration delay, H handler) -{ - clock::time_point now = clock::now(); - // FIXME: This method of detecting overflow does not work. Comparison - // between distinct duration types is not overflow safe. Overflow easily - // happens in the implied conversion of arguments to the common duration - // type (std::common_type<>). - auto max_add = clock::time_point::max() - now; - if (delay > max_add) - throw util::overflow_error("Expiration time overflow"); - clock::time_point expiration_time = now + delay; - Service::LendersWaitOperPtr op = - Service::alloc>(m_wait_oper, *this, expiration_time, - std::move(handler)); // Throws - initiate_oper(std::move(op)); // Throws -} - -// ---------------- Trigger ---------------- - -template -class Trigger::ExecOper : public Service::TriggerExecOperBase { -public: - ExecOper(Service::Impl& service_impl, H handler) : - Service::TriggerExecOperBase{service_impl}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(in_use()); - // Note: Potential suicide when `self` goes out of scope - util::bind_ptr self{this, bind_ptr_base::adopt_tag{}}; - if (m_service) { - Service::reset_trigger_exec(*m_service, *this); - m_handler(); // Throws - } - } -private: - H m_handler; -}; - -template inline Trigger::Trigger(Service& service, H handler) : - m_exec_oper{new ExecOper{*service.m_impl, std::move(handler)}} // Throws -{ -} - -inline Trigger::~Trigger() noexcept -{ - if (m_exec_oper) - m_exec_oper->orphan(); -} - -inline void Trigger::trigger() noexcept -{ - REALM_ASSERT(m_exec_oper); - m_exec_oper->trigger(); -} - -// ---------------- ReadAheadBuffer ---------------- - -inline ReadAheadBuffer::ReadAheadBuffer() : - m_buffer{new char[s_size]} // Throws -{ -} - -inline void ReadAheadBuffer::clear() noexcept -{ - m_begin = nullptr; - m_end = nullptr; -} - -inline bool ReadAheadBuffer::empty() const noexcept -{ - return (m_begin == m_end); -} - -template inline void ReadAheadBuffer::refill_sync(S& stream, std::error_code& ec) noexcept -{ - char* buffer = m_buffer.get(); - std::size_t size = s_size; - static_assert(noexcept(stream.do_read_some_sync(buffer, size, ec)), ""); - std::size_t n = stream.do_read_some_sync(buffer, size, ec); - if (REALM_UNLIKELY(n == 0)) - return; - REALM_ASSERT(!ec); - REALM_ASSERT(n <= size); - m_begin = m_buffer.get(); - m_end = m_begin + n; -} - -template -inline bool ReadAheadBuffer::refill_async(S& stream, std::error_code& ec, Want& want) noexcept -{ - char* buffer = m_buffer.get(); - std::size_t size = s_size; - static_assert(noexcept(stream.do_read_some_async(buffer, size, ec, want)), ""); - std::size_t n = stream.do_read_some_async(buffer, size, ec, want); - if (n == 0) - return false; - REALM_ASSERT(!ec); - REALM_ASSERT(n <= size); - m_begin = m_buffer.get(); - m_end = m_begin + n; - return true; -} - -} // namespace network -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_NETWORK_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/network_ssl.hpp b/Lesson14/Pods/Realm/include/core/realm/util/network_ssl.hpp deleted file mode 100644 index 3284bf8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/network_ssl.hpp +++ /dev/null @@ -1,1378 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_NETWORK_SSL_HPP -#define REALM_UTIL_NETWORK_SSL_HPP - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if REALM_HAVE_OPENSSL -# include -# include -#elif REALM_HAVE_SECURE_TRANSPORT -# include -# include -# include - -#define REALM_HAVE_KEYCHAIN_APIS (TARGET_OS_MAC && !TARGET_OS_IPHONE) - -#endif - -// FIXME: Add necessary support for customizing the SSL server and client -// configurations. - -// FIXME: Currently, the synchronous SSL operations (handshake, read, write, -// shutdown) do not automatically retry if the underlying SSL function returns -// with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. This normally never -// happens, but it can happen according to the man pages, but in the case of -// SSL_write(), only when a renegotiation has to take place. It is likely that -// the solution is to to wrap the SSL calls inside a loop, such that they keep -// retrying until they succeed, however, such a simple scheme will fail if the -// synchronous operations were to be used with an underlying TCP socket in -// nonblocking mode. Currently, the underlying TCP socket is always in blocking -// mode when performing synchronous operations, but that may continue to be the -// case in teh future. - - -namespace realm { -namespace util { -namespace network { -namespace ssl { - -enum class Errors { - certificate_rejected = 1, -}; - -class ErrorCategory : public std::error_category { -public: - const char* name() const noexcept override final; - std::string message(int) const override final; - bool equivalent(const std::error_code&, int) const noexcept override final; -}; - -/// The error category associated with \ref Errors. The name of this category is -/// `realm.util.network.ssl`. -extern ErrorCategory error_category; - -inline std::error_code make_error_code(Errors err) -{ - return std::error_code(int(err), error_category); -} - -inline std::error_condition make_error_condition(Errors err) -{ - return std::error_condition(int(err), error_category); -} - -} // namespace ssl -} // namespace network -} // namespace util -} // namespace realm - -namespace std { - -template<> class is_error_condition_enum { -public: - static const bool value = true; -}; - -} // namespace std - -namespace realm { -namespace util { -namespace network { - -class OpensslErrorCategory : public std::error_category { -public: - const char* name() const noexcept override final; - std::string message(int) const override final; -}; - -/// The error category associated with error codes produced by the third-party -/// library, OpenSSL. The name of this category is `openssl`. -extern OpensslErrorCategory openssl_error_category; - -class SecureTransportErrorCategory : public std::error_category { -public: - const char* name() const noexcept override final; - std::string message(int) const override final; -}; - -/// The error category associated with error codes produced by Apple's -/// SecureTransport library. The name of this category is `securetransport`. -extern SecureTransportErrorCategory secure_transport_error_category; - - -namespace ssl { - -class ProtocolNotSupported; - - -/// `VerifyMode::none` corresponds to OpenSSL's `SSL_VERIFY_NONE`, and -/// `VerifyMode::peer` to `SSL_VERIFY_PEER`. -enum class VerifyMode { none, peer }; - - -class Context { -public: - Context(); - ~Context() noexcept; - - /// File must be in PEM format. Corresponds to OpenSSL's - /// `SSL_CTX_use_certificate_chain_file()`. - void use_certificate_chain_file(const std::string& path); - - /// File must be in PEM format. Corresponds to OpenSSL's - /// `SSL_CTX_use_PrivateKey_file()`. - void use_private_key_file(const std::string& path); - - /// Calling use_default_verify() will make a client use the device - /// default certificates for server verification. For OpenSSL, - /// use_default_verify() corresponds to - /// SSL_CTX_set_default_verify_paths(SSL_CTX*); - void use_default_verify(); - - /// The verify file is a PEM file containing trust certificates that the - /// client will use to verify the server certificate. If use_verify_file() - /// is not called, the default device trust store will be used. - /// use_verify_file() corresponds roughly to OpenSSL's - /// SSL_CTX_load_verify_locations(). - void use_verify_file(const std::string& path); - -private: - void ssl_init(); - void ssl_destroy() noexcept; - void ssl_use_certificate_chain_file(const std::string& path, std::error_code&); - void ssl_use_private_key_file(const std::string& path, std::error_code&); - void ssl_use_default_verify(std::error_code&); - void ssl_use_verify_file(const std::string& path, std::error_code&); - -#if REALM_HAVE_OPENSSL - SSL_CTX* m_ssl_ctx = nullptr; - -#elif REALM_HAVE_SECURE_TRANSPORT - -#if REALM_HAVE_KEYCHAIN_APIS - std::error_code open_temporary_keychain_if_needed(); - std::error_code update_identity_if_needed(); - - util::CFPtr m_keychain; - std::string m_keychain_path; - - util::CFPtr m_certificate; - util::CFPtr m_private_key; - util::CFPtr m_identity; - - util::CFPtr m_certificate_chain; - -#else - using SecKeychainRef = std::nullptr_t; - -#endif // REALM_HAVE_KEYCHAIN_APIS - static util::CFPtr load_pem_file(const std::string& path, SecKeychainRef, std::error_code&); - - util::CFPtr m_trust_anchors; - util::CFPtr m_pinned_certificate; - -#endif - - friend class Stream; -}; - - -/// Switching between synchronous and asynchronous operations is allowed, but -/// only in a nonoverlapping fashion. That is, a synchronous operation is not -/// allowed to run concurrently with an asynchronous one on the same -/// stream. Note that an asynchronous operation is considered to be running -/// until its completion handler starts executing. -class Stream { -public: - using port_type = util::network::Endpoint::port_type; - using SSLVerifyCallback = bool(const std::string& server_address, - port_type server_port, - const char* pem_data, - size_t pem_size, - int preverify_ok, - int depth); - - enum HandshakeType { client, server }; - - util::Logger* logger = nullptr; - - Stream(Socket&, Context&, HandshakeType); - ~Stream() noexcept; - - /// \brief set_logger() set a logger for the stream class. If - /// set_logger() is not called, no logging will take place by - /// the Stream class. - void set_logger(util::Logger*); - - /// \brief Set the certificate verification mode for this SSL stream. - /// - /// Corresponds to OpenSSL's `SSL_set_verify()` with null passed as - /// `verify_callback`. - /// - /// Clients should always set it to `VerifyMode::peer`, such that the client - /// verifies the servers certificate. Servers should only set it to - /// `VerifyMode::peer` if they want to request a certificate from the - /// client. When testing with self-signed certificates, it is necessary to - /// set it to `VerifyMode::none` for clients too. - /// - /// It is an error if this function is called after the handshake operation - /// is initiated. - /// - /// The default verify mode is `VerifyMode::none`. - void set_verify_mode(VerifyMode); - - /// \brief Check the certificate against a host_name. - /// - /// set_check_host() includes a host name check in the - /// certificate verification. It is typically used by clients - /// to secure that the received certificate has a common name - /// or subject alternative name that matches \param host_name. - /// - /// set_check_host() is only useful if verify_mode is - /// set to VerifyMode::peer. - void set_check_host(std::string host_name); - const std::string& get_host_name(); - - /// get_server_port() and set_server_port() are getter and setter for - /// the server port. They are only used by the verify callback function - /// below. - port_type get_server_port(); - void set_server_port(port_type server_port); - - /// If use_verify_callback() is called, the SSL certificate chain of - /// the server is presented to callback, one certificate at a time. - /// The SSL connection is accepted if and only if callback returns true - /// for all certificates. - /// The signature of \param callback is - /// - /// bool(const std::string& server_address, - /// port_type server_port, - /// const char* pem_data, - /// size_t pem_size, - /// int preverify_ok, - /// int depth); - // - /// server address and server_port is the address and port of the server - /// that a SSL connection is being established to. - /// pem_data is the certificate of length pem_size in - /// the PEM format. preverify_ok is OpenSSL's preverification of the - /// certificate. preverify_ok is either 0, or 1. If preverify_ok is 1, - /// OpenSSL has accepted the certificate and it will generally be safe - /// to trust that certificate. depth represents the position of the - /// certificate in the certificate chain sent by the server. depth = 0 - /// represents the actual server certificate that should contain the - /// host name(server address) of the server. The highest depth is the - /// root certificate. - /// The callback function will receive the certificates starting from - /// the root certificate and moving down the chain until it reaches the - /// server's own certificate with a host name. The depth of the last - /// certificate is 0. The depth of the first certificate is chain - /// length - 1. - /// - /// The return value of the callback function decides whether the - /// client accepts the certificate. If the return value is false, the - /// processing of the certificate chain is interrupted and the SSL - /// connection is rejected. If the return value is true, the verification - /// process continues. If the callback function returns true for all - /// presented certificates including the depth == 0 certificate, the - /// SSL connection is accepted. - /// - /// A recommended way of using the callback function is to return true - /// if preverify_ok = 1 and depth > 0, - /// always check the host name if depth = 0, - /// and use an independent verification step if preverify_ok = 0. - /// - /// Another possible way of using the callback is to collect all the - /// certificates until depth = 0, and present the entire chain for - /// independent verification. - void use_verify_callback(const std::function& callback); - -#ifdef REALM_INCLUDE_CERTS - /// use_included_certificates() loads a set of certificates that are - /// included in the header file src/realm/noinst/root_certs.hpp. By using - /// the included certificates, the client can verify a server in the case - /// where the relevant certificate cannot be found, or is absent, in the - /// system trust store. This function is only implemented for OpenSSL. - void use_included_certificates(); -#endif - - /// @{ - /// - /// Read and write operations behave the same way as they do on \ref - /// network::Socket, except that after cancellation of asynchronous - /// operations (`lowest_layer().cancel()`), the stream may be left in a bad - /// state (see below). - /// - /// The handshake operation must complete successfully before any read, - /// write, or shutdown operations are performed. - /// - /// The shutdown operation sends the shutdown alert to the peer, and - /// returns/completes as soon as the alert message has been written to the - /// underlying socket. It is an error if the shutdown operation is initiated - /// while there are read or write operations in progress. No read or write - /// operations are allowed to be initiated after the shutdown operation has - /// been initiated. When the shutdown operation has completed, it is safe to - /// close the underlying socket (`lowest_layer().close()`). - /// - /// If a write operation is executing while, or is initiated after a close - /// notify alert is received from the remote peer, the write operation will - /// fail with error::broken_pipe. - /// - /// Callback functions for async read and write operations must take two - /// arguments, an std::error_code(), and an integer of a type std::size_t - /// indicating the number of transferred bytes (other types are allowed as - /// long as implicit conversion can take place). - /// - /// Callback functions for async handshake and shutdown operations must take - /// a single argument of type std::error_code() (other types are allowed as - /// long as implicit conversion can take place). - /// - /// Resumption of stream operation after cancellation of asynchronous - /// operations is not supported (does not work). Since the shutdown - /// operation involves network communication, that operation is also not - /// allowed after cancellation. The only thing that is allowed, is to - /// destroy the stream object. Other stream objects are not affected. - - void handshake(); - std::error_code handshake(std::error_code&); - - std::size_t read(char* buffer, std::size_t size); - std::size_t read(char* buffer, std::size_t size, std::error_code& ec); - std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&); - std::size_t read(char* buffer, std::size_t size, ReadAheadBuffer&, std::error_code& ec); - std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&); - std::size_t read_until(char* buffer, std::size_t size, char delim, ReadAheadBuffer&, - std::error_code& ec); - - std::size_t write(const char* data, std::size_t size); - std::size_t write(const char* data, std::size_t size, std::error_code& ec); - - std::size_t read_some(char* buffer, std::size_t size); - std::size_t read_some(char* buffer, std::size_t size, std::error_code&); - - std::size_t write_some(const char* data, std::size_t size); - std::size_t write_some(const char* data, std::size_t size, std::error_code&); - - void shutdown(); - std::error_code shutdown(std::error_code&); - - template void async_handshake(H handler); - - template void async_read(char* buffer, std::size_t size, H handler); - template void async_read(char* buffer, std::size_t size, ReadAheadBuffer&, H handler); - template void async_read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer&, H handler); - - template void async_write(const char* data, std::size_t size, H handler); - - template void async_read_some(char* buffer, std::size_t size, H handler); - - template void async_write_some(const char* data, std::size_t size, H handler); - - template void async_shutdown(H handler); - - /// @} - - /// Returns a reference to the underlying socket. - Socket& lowest_layer() noexcept; - -private: - using Want = Service::Want; - using StreamOps = Service::BasicStreamOps; - - class HandshakeOperBase; - template class HandshakeOper; - class ShutdownOperBase; - template class ShutdownOper; - - using LendersHandshakeOperPtr = std::unique_ptr; - using LendersShutdownOperPtr = std::unique_ptr; - - Socket& m_tcp_socket; - Context& m_ssl_context; - const HandshakeType m_handshake_type; - - // The host name that the certificate should be checked against. - // The host name is called server address in the certificate verify - // callback function. - std::string m_host_name; - - // The port of the server which is used in the certificate verify - // callback function. - port_type m_server_port; - - // The callback for certificate verification and an - // opaque argument that will be supplied to the callback. - const std::function* m_ssl_verify_callback = nullptr; - - bool m_valid_certificate_in_chain = false; - - - // See Service::BasicStreamOps for details on these these 6 functions. - void do_init_read_async(std::error_code&, Want&) noexcept; - void do_init_write_async(std::error_code&, Want&) noexcept; - std::size_t do_read_some_sync(char* buffer, std::size_t size, - std::error_code&) noexcept; - std::size_t do_write_some_sync(const char* data, std::size_t size, - std::error_code&) noexcept; - std::size_t do_read_some_async(char* buffer, std::size_t size, - std::error_code&, Want&) noexcept; - std::size_t do_write_some_async(const char* data, std::size_t size, - std::error_code&, Want&) noexcept; - - // The meaning of the arguments and return values of ssl_read() and - // ssl_write() are identical to do_read_some_async() and - // do_write_some_async() respectively, except that when the return value is - // nonzero, `want` is always `Want::nothing`, meaning that after bytes have - // been transferred, ssl_read() and ssl_write() must be called again to - // figure out whether it is necessary to wait for read or write readiness. - // - // The first invocation of ssl_shutdown() must send the shutdown alert to - // the peer. In blocking mode it must wait until the alert has been sent. In - // nonblocking mode, it must keep setting `want` to something other than - // `Want::nothing` until the alert has been sent. When the shutdown alert - // has been sent, it is safe to shut down the sending side of the underlying - // socket. On failure, ssl_shutdown() must set `ec` to something different - // than `std::error_code()` and return false. On success, it must set `ec` - // to `std::error_code()`, and return true if a shutdown alert from the peer - // has already been received, otherwise it must return false. When it sets - // `want` to something other than `Want::nothing`, it must set `ec` to - // `std::error_code()` and return false. - // - // The second invocation of ssl_shutdown() (after the first invocation - // completed) must wait for reception on the peers shutdown alert. - // - // Note: The semantics around the second invocation of shutdown is currently - // unused by the higher level API, because of a requirement of compatibility - // with Apple's Secure Transport API. - void ssl_init(); - void ssl_destroy() noexcept; - void ssl_set_verify_mode(VerifyMode, std::error_code&); - void ssl_set_check_host(std::string, std::error_code&); - void ssl_use_verify_callback(const std::function&, std::error_code&); - void ssl_use_included_certificates(std::error_code&); - - void ssl_handshake(std::error_code&, Want& want) noexcept; - bool ssl_shutdown(std::error_code& ec, Want& want) noexcept; - std::size_t ssl_read(char* buffer, std::size_t size, - std::error_code&, Want& want) noexcept; - std::size_t ssl_write(const char* data, std::size_t size, - std::error_code&, Want& want) noexcept; - -#if REALM_HAVE_OPENSSL - class BioMethod; - static BioMethod s_bio_method; - SSL* m_ssl = nullptr; - std::error_code m_bio_error_code; - - int m_ssl_index = -1; - - template - std::size_t ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept; - - int do_ssl_accept() noexcept; - int do_ssl_connect() noexcept; - int do_ssl_shutdown() noexcept; - int do_ssl_read(char* buffer, std::size_t size) noexcept; - int do_ssl_write(const char* data, std::size_t size) noexcept; - - static int bio_write(BIO*, const char*, int) noexcept; - static int bio_read(BIO*, char*, int) noexcept; - static int bio_puts(BIO*, const char*) noexcept; - static long bio_ctrl(BIO*, int, long, void*) noexcept; - static int bio_create(BIO*) noexcept; - static int bio_destroy(BIO*) noexcept; - - // verify_callback_using_hostname is used as an argument to OpenSSL's SSL_set_verify function. - // verify_callback_using_hostname verifies that the certificate is valid and contains - // m_host_name as a Common Name or Subject Alternative Name. - static int verify_callback_using_hostname(int preverify_ok, X509_STORE_CTX *ctx) noexcept; - - // verify_callback_using_delegate() is also used as an argument to OpenSSL's set_verify_function. - // verify_callback_using_delegate() calls out to the user supplied verify callback. - static int verify_callback_using_delegate(int preverify_ok, X509_STORE_CTX *ctx) noexcept; - - // verify_callback_using_root_certs is used by OpenSSL to handle certificate verification - // using the included root certifictes. - static int verify_callback_using_root_certs(int preverify_ok, X509_STORE_CTX *ctx); -#elif REALM_HAVE_SECURE_TRANSPORT - util::CFPtr m_ssl; - VerifyMode m_verify_mode = VerifyMode::none; - - enum class BlockingOperation { - read, - write, - }; - util::Optional m_last_operation; - - // Details of the underlying I/O error that lead to errSecIO being returned - // from a SecureTransport function. - std::error_code m_last_error; - - // The number of bytes accepted by SSWrite() but not yet confirmed to be - // written to the underlying socket. - std::size_t m_num_partially_written_bytes = 0; - - template - std::size_t ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept; - - std::pair do_ssl_handshake() noexcept; - std::pair do_ssl_shutdown() noexcept; - std::pair do_ssl_read(char* buffer, std::size_t size) noexcept; - std::pair do_ssl_write(const char* data, std::size_t size) noexcept; - - static OSStatus tcp_read(SSLConnectionRef, void*, std::size_t* length) noexcept; - static OSStatus tcp_write(SSLConnectionRef, const void*, std::size_t* length) noexcept; - - OSStatus tcp_read(void*, std::size_t* length) noexcept; - OSStatus tcp_write(const void*, std::size_t* length) noexcept; - - OSStatus verify_peer() noexcept; -#endif - - friend class Service::BasicStreamOps; - friend class network::ReadAheadBuffer; -}; - - -// Implementation - -class ProtocolNotSupported : public std::exception { -public: - const char* what() const noexcept override final; -}; - -inline Context::Context() -{ - ssl_init(); // Throws -} - -inline Context::~Context() noexcept -{ - ssl_destroy(); -} - -inline void Context::use_certificate_chain_file(const std::string& path) -{ - std::error_code ec; - ssl_use_certificate_chain_file(path, ec); // Throws - if (ec) - throw std::system_error(ec); -} - -inline void Context::use_private_key_file(const std::string& path) -{ - std::error_code ec; - ssl_use_private_key_file(path, ec); // Throws - if (ec) - throw std::system_error(ec); -} - -inline void Context::use_default_verify() -{ - std::error_code ec; - ssl_use_default_verify(ec); - if (ec) - throw std::system_error(ec); -} - -inline void Context::use_verify_file(const std::string& path) -{ - std::error_code ec; - ssl_use_verify_file(path, ec); - if (ec) { - throw std::system_error(ec); - } -} - -class Stream::HandshakeOperBase : public Service::IoOper { -public: - HandshakeOperBase(std::size_t size, Stream& stream) : - IoOper{size}, - m_stream{&stream} - { - } - Want initiate() - { - REALM_ASSERT(this == m_stream->m_tcp_socket.m_read_oper.get()); - REALM_ASSERT(!is_complete()); - m_stream->m_tcp_socket.m_desc.ensure_nonblocking_mode(); // Throws - return advance(); - } - Want advance() noexcept override final - { - REALM_ASSERT(!is_complete()); - REALM_ASSERT(!is_canceled()); - REALM_ASSERT(!m_error_code); - Want want = Want::nothing; - m_stream->ssl_handshake(m_error_code, want); - set_is_complete(want == Want::nothing); - return want; - } - void recycle() noexcept override final - { - bool orphaned = !m_stream; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_stream = nullptr; - } - Service::Descriptor& descriptor() noexcept override final - { - return m_stream->lowest_layer().m_desc; - } -protected: - Stream* m_stream; - std::error_code m_error_code; -}; - -template class Stream::HandshakeOper : public HandshakeOperBase { -public: - HandshakeOper(std::size_t size, Stream& stream, H handler) : - HandshakeOperBase{size, stream}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(is_complete() || is_canceled()); - bool orphaned = !m_stream; - std::error_code ec = m_error_code; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec); // Throws - } -private: - H m_handler; -}; - -class Stream::ShutdownOperBase : public Service::IoOper { -public: - ShutdownOperBase(std::size_t size, Stream& stream) : - IoOper{size}, - m_stream{&stream} - { - } - Want initiate() - { - REALM_ASSERT(this == m_stream->m_tcp_socket.m_write_oper.get()); - REALM_ASSERT(!is_complete()); - m_stream->m_tcp_socket.m_desc.ensure_nonblocking_mode(); // Throws - return advance(); - } - Want advance() noexcept override final - { - REALM_ASSERT(!is_complete()); - REALM_ASSERT(!is_canceled()); - REALM_ASSERT(!m_error_code); - Want want = Want::nothing; - m_stream->ssl_shutdown(m_error_code, want); - if (want == Want::nothing) - set_is_complete(true); - return want; - } - void recycle() noexcept override final - { - bool orphaned = !m_stream; - REALM_ASSERT(orphaned); - // Note: do_recycle() commits suicide. - do_recycle(orphaned); - } - void orphan() noexcept override final - { - m_stream = nullptr; - } - Service::Descriptor& descriptor() noexcept override final - { - return m_stream->lowest_layer().m_desc; - } -protected: - Stream* m_stream; - std::error_code m_error_code; -}; - -template class Stream::ShutdownOper : public ShutdownOperBase { -public: - ShutdownOper(std::size_t size, Stream& stream, H handler) : - ShutdownOperBase{size, stream}, - m_handler{std::move(handler)} - { - } - void recycle_and_execute() override final - { - REALM_ASSERT(is_complete() || is_canceled()); - bool orphaned = !m_stream; - std::error_code ec = m_error_code; - if (is_canceled()) - ec = error::operation_aborted; - // Note: do_recycle_and_execute() commits suicide. - do_recycle_and_execute(orphaned, m_handler, ec); // Throws - } -private: - H m_handler; -}; - -inline Stream::Stream(Socket& socket, Context& context, HandshakeType type) : - m_tcp_socket{socket}, - m_ssl_context{context}, - m_handshake_type{type} -{ - ssl_init(); // Throws -} - -inline Stream::~Stream() noexcept -{ - m_tcp_socket.cancel(); - ssl_destroy(); -} - -inline void Stream::set_logger(util::Logger* logger) -{ - this->logger = logger; -} - -inline void Stream::set_verify_mode(VerifyMode mode) -{ - std::error_code ec; - ssl_set_verify_mode(mode, ec); // Throws - if (ec) - throw std::system_error(ec); -} - -inline void Stream::set_check_host(std::string host_name) -{ - m_host_name = host_name; - std::error_code ec; - ssl_set_check_host(host_name, ec); - if (ec) - throw std::system_error(ec); -} - -inline const std::string& Stream::get_host_name() -{ - return m_host_name; -} - -inline Stream::port_type Stream::get_server_port() -{ - return m_server_port; -} - -inline void Stream::set_server_port(port_type server_port) -{ - m_server_port = server_port; -} - -inline void Stream::use_verify_callback(const std::function& callback) -{ - std::error_code ec; - ssl_use_verify_callback(callback, ec); // Throws - if (ec) - throw std::system_error(ec); -} - -#ifdef REALM_INCLUDE_CERTS -inline void Stream::use_included_certificates() -{ - std::error_code ec; - ssl_use_included_certificates(ec); // Throws - if (ec) - throw std::system_error(ec); -} -#endif - -inline void Stream::handshake() -{ - std::error_code ec; - if (handshake(ec)) // Throws - throw std::system_error(ec); -} - -inline std::size_t Stream::read(char* buffer, std::size_t size) -{ - std::error_code ec; - read(buffer, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Stream::read(char* buffer, std::size_t size, std::error_code& ec) -{ - return StreamOps::read(*this, buffer, size, ec); // Throws -} - -inline std::size_t Stream::read(char* buffer, std::size_t size, ReadAheadBuffer& rab) -{ - std::error_code ec; - read(buffer, size, rab, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Stream::read(char* buffer, std::size_t size, ReadAheadBuffer& rab, - std::error_code& ec) -{ - int delim = std::char_traits::eof(); - return StreamOps::buffered_read(*this, buffer, size, delim, rab, ec); // Throws -} - -inline std::size_t Stream::read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab) -{ - std::error_code ec; - std::size_t n = read_until(buffer, size, delim, rab, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Stream::read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab, std::error_code& ec) -{ - int delim_2 = std::char_traits::to_int_type(delim); - return StreamOps::buffered_read(*this, buffer, size, delim_2, rab, ec); // Throws -} - -inline std::size_t Stream::write(const char* data, std::size_t size) -{ - std::error_code ec; - write(data, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return size; -} - -inline std::size_t Stream::write(const char* data, std::size_t size, std::error_code& ec) -{ - return StreamOps::write(*this, data, size, ec); // Throws -} - -inline std::size_t Stream::read_some(char* buffer, std::size_t size) -{ - std::error_code ec; - std::size_t n = read_some(buffer, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Stream::read_some(char* buffer, std::size_t size, std::error_code& ec) -{ - return StreamOps::read_some(*this, buffer, size, ec); // Throws -} - -inline std::size_t Stream::write_some(const char* data, std::size_t size) -{ - std::error_code ec; - std::size_t n = write_some(data, size, ec); // Throws - if (ec) - throw std::system_error(ec); - return n; -} - -inline std::size_t Stream::write_some(const char* data, std::size_t size, std::error_code& ec) -{ - return StreamOps::write_some(*this, data, size, ec); // Throws -} - -inline void Stream::shutdown() -{ - std::error_code ec; - if (shutdown(ec)) // Throws - throw std::system_error(ec); -} - -template inline void Stream::async_handshake(H handler) -{ - LendersHandshakeOperPtr op = - Service::alloc>(m_tcp_socket.m_read_oper, *this, - std::move(handler)); // Throws - m_tcp_socket.m_desc.initiate_oper(std::move(op)); // Throws -} - -template inline void Stream::async_read(char* buffer, std::size_t size, H handler) -{ - bool is_read_some = false; - StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws -} - -template -inline void Stream::async_read(char* buffer, std::size_t size, ReadAheadBuffer& rab, H handler) -{ - int delim = std::char_traits::eof(); - StreamOps::async_buffered_read(*this, buffer, size, delim, rab, std::move(handler)); // Throws -} - -template -inline void Stream::async_read_until(char* buffer, std::size_t size, char delim, - ReadAheadBuffer& rab, H handler) -{ - int delim_2 = std::char_traits::to_int_type(delim); - StreamOps::async_buffered_read(*this, buffer, size, delim_2, rab, std::move(handler)); // Throws -} - -template inline void Stream::async_write(const char* data, std::size_t size, H handler) -{ - bool is_write_some = false; - StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws -} - -template inline void Stream::async_read_some(char* buffer, std::size_t size, H handler) -{ - bool is_read_some = true; - StreamOps::async_read(*this, buffer, size, is_read_some, std::move(handler)); // Throws -} - -template inline void Stream::async_write_some(const char* data, std::size_t size, H handler) -{ - bool is_write_some = true; - StreamOps::async_write(*this, data, size, is_write_some, std::move(handler)); // Throws -} - -template inline void Stream::async_shutdown(H handler) -{ - LendersShutdownOperPtr op = - Service::alloc>(m_tcp_socket.m_write_oper, *this, - std::move(handler)); // Throws - m_tcp_socket.m_desc.initiate_oper(std::move(op)); // Throws -} - -inline void Stream::do_init_read_async(std::error_code&, Want& want) noexcept -{ - want = Want::nothing; // Proceed immediately unless there is an error -} - -inline void Stream::do_init_write_async(std::error_code&, Want& want) noexcept -{ - want = Want::nothing; // Proceed immediately unless there is an error -} - -inline std::size_t Stream::do_read_some_sync(char* buffer, std::size_t size, - std::error_code& ec) noexcept -{ - Want want = Want::nothing; - std::size_t n = do_read_some_async(buffer, size, ec, want); - if (n == 0 && want != Want::nothing) - ec = error::resource_unavailable_try_again; - return n; -} - -inline std::size_t Stream::do_write_some_sync(const char* data, std::size_t size, - std::error_code& ec) noexcept -{ - Want want = Want::nothing; - std::size_t n = do_write_some_async(data, size, ec, want); - if (n == 0 && want != Want::nothing) - ec = error::resource_unavailable_try_again; - return n; -} - -inline std::size_t Stream::do_read_some_async(char* buffer, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - return ssl_read(buffer, size, ec, want); -} - -inline std::size_t Stream::do_write_some_async(const char* data, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - return ssl_write(data, size, ec, want); -} - -inline Socket& Stream::lowest_layer() noexcept -{ - return m_tcp_socket; -} - - -#if REALM_HAVE_OPENSSL - -inline void Stream::ssl_handshake(std::error_code& ec, Want& want) noexcept -{ - auto perform = [this]() noexcept { - switch (m_handshake_type) { - case client: - return do_ssl_connect(); - case server: - return do_ssl_accept(); - } - REALM_ASSERT(false); - return 0; - }; - std::size_t n = ssl_perform(std::move(perform), ec, want); - REALM_ASSERT(n == 0 || n == 1); - if (want == Want::nothing && n == 0 && !ec) { - // End of input on TCP socket - ec = MiscExtErrors::premature_end_of_input; - } -} - -inline std::size_t Stream::ssl_read(char* buffer, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - auto perform = [this, buffer, size]() noexcept { - return do_ssl_read(buffer, size); - }; - std::size_t n = ssl_perform(std::move(perform), ec, want); - if (want == Want::nothing && n == 0 && !ec) { - // End of input on TCP socket - if (SSL_get_shutdown(m_ssl) & SSL_RECEIVED_SHUTDOWN) { - ec = MiscExtErrors::end_of_input; - } - else { - ec = MiscExtErrors::premature_end_of_input; - } - } - return n; -} - -inline std::size_t Stream::ssl_write(const char* data, std::size_t size, - std::error_code& ec, Want& want) noexcept -{ - // While OpenSSL is able to continue writing after we have received the - // close notify alert fro the remote peer, Apple's Secure Transport API is - // not, so to achieve common behaviour, we make sure that any such attempt - // will result in an `error::broken_pipe` error. - if ((SSL_get_shutdown(m_ssl) & SSL_RECEIVED_SHUTDOWN) != 0) { - ec = error::broken_pipe; - want = Want::nothing; - return 0; - } - auto perform = [this, data, size]() noexcept { - return do_ssl_write(data, size); - }; - std::size_t n = ssl_perform(std::move(perform), ec, want); - if (want == Want::nothing && n == 0 && !ec) { - // End of input on TCP socket - ec = MiscExtErrors::premature_end_of_input; - } - return n; -} - -inline bool Stream::ssl_shutdown(std::error_code& ec, Want& want) noexcept -{ - auto perform = [this]() noexcept { - return do_ssl_shutdown(); - }; - std::size_t n = ssl_perform(std::move(perform), ec, want); - REALM_ASSERT(n == 0 || n == 1); - if (want == Want::nothing && n == 0 && !ec) { - // The first invocation of SSL_shutdown() does not signal completion - // until the shutdown alert has been sent to the peer, or an error - // occurred (does not wait for acknowledgment). - // - // The second invocation (after a completed first invocation) does not - // signal completion until the peers shutdown alert has been received, - // or an error occurred. - // - // It is believed that: - // - // If this is the first time SSL_shutdown() is called, and - // `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` evaluates to nonzero, then a - // zero return value means "partial success" (shutdown alert was sent, - // but the peers shutdown alert was not yet received), and 1 means "full - // success" (peers shutdown alert has already been received). - // - // If this is the first time SSL_shutdown() is called, and - // `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` valuates to zero, then a - // zero return value means "premature end of input", and 1 is supposedly - // not a possibility. - // - // If this is the second time SSL_shutdown() is called (after the first - // call has returned zero), then a zero return value means "premature - // end of input", and 1 means "full success" (peers shutdown alert has - // now been received). - if ((SSL_get_shutdown(m_ssl) & SSL_SENT_SHUTDOWN) == 0) - ec = MiscExtErrors::premature_end_of_input; - } - return (n > 0); -} - -// Provides a homogeneous, and mostly quirks-free interface across the OpenSSL -// operations (handshake, read, write, shutdown). -// -// First of all, if the operation remains incomplete (neither successfully -// completed, nor failed), ssl_perform() will set `ec` to `std::system_error()`, -// `want` to something other than `Want::nothing`, and return zero. Note that -// read and write operations are partial in the sense that they do not need to -// read or write everything before completing successfully. They only need to -// read or write at least one byte to complete successfully. -// -// Such a situation will normally only happen when the underlying TCP socket is -// in nonblocking mode, and the read/write requirements of the operation could -// not be immediately accommodated. However, as is noted in the SSL_write() man -// page, it can also happen in blocking mode (at least while writing). -// -// If an error occurred, ssl_perform() will set `ec` to something other than -// `std::system_error()`, `want` to `Want::nothing`, and return 0. -// -// If no error occurred, and the operation completed (`!ec && want == -// Want::nothing`), then the return value indicates the outcome of the -// operation. -// -// In general, a nonzero value means "full" success, and a zero value means -// "partial" success, however, a zero result can also generally mean "premature -// end of input" / "unclean protocol termination". -// -// Assuming there is no premature end of input, then for reads and writes, the -// returned value is the number of transferred bytes. Zero for read on end of -// input. Never zero for write. For handshake it is always 1. For shutdown it is -// 1 if the peer shutdown alert was already received, otherwise it is zero. -// -// ssl_read() should use `SSL_get_shutdown() & SSL_RECEIVED_SHUTDOWN` to -// distinguish between the two possible meanings of zero. -// -// ssl_shutdown() should use `SSL_get_shutdown() & SSL_SENT_SHUTDOWN` to -// distinguish between the two possible meanings of zero. -template -std::size_t Stream::ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept -{ - ERR_clear_error(); - m_bio_error_code = std::error_code(); // Success - int ret = oper(); - int ssl_error = SSL_get_error(m_ssl, ret); - int sys_error = int(ERR_get_error()); - - // Guaranteed by the documentation of SSL_get_error() - REALM_ASSERT((ret > 0) == (ssl_error == SSL_ERROR_NONE)); - - REALM_ASSERT(!m_bio_error_code || ssl_error == SSL_ERROR_SYSCALL); - - // Judging from various comments in the man pages, and from experience with - // the API, it seems that, - // - // ret=0, ssl_error=SSL_ERROR_SYSCALL, sys_error=0 - // - // is supposed to be an indicator of "premature end of input" / "unclean - // protocol termination", while - // - // ret=0, ssl_error=SSL_ERROR_ZERO_RETURN - // - // is supposed to be an indicator of the following success conditions: - // - // - Mature end of input / clean protocol termination. - // - // - Successful transmission of the shutdown alert, but no prior reception - // of shutdown alert from peer. - // - // Unfortunately, as is also remarked in various places in the man pages, - // those two success conditions may actually result in `ret=0, - // ssl_error=SSL_ERROR_SYSCALL, sys_error=0` too, and it seems that they - // almost always do. - // - // This means that we cannot properly discriminate between these conditions - // in ssl_perform(), and will have to defer to the caller to interpret the - // situation. Since thay cannot be properly told apart, we report all - // `ret=0, ssl_error=SSL_ERROR_SYSCALL, sys_error=0` and `ret=0, - // ssl_error=SSL_ERROR_ZERO_RETURN` cases as the latter. - switch (ssl_error) { - case SSL_ERROR_NONE: - ec = std::error_code(); // Success - want = Want::nothing; - return std::size_t(ret); // ret > 0 - case SSL_ERROR_ZERO_RETURN: - ec = std::error_code(); // Success - want = Want::nothing; - return 0; - case SSL_ERROR_WANT_READ: - ec = std::error_code(); // Success - want = Want::read; - return 0; - case SSL_ERROR_WANT_WRITE: - ec = std::error_code(); // Success - want = Want::write; - return 0; - case SSL_ERROR_SYSCALL: - if (REALM_UNLIKELY(sys_error != 0)) { - ec = make_basic_system_error_code(sys_error); - } - else if (REALM_UNLIKELY(m_bio_error_code)) { - ec = m_bio_error_code; - } - else if (ret == 0) { - // ret = 0, ssl_eror = SSL_ERROR_SYSCALL, sys_error = 0 - // - // See remarks above! - ec = std::error_code(); // Success - } - else { - // ret = -1, ssl_eror = SSL_ERROR_SYSCALL, sys_error = 0 - // - // This situation arises in OpenSSL version >= 1.1. - // It has been observed in the SSL_connect call if the - // other endpoint terminates the connection during - // SSL_connect. The OpenSSL documentation states - // that ret = -1 implies an underlying BIO error and - // that errno should be consulted. However, - // errno = 0(Undefined error) in the observed case. - // At the moment. we will report - // MiscExtErrors::premature_end_of_input. - // If we see this error case occurring in other situations in - // the future, we will have to update this case. - ec = MiscExtErrors::premature_end_of_input; - } - want = Want::nothing; - return 0; - case SSL_ERROR_SSL: - ec = std::error_code(sys_error, openssl_error_category); - want = Want::nothing; - return 0; - default: - break; - } - // We are not supposed to ever get here - REALM_ASSERT(false); - return 0; -} - -inline int Stream::do_ssl_accept() noexcept -{ - int ret = SSL_accept(m_ssl); - return ret; -} - -inline int Stream::do_ssl_connect() noexcept -{ - int ret = SSL_connect(m_ssl); - return ret; -} - -inline int Stream::do_ssl_read(char* buffer, std::size_t size) noexcept -{ - int size_2 = int(size); - if (size > unsigned(std::numeric_limits::max())) - size_2 = std::size_t(std::numeric_limits::max()); - int ret = SSL_read(m_ssl, buffer, size_2); - return ret; -} - -inline int Stream::do_ssl_write(const char* data, std::size_t size) noexcept -{ - int size_2 = int(size); - if (size > unsigned(std::numeric_limits::max())) - size_2 = std::size_t(std::numeric_limits::max()); - int ret = SSL_write(m_ssl, data, size_2); - return ret; -} - -inline int Stream::do_ssl_shutdown() noexcept -{ - int ret = SSL_shutdown(m_ssl); - return ret; -} - -#elif REALM_HAVE_SECURE_TRANSPORT - -// Provides a homogeneous, and mostly quirks-free interface across the SecureTransport -// operations (handshake, read, write, shutdown). -// -// First of all, if the operation remains incomplete (neither successfully -// completed, nor failed), ssl_perform() will set `ec` to `std::system_error()`, -// `want` to something other than `Want::nothing`, and return zero. -// -// If an error occurred, ssl_perform() will set `ec` to something other than -// `std::system_error()`, `want` to `Want::nothing`, and return 0. -// -// If no error occurred, and the operation completed (`!ec && want == -// Want::nothing`), then the return value indicates the outcome of the -// operation. -// -// In general, a nonzero value means "full" success, and a zero value means -// "partial" success, however, a zero result can also generally mean "premature -// end of input" / "unclean protocol termination". -// -// Assuming there is no premature end of input, then for reads and writes, the -// returned value is the number of transferred bytes. Zero for read on end of -// input. Never zero for write. For handshake it is always 1. For shutdown it is -// 1 if the peer shutdown alert was already received, otherwise it is zero. -template -std::size_t Stream::ssl_perform(Oper oper, std::error_code& ec, Want& want) noexcept -{ - OSStatus result; - std::size_t n; - std::tie(result, n) = oper(); - - if (result == noErr) { - ec = std::error_code(); - want = Want::nothing; - return n; - } - - if (result == errSSLWouldBlock) { - REALM_ASSERT(m_last_operation); - ec = std::error_code(); - want = m_last_operation == BlockingOperation::read ? Want::read : Want::write; - m_last_operation = {}; - return n; - } - - if (result == errSSLClosedGraceful) { - ec = MiscExtErrors::end_of_input; - want = Want::nothing; - return n; - } - - if (result == errSSLClosedAbort || result == errSSLClosedNoNotify) { - ec = MiscExtErrors::premature_end_of_input; - want = Want::nothing; - return n; - } - - if (result == errSecIO) { - // A generic I/O error means something went wrong at a lower level. Use the error - // code we smuggled out of our lower-level functions to provide a more specific error. - REALM_ASSERT(m_last_error); - ec = m_last_error; - want = Want::nothing; - return n; - } - - ec = std::error_code(result, secure_transport_error_category); - want = Want::nothing; - return 0; -} -#endif // REALM_HAVE_OPENSSL / REALM_HAVE_SECURE_TRANSPORT - -} // namespace ssl -} // namespace network -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_NETWORK_SSL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/optional.hpp b/Lesson14/Pods/Realm/include/core/realm/util/optional.hpp deleted file mode 100644 index 57a2958..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/optional.hpp +++ /dev/null @@ -1,742 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - -#pragma once -#ifndef REALM_UTIL_OPTIONAL_HPP -#define REALM_UTIL_OPTIONAL_HPP - -#include -#include - -#include // std::logic_error -#include // std::less - -namespace realm { -namespace util { - -template -class Optional; - -// some() should be the equivalent of the proposed C++17 `make_optional`. -template -Optional some(Args&&...); -template -struct Some; - -// Note: Should conform with the future std::nullopt_t and std::in_place_t. -struct None { - constexpr explicit None(int) - { - } -}; -static constexpr None none{0}; -struct InPlace { - constexpr InPlace() - { - } -}; -static constexpr InPlace in_place; - -// Note: Should conform with the future std::bad_optional_access. -struct BadOptionalAccess : ExceptionWithBacktrace { - using ExceptionWithBacktrace::ExceptionWithBacktrace; -}; - -} // namespace util - -namespace _impl { - -template ::value> -struct OptionalStorage; - -template -struct TypeIsAssignableToOptional { - // Constraints from [optional.object.assign.18] - static const bool value = (std::is_same::type, T>::value && - std::is_constructible::value && std::is_assignable::value); -}; - -} // namespace _impl - -namespace util { - -// Note: Should conform with the future std::optional. -template -class Optional : private _impl::OptionalStorage { -public: - using value_type = T; - - constexpr Optional(); - constexpr Optional(None); - Optional(Optional&& other); - Optional(const Optional& other); - - constexpr Optional(T&& value); - constexpr Optional(const T& value); - - template - constexpr Optional(InPlace tag, Args&&...); - // FIXME: std::optional specifies an std::initializer_list constructor overload as well. - - Optional& operator=(None); - Optional& operator=(Optional&& other); - Optional& operator=(const Optional& other); - - template ::value>::type> - Optional& operator=(U&& value); - - explicit constexpr operator bool() const; - constexpr const T& value() const; // Throws - T& value(); // Throws, FIXME: Can be constexpr with C++14 - constexpr const T& operator*() const; // Throws - T& operator*(); // Throws, FIXME: Can be constexpr with C++14 - constexpr const T* operator->() const; // Throws - T* operator->(); // Throws, FIXME: Can be constexpr with C++14 - - template - constexpr T value_or(U&& value) const &; - - template - T value_or(U&& value) &&; - - void swap(Optional& other); // FIXME: Add noexcept() clause - - template - void emplace(Args&&...); - // FIXME: std::optional specifies an std::initializer_list overload for `emplace` as well. -private: - using Storage = _impl::OptionalStorage; - using Storage::m_engaged; - using Storage::m_value; - - constexpr bool is_engaged() const - { - return m_engaged; - } - void set_engaged(bool b) - { - m_engaged = b; - } - void clear(); -}; - - -/// An Optional is functionally equivalent to a bool. -/// Note: C++17 does not (yet) specify this specialization, but it is convenient -/// as a "safer bool", especially in the presence of `fmap`. -/// Disabled for compliance with std::optional. -// template <> -// class Optional { -// public: -// Optional() {} -// Optional(None) {} -// Optional(Optional&&) = default; -// Optional(const Optional&) = default; -// explicit operator bool() const { return m_engaged; } -// private: -// bool m_engaged = false; -// friend struct Some; -// }; - -/// An Optional is a non-owning nullable pointer that throws on dereference. -// FIXME: Visual Studio 2015's constexpr support isn't sufficient to allow Optional to compile -// in constexpr contexts. -template -class Optional { -public: - using value_type = T&; - using target_type = typename std::decay::type; - - constexpr Optional() - { - } - constexpr Optional(None) - { - } // FIXME: Was a delegating constructor, but not fully supported in VS2015 - Optional(const Optional& other) = default; - template - Optional(const Optional& other) - : m_ptr(other.m_ptr) - { - } - template - Optional(std::reference_wrapper ref) - : m_ptr(&ref.get()) - { - } - - constexpr Optional(T& init_value) - : m_ptr(&init_value) - { - } - Optional(T&& value) = delete; // Catches accidental references to rvalue temporaries. - - Optional& operator=(None) - { - m_ptr = nullptr; - return *this; - } - Optional& operator=(const Optional& other) - { - m_ptr = other.m_ptr; - return *this; - } - - template - Optional& operator=(std::reference_wrapper ref) - { - m_ptr = &ref.get(); - return *this; - } - - explicit constexpr operator bool() const - { - return m_ptr; - } - constexpr const target_type& value() const; // Throws - target_type& value(); // Throws - constexpr const target_type& operator*() const - { - return value(); - } - target_type& operator*() - { - return value(); - } - constexpr const target_type* operator->() const - { - return &value(); - } - target_type* operator->() - { - return &value(); - } - - void swap(Optional other); // FIXME: Add noexcept() clause -private: - T* m_ptr = nullptr; - - template - friend class Optional; -}; - - -template -struct RemoveOptional { - using type = T; -}; -template -struct RemoveOptional> { - using type = typename RemoveOptional::type; // Remove recursively -}; - - -/// Implementation: - -template -struct Some { - template - static Optional some(Args&&... args) - { - return Optional{std::forward(args)...}; - } -}; - -/// Disabled for compliance with std::optional. -// template <> -// struct Some { -// static Optional some() -// { -// Optional opt; -// opt.m_engaged = true; -// return opt; -// } -// }; - -template -Optional some(Args&&... args) -{ - return Some::some(std::forward(args)...); -} - - -template -constexpr Optional::Optional() - : Storage(none) -{ -} - -template -constexpr Optional::Optional(None) - : Storage(none) -{ -} - -template -Optional::Optional(Optional&& other) - : Storage(none) -{ - if (other.m_engaged) { - new (&m_value) T(std::move(other.m_value)); - m_engaged = true; - } -} - -template -Optional::Optional(const Optional& other) - : Storage(none) -{ - if (other.m_engaged) { - new (&m_value) T(other.m_value); - m_engaged = true; - } -} - -template -constexpr Optional::Optional(T&& r_value) - : Storage(std::move(r_value)) -{ -} - -template -constexpr Optional::Optional(const T& l_value) - : Storage(l_value) -{ -} - -template -template -constexpr Optional::Optional(InPlace, Args&&... args) - : Storage(std::forward(args)...) -{ -} - -template -void Optional::clear() -{ - if (m_engaged) { - m_value.~T(); - m_engaged = false; - } -} - -template -Optional& Optional::operator=(None) -{ - clear(); - return *this; -} - -template -Optional& Optional::operator=(Optional&& other) -{ - if (m_engaged) { - if (other.m_engaged) { - m_value = std::move(other.m_value); - } - else { - clear(); - } - } - else { - if (other.m_engaged) { - new (&m_value) T(std::move(other.m_value)); - m_engaged = true; - } - } - return *this; -} - -template -Optional& Optional::operator=(const Optional& other) -{ - if (m_engaged) { - if (other.m_engaged) { - m_value = other.m_value; - } - else { - clear(); - } - } - else { - if (other.m_engaged) { - new (&m_value) T(other.m_value); - m_engaged = true; - } - } - return *this; -} - -template -template -Optional& Optional::operator=(U&& r_value) -{ - if (m_engaged) { - m_value = std::forward(r_value); - } - else { - new (&m_value) T(std::forward(r_value)); - m_engaged = true; - } - return *this; -} - -template -constexpr Optional::operator bool() const -{ - return m_engaged; -} - -template -constexpr const T& Optional::value() const -{ - return m_engaged ? m_value : (throw BadOptionalAccess{"bad optional access"}, m_value); -} - -template -T& Optional::value() -{ - if (!m_engaged) { - throw BadOptionalAccess{"bad optional access"}; - } - return m_value; -} - -template -constexpr const typename Optional::target_type& Optional::value() const -{ - return m_ptr ? *m_ptr : (throw BadOptionalAccess{"bad optional access"}, *m_ptr); -} - -template -typename Optional::target_type& Optional::value() -{ - if (!m_ptr) { - throw BadOptionalAccess{"bad optional access"}; - } - return *m_ptr; -} - -template -constexpr const T& Optional::operator*() const -{ - // Note: This differs from std::optional, which doesn't throw. - return value(); -} - -template -T& Optional::operator*() -{ - // Note: This differs from std::optional, which doesn't throw. - return value(); -} - -template -constexpr const T* Optional::operator->() const -{ - // Note: This differs from std::optional, which doesn't throw. - return &value(); -} - -template -T* Optional::operator->() -{ - // Note: This differs from std::optional, which doesn't throw. - return &value(); -} - -template -template -constexpr T Optional::value_or(U&& otherwise) const & -{ - return m_engaged ? T{m_value} : T{std::forward(otherwise)}; -} - -template -template -T Optional::value_or(U&& otherwise) && -{ - if (is_engaged()) { - return T(std::move(m_value)); - } - else { - return T(std::forward(otherwise)); - } -} - -template -void Optional::swap(Optional& other) -{ - // FIXME: This might be optimizable. - Optional tmp = std::move(other); - other = std::move(*this); - *this = std::move(tmp); -} - -template -template -void Optional::emplace(Args&&... args) -{ - clear(); - new (&m_value) T(std::forward(args)...); - m_engaged = true; -} - - -template -constexpr Optional::type> make_optional(T&& value) -{ - using Type = typename std::decay::type; - return some(std::forward(value)); -} - -template -bool operator==(const Optional& lhs, const Optional& rhs) -{ - if (!lhs && !rhs) { - return true; - } - if (lhs && rhs) { - return *lhs == *rhs; - } - return false; -} - -template -bool operator!=(const Optional& lhs, const Optional& rhs) -{ - return !(lhs == rhs); -} - -template -bool operator<(const Optional& lhs, const Optional& rhs) -{ - if (!rhs) { - return false; - } - if (!lhs) { - return true; - } - return std::less{}(*lhs, *rhs); -} - -template -bool operator>(const util::Optional& lhs, const util::Optional& rhs) -{ - if (!lhs) { - return false; - } - if (!rhs) { - return true; - } - return std::greater{}(*lhs, *rhs); -} - -template -bool operator==(const Optional& lhs, None) -{ - return !bool(lhs); -} - -template -bool operator!=(const Optional& lhs, None) -{ - return bool(lhs); -} - -template -bool operator<(const Optional& lhs, None) -{ - static_cast(lhs); - return false; -} - -template -bool operator==(None, const Optional& rhs) -{ - return !bool(rhs); -} - -template -bool operator!=(None, const Optional& rhs) -{ - return bool(rhs); -} - -template -bool operator<(None, const Optional& rhs) -{ - return bool(rhs); -} - -template -bool operator==(const Optional& lhs, const U& rhs) -{ - return lhs ? *lhs == rhs : false; -} - -template -bool operator<(const Optional& lhs, const T& rhs) -{ - return lhs ? std::less{}(*lhs, rhs) : true; -} - -template -bool operator==(const T& lhs, const Optional& rhs) -{ - return rhs ? lhs == *rhs : false; -} - -template -bool operator<(const T& lhs, const Optional& rhs) -{ - return rhs ? std::less{}(lhs, *rhs) : false; -} - -template -auto operator>>(Optional lhs, F&& rhs) -> decltype(fmap(lhs, std::forward(rhs))) -{ - return fmap(lhs, std::forward(rhs)); -} - -template -OS& operator<<(OS& os, const Optional& rhs) -{ - if (rhs) { - os << "some(" << *rhs << ")"; - } - else { - os << "none"; - } - return os; -} - -template -T unwrap(T&& value) -{ - return value; -} - -template -T unwrap(util::Optional&& value) -{ - return *value; -} - -template -T unwrap(const util::Optional& value) -{ - return *value; -} - -template -T unwrap(util::Optional& value) -{ - return *value; -} - -} // namespace util - -namespace _impl { - -// T is trivially destructible. -template -struct OptionalStorage { - union { - T m_value; - char m_null_state; - }; - bool m_engaged = false; - - constexpr OptionalStorage(realm::util::None) - : m_null_state() - { - } - constexpr OptionalStorage(T&& value) - : m_value(std::move(value)) - , m_engaged(true) - { - } - - template - constexpr OptionalStorage(Args&&... args) - : m_value(args...) - , m_engaged(true) - { - } -}; - -// T is not trivially destructible. -template -struct OptionalStorage { - union { - T m_value; - char m_null_state; - }; - bool m_engaged = false; - - constexpr OptionalStorage(realm::util::None) - : m_null_state() - { - } - constexpr OptionalStorage(T&& value) - : m_value(std::move(value)) - , m_engaged(true) - { - } - - template - constexpr OptionalStorage(Args&&... args) - : m_value(args...) - , m_engaged(true) - { - } - - ~OptionalStorage() - { - if (m_engaged) - m_value.~T(); - } -}; - -} // namespace _impl - -using util::none; - -} // namespace realm - - -// for convienence, inject a default hash implementation into the std namespace -namespace std -{ - template - struct hash> - { - std::size_t operator()(realm::util::Optional const& o) const noexcept - { - if (bool(o) == false) { - return 0; // any choice will collide with some std::hash - } else { - return std::hash{}(*o); - } - } - }; -} - - -#endif // REALM_UTIL_OPTIONAL_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/overload.hpp b/Lesson14/Pods/Realm/include/core/realm/util/overload.hpp deleted file mode 100644 index 49188ae..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/overload.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************* - * - * Copyright 2017 Realm Inc. - * - * 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 REALM_UTIL_OVERLOAD_HPP -#define REALM_UTIL_OVERLOAD_HPP - -#include - -namespace realm { - -namespace _impl { - -template -struct Overloaded; - -} // namespace _impl - - -namespace util { - -// Declare an overload set using lambdas or other function objects. -// A minimal version of C++ Library Evolution Working Group proposal P0051R2. - -template -_impl::Overloaded overload(Fns&&... f) -{ - return _impl::Overloaded(std::forward(f)...); -} - -} // namespace util - - -namespace _impl { - -template -struct Overloaded : Fn, Overloaded { - template - Overloaded(U&& fn, Rest&&... rest) : Fn(std::forward(fn)), Overloaded(std::forward(rest)...) { } - - using Fn::operator(); - using Overloaded::operator(); -}; - -template -struct Overloaded : Fn { - template - Overloaded(U&& fn) : Fn(std::forward(fn)) { } - - using Fn::operator(); -}; - -} // namespace _impl -} // namespace realm - -#endif // REALM_UTIL_OVERLOAD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/parent_dir.hpp b/Lesson14/Pods/Realm/include/core/realm/util/parent_dir.hpp deleted file mode 100644 index 0e74e22..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/parent_dir.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_PARENT_DIR_HPP -#define REALM_UTIL_PARENT_DIR_HPP - -#include - -namespace realm { -namespace util { - -/// Same effect as std::filesystem::path::parent_path(). -/// -/// FIXME: This function ought to be moved to in the -/// realm-core repository. -std::string parent_dir(const std::string& path); - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_PARENT_DIR_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/platform_info.hpp b/Lesson14/Pods/Realm/include/core/realm/util/platform_info.hpp deleted file mode 100644 index 16ae43a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/platform_info.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_PLATFORM_INFO_HPP -#define REALM_UTIL_PLATFORM_INFO_HPP - -#include - - -namespace realm { -namespace util { - -/// Get a description of the current system platform. -/// -/// Returns a space-separated concatenation of `osname`, `sysname`, `release`, -/// `version`, and `machine` as returned by get_platform_info(PlatformInfo&). -std::string get_platform_info(); - - -struct PlatformInfo { - std::string osname; ///< Equivalent to `uname -o` (Linux). - std::string sysname; ///< Equivalent to `uname -s`. - std::string release; ///< Equivalent to `uname -r`. - std::string version; ///< Equivalent to `uname -v`. - std::string machine; ///< Equivalent to `uname -m`. -}; - -/// Get a description of the current system platform. -void get_platform_info(PlatformInfo&); - - - - -// Implementation - -inline std::string get_platform_info() -{ - PlatformInfo info; - get_platform_info(info); // Throws - return (info.osname + " " + info.sysname + " " + info.release + " " + info.version + " " + - info.machine); // Throws -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_PLATFORM_INFO_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/priority_queue.hpp b/Lesson14/Pods/Realm/include/core/realm/util/priority_queue.hpp deleted file mode 100644 index a2a28c8..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/priority_queue.hpp +++ /dev/null @@ -1,304 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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. - * - **************************************************************************/ - - -#pragma once -#ifndef REALM_UTIL_PRIORITY_QUEUE_HPP -#define REALM_UTIL_PRIORITY_QUEUE_HPP - -#include -#include -#include - -namespace realm { -namespace util { - - -/// PriorityQueue corresponds exactly to `std::priority_queue`, but has the extra feature -/// of allowing iteration and erasure of elements in the queue. -/// -/// PriorityQueue only allows const access to its elements, because non-const access -/// would open up the risk of changing the ordering of the elements. -/// -/// Note: As opposed to `std::priority_queue`, this does not store elements in a heap -/// internally. Instead, elements are stored in sorted order. Users of this class are -/// allowed to operate on this assumption. -template , class Compare = std::less> -class PriorityQueue : private Compare { -public: - using container_type = Container; - using value_type = typename Container::value_type; - using size_type = typename Container::size_type; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using const_reverse_iterator = typename Container::const_reverse_iterator; - using const_iterator = typename Container::const_iterator; - - //@{ - /// Construct a PriorityQueue, optionally providing a comparator object. - PriorityQueue(const Compare& comparator, const Container& cont); - - explicit PriorityQueue(const Compare& comparator = Compare{}, Container&& cont = Container{}); - - template - PriorityQueue(InputIt first, InputIt last, const Compare& comparator, const Container& cont); - - template - PriorityQueue(InputIt first, InputIt last, const Compare& comparator = Compare{}, Container&& cont = Container{}); - //@} - // Skipping Allocator-specific template constructors. - - PriorityQueue(const PriorityQueue&) = default; - PriorityQueue(PriorityQueue&&) = default; - PriorityQueue& operator=(const PriorityQueue&) = default; - PriorityQueue& operator=(PriorityQueue&&) = default; - - bool empty() const; - size_type size() const; - - //@{ - /// Push an element to the priority queue. - /// - /// If insertion to the underlying `Container` invalidates - /// iterators and references, any iterators and references into this - /// priority queue are also invalidated. By default, this is the case. - void push(const T& value); - void push(T&& value); - //@} - - /// Pop the largest element from the priority queue. - /// - /// If `pop_back` on the underlying `Container` invalidates - /// iterators and references, any iterators and reference into this - /// priority queue are also invalidated. By default, this is *NOT* the case. - /// - /// Calling `pop()` on an empty priority queue is undefined. - void pop(); - - /// Return a reference to the largest element of the priority queue. - /// - /// Calling `top()` on an empty priority queue is undefined. - const_reference top() const; - - /// Pop the top of the queue and return it by moving it out of the queue. - /// - /// Note: This method does not exist in `std::priority_queue`. - /// - /// Calling `pop_top()` on an empty priorty queue is undefined. - value_type pop_top(); - - // FIXME: emplace() deliberately omitted for simplicity. - - /// Swap the contents of this priority queue with the contents of \a other. - void swap(PriorityQueue& other); - - // Not in std::priority_queue: - - /// Return an iterator to the beginning of the queue (smallest element first). - const_iterator begin() const; - - /// Return an iterator to the end of the queue (largest element last); - const_iterator end() const; - - /// Return a reverse iterator into the priority queue (largest element first). - const_reverse_iterator rbegin() const; - - /// Return a reverse iterator representing the end of the priority queue (smallest element last). - const_reverse_iterator rend() const; - - /// Erase element pointed to by \a it. - /// - /// Note: This function differs from `std::priority_queue` by returning the erased - /// element using move semantics. - /// - /// Calling `erase()` with a beyond-end iterator (such as what is returned by `end()`) - /// is undefined. - value_type erase(const_iterator it); - - /// Remove all elements from the priority queue. - void clear(); - - /// Calls `reserve()` on the underlying `Container`. - void reserve(size_type); - -private: - Container m_queue; - - const Compare& compare() const; - Compare& compare(); -}; - - -/// Implementation - -template -PriorityQueue::PriorityQueue(const Compare& comparator, const Container& cont) - : Compare(comparator) - , m_queue(cont) -{ -} - -template -PriorityQueue::PriorityQueue(const Compare& comparator, Container&& cont) - : Compare(comparator) - , m_queue(std::move(cont)) -{ -} - -template -template -PriorityQueue::PriorityQueue(InputIt first, InputIt last, const Compare& comparator, - const Container& cont) - : Compare(comparator) - , m_queue(cont) -{ - for (auto it = first; it != last; ++it) { - push(*it); - } -} - -template -template -PriorityQueue::PriorityQueue(InputIt first, InputIt last, const Compare& comparator, - Container&& cont) - : Compare(comparator) - , m_queue(std::move(cont)) -{ - for (auto it = first; it != last; ++it) { - push(*it); - } -} - -template -typename PriorityQueue::size_type PriorityQueue::size() const -{ - return m_queue.size(); -} - -template -bool PriorityQueue::empty() const -{ - return m_queue.empty(); -} - -template -void PriorityQueue::push(const T& element) -{ - auto it = std::lower_bound(m_queue.begin(), m_queue.end(), element, compare()); - m_queue.insert(it, element); -} - -template -void PriorityQueue::push(T&& element) -{ - auto it = std::lower_bound(m_queue.begin(), m_queue.end(), element, compare()); - m_queue.insert(it, std::move(element)); -} - -template -void PriorityQueue::pop() -{ - m_queue.pop_back(); -} - -template -typename PriorityQueue::const_reference PriorityQueue::top() const -{ - return m_queue.back(); -} - -template -typename PriorityQueue::value_type PriorityQueue::pop_top() -{ - value_type value = std::move(m_queue.back()); - m_queue.pop_back(); - return value; -} - -template -Compare& PriorityQueue::compare() -{ - return *this; -} - -template -const Compare& PriorityQueue::compare() const -{ - return *this; -} - -template -typename PriorityQueue::const_iterator PriorityQueue::begin() const -{ - return m_queue.begin(); -} - -template -typename PriorityQueue::const_iterator PriorityQueue::end() const -{ - return m_queue.end(); -} - -template -typename PriorityQueue::const_reverse_iterator -PriorityQueue::rbegin() const -{ - return m_queue.rbegin(); -} - -template -typename PriorityQueue::const_reverse_iterator -PriorityQueue::rend() const -{ - return m_queue.rend(); -} - -template -typename PriorityQueue::value_type -PriorityQueue::erase(const_iterator it) -{ - // Convert to non-const iterator: - auto non_const_iterator = m_queue.begin() + (it - m_queue.begin()); - value_type value = std::move(*non_const_iterator); - m_queue.erase(non_const_iterator); - return value; -} - -template -void PriorityQueue::clear() -{ - m_queue.clear(); -} - -template -void PriorityQueue::reserve(size_type sz) -{ - m_queue.reserve(sz); -} - -template -void PriorityQueue::swap(PriorityQueue& other) -{ - using std::swap; - swap(m_queue, other.m_queue); - swap(compare(), other.compare()); -} -} -} - -#endif // REALM_UTIL_PRIORITY_QUEUE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/quote.hpp b/Lesson14/Pods/Realm/include/core/realm/util/quote.hpp deleted file mode 100644 index 7959a44..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/quote.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_QUOTE_HPP -#define REALM_UTIL_QUOTE_HPP - -#include - -namespace realm { -namespace util { - -template struct Quote { - bool smart; - util::BasicStringView view; -}; - - -/// Mark text for quotation during output to stream. -/// -/// If `out` is an output stream, and `str` is a string (e.g., an std::string), -/// then -/// -/// out << quoted(str) -/// -/// will write `str` in quoted form to `out`. -/// -/// Quotation involves bracketing the text in double quotes (`"`), and escaping -/// special characters according to the rules of C/C++ string literals. In this -/// case, the special characters are `"` and `\` as well as those that are not -/// printable (!std::isprint()). -/// -/// Quotation happens as the string is written to a stream, so there is no -/// intermediate representation of the quoted string. -template Quote quoted(util::BasicStringView) noexcept; - - -/// Same as quoted(), except that in this case, quotation is elided when the -/// specified string consists of a single printable word. Or, to be more -/// precise, quotation is elided if the string is nonempty, consists entirely of -/// printable charcters (std::isprint()), does not contain space (` `), and does -/// not conatian quotation (`"`) or backslash (`\`). -template Quote smart_quoted(util::BasicStringView) noexcept; - - -template -std::basic_ostream& operator<<(std::basic_ostream&, Quote); - - - - - -// Implementation - -template inline Quote quoted(util::BasicStringView view) noexcept -{ - bool smart = false; - return {smart, view}; -} - -template -inline Quote smart_quoted(util::BasicStringView view) noexcept -{ - bool smart = true; - return {smart, view}; -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, Quote quoted) -{ - std::locale loc = out.getloc(); - const std::ctype& ctype = std::use_facet>(loc); - util::BasicStringView view = quoted.view; - if (quoted.smart && !view.empty()) { - for (C ch : view) { - if (ch == '"' || ch == '\\' || !ctype.is(ctype.graph, ch)) - goto quote; - } - return out << view; // Throws - } - quote: - typename std::basic_ostream::sentry sentry{out}; - if (REALM_LIKELY(sentry)) { - C dquote = ctype.widen('"'); - C bslash = ctype.widen('\\'); - out.put(dquote); // Throws - bool follows_hex = false; - for (C ch : view) { - if (REALM_LIKELY(ctype.is(ctype.print, ch))) { - if (REALM_LIKELY(!follows_hex || !ctype.is(ctype.xdigit, ch))) { - if (REALM_LIKELY(ch != '"' || ch != '\\')) - goto put_char; - goto escape_char; - } - } - switch (ch) { - case '\a': - ch = ctype.widen('a'); - goto escape_char; - case '\b': - ch = ctype.widen('b'); - goto escape_char; - case '\f': - ch = ctype.widen('f'); - goto escape_char; - case '\n': - ch = ctype.widen('n'); - goto escape_char; - case '\r': - ch = ctype.widen('r'); - goto escape_char; - case '\t': - ch = ctype.widen('t'); - goto escape_char; - case '\v': - ch = ctype.widen('v'); - goto escape_char; - } - goto numeric; - escape_char: - out.put(bslash); // Throws - put_char: - out.put(ch); // Throws - next: - follows_hex = false; - continue; - numeric: - out.put(bslash); // Throws - using D = typename std::make_unsigned::type; - char digits[] = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; - D val = ch; - if (val < 512) { - out.put(ctype.widen(digits[val / 64 ])); // Throws - out.put(ctype.widen(digits[val % 64 / 8])); // Throws - out.put(ctype.widen(digits[val % 8])); // Throws - goto next; - } - out.put(ctype.widen('x')); // Throws - const int max_hex_digits = (std::numeric_limits::digits + 3) / 4; - C buffer[max_hex_digits]; - int i = max_hex_digits; - while (val != 0) { - buffer[--i] = ctype.widen(digits[val % 16]); - val /= 16; - } - out.write(buffer + i, max_hex_digits - i); // Throws - follows_hex = true; - } - out.put(dquote); // Throws - } - return out; -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_QUOTE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/random.hpp b/Lesson14/Pods/Realm/include/core/realm/util/random.hpp deleted file mode 100644 index d0c7fe9..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/random.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_RANDOM_HPP -#define REALM_UTIL_RANDOM_HPP - -#include -#include -#include -#include -#include -#include - -namespace realm { -namespace util { - -/// Perform a nondeterministc seeding of the specified pseudo random number -/// generator. -/// -/// \tparam Engine A type that satisfies UniformRandomBitGenerator as defined by -/// the C++ standard. -/// -/// \tparam state_size The number of words of type Engine::result_type that make -/// up the engine state. -/// -/// Thread-safe. -/// -/// FIXME: Move this to core repo, as it is generally useful. -template -void seed_prng_nondeterministically(Engine&); - -template -std::string generate_random_lower_case_string(Engine& engine, size_t size); - - -// Implementation - -} // namespace util - -namespace _impl { - -void get_extra_seed_entropy(unsigned int& extra_entropy_1, unsigned int& extra_entropy_2, - unsigned int& extra_entropy_3); - -} // namespace _impl - -namespace util { - -template void seed_prng_nondeterministically(Engine& engine) -{ - // This implementation was informed and inspired by - // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0205r0.html. - // - // The number of bits of entropy needed is `state_size * - // std::numeric_limits::digits` (assuming that - // the engine uses all available bits in each word). - // - // Each invocation of `std::random_device::operator()` gives us - // `std::numeric_limits::digits` bits (assuming maximum - // entropy). Note that `std::random_device::result_type` must be `unsigned - // int`, `std::random_device::min()` must return zero, and - // `std::random_device::max()` must return `std::numeric_limits::max()`. - // - // Ideally, we could have used `std::random_device::entropy()` as the actual - // number of bits of entropy produced per invocation of - // `std::random_device::operator()`, however, it is incorrectly implemented - // on many platform. Also, it is supposed to return zero when - // `std::random_device` is just a PRNG, but that would leave us with no way - // to continue. - // - // When the actual entropy from `std::random_device` is less than maximum, - // the seeding will be less than optimal. For example, if the actual entropy - // is only half of the maximum, then the seeding will only produce half the - // entrpy that it ought to, but that will generally still be a good seeding. - // - // For the (assumed) rare cases where `std::random_device` is a PRGN that is - // not nondeterministically seeded, we include a bit of extra entropy taken - // from such places as the current time and the ID of the executing process - // (when available). - - constexpr long seed_bits_needed = state_size * - long(std::numeric_limits::digits); - constexpr int seed_bits_per_device_invocation = - std::numeric_limits::digits; - constexpr size_t seed_words_needed = - size_t((seed_bits_needed + (seed_bits_per_device_invocation - 1)) / - seed_bits_per_device_invocation); // Rounding up - constexpr int num_extra = 3; - std::array seed_values; - std::random_device rnddev; - std::generate(seed_values.begin(), seed_values.end()-num_extra, std::ref(rnddev)); - - unsigned int extra_entropy[3]; - _impl::get_extra_seed_entropy(extra_entropy[0], extra_entropy[1], extra_entropy[2]); - static_assert(num_extra == sizeof extra_entropy / sizeof extra_entropy[0], "Mismatch"); - std::copy(extra_entropy, extra_entropy+num_extra, seed_values.end()-num_extra); - - std::seed_seq seed_seq(seed_values.begin(), seed_values.end()); - engine.seed(seed_seq); -} - -template -std::string generate_random_lower_case_string(Engine& engine, size_t size) -{ - std::uniform_int_distribution dist(0, 25); - std::string str; - str.reserve(size); - for (size_t i = 0; i < size; ++i) { - short val = dist(engine); - char c = 'a' + char(val); - str.push_back(c); - } - return str; -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_RANDOM_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/resource_limits.hpp b/Lesson14/Pods/Realm/include/core/realm/util/resource_limits.hpp deleted file mode 100644 index 858624a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/resource_limits.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_RESOURCE_LIMITS_HPP -#define REALM_UTIL_RESOURCE_LIMITS_HPP - -namespace realm { -namespace util { - - -enum class Resource { - /// The maximum size, in bytes, of the core file produced when the memory - /// image of this process is dumped. If the memory image is larger than the - /// limit, the core file will not be created. Same as `RLIMIT_CORE` of - /// POSIX. - core_dump_size, - - /// The maximum CPU time, in seconds, available to this process. If the - /// limit is exceeded, the process will be killed. Same as `RLIMIT_CPU` of - /// POSIX. - cpu_time, - - /// The maximum size, in bytes, of the data segment of this process. If the - /// limit is exceede, std::malloc() will fail with `errno` equal to - /// `ENOMEM`. Same as `RLIMIT_DATA` of POSIX. - data_segment_size, - - /// The maximum size, in bytes, of a file that is modified by this - /// process. If the limit is exceede, the process will be killed. Same as - /// `RLIMIT_FSIZE` of POSIX. - file_size, - - /// One plus the maximum file descriptor value that can be opened by this - /// process. Same as `RLIMIT_NOFILE` of POSIX. - num_open_files, - - /// The maximum size, in bytes, of the stack of the main thread of this - /// process. If the limit is exceede, the process is killed. Same as - /// `RLIMIT_STACK` of POSIX. - stack_size, - - /// The maximum size, in bytes, of the process's virtual memory (address - /// space). If the limit is exceeded due to heap allocation, std::malloc() - /// will fail with `errno` equal to `ENOMEM`. If the limit is exceeded due - /// to explicit memory mapping, mmap() will fail with `errno` equal to - /// `ENOMEM`. If the limit is exceeded due to stack expansion, the process - /// will be killed. Same as `RLIMIT_AS` of POSIX. - virtual_memory_size -}; - - -bool system_has_rlimit(Resource) noexcept; - - -//@{ -/// Get or set resouce limits. A negative value means 'unlimited', both when -/// getting and when setting. -long get_hard_rlimit(Resource); -long get_soft_rlimit(Resource); -void set_soft_rlimit(Resource, long value); -//@} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_RESOURCE_LIMITS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/safe_int_ops.hpp b/Lesson14/Pods/Realm/include/core/realm/util/safe_int_ops.hpp deleted file mode 100644 index 15030ad..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/safe_int_ops.hpp +++ /dev/null @@ -1,623 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_SAFE_INT_OPS_HPP -#define REALM_UTIL_SAFE_INT_OPS_HPP - -#ifdef _WIN32 -#undef max // collides with numeric_limits::max called later in this header file -#undef min // collides with numeric_limits::min called later in this header file -#endif - -#include - -#include -#include -#include - -namespace realm { -namespace util { - - -/// Perform integral or floating-point promotion on the argument. This -/// is useful for example when printing a number of arbitrary numeric -/// type to 'stdout', since it will convert values of character-like -/// types to regular integer types, which will then be printed as -/// numbers rather characters. -template -typename Promote::type promote(T value) noexcept; - - -/// This function allows you to test for a negative value in any -/// numeric type, even when the type is unsigned. Normally, when the -/// type is unsigned, such a test will produce a compiler warning. -template -bool is_negative(T value) noexcept; - - -/// Cast the specified value to the specified unsigned type reducing -/// the value (or in case of negative values, the two's complement -/// representation) modulo `2**N` where `N` is the number of value -/// bits (or digits) in the unsigned target type. This is usefull in -/// cases where the target type may be `bool`, but need not be `bool`. -template -To cast_to_unsigned(From) noexcept; - - -//@{ - -/// Compare two integers of the same, or of different type, and -/// produce the expected result according to the natural -/// interpretation of the operation. -/// -/// Note that in general a standard comparison between a signed and an -/// unsigned integer type is unsafe, and it often generates a compiler -/// warning. An example is a 'less than' comparison between a negative -/// value of type 'int' and a small positive value of type -/// 'unsigned'. In this case the negative value will be converted to -/// 'unsigned' producing a large positive value which, in turn, will -/// lead to the counter intuitive result of 'false'. -/// -/// Please note that these operation incur absolutely no overhead when -/// the two types have the same signedness. -/// -/// These functions check at compile time that both types have valid -/// specializations of std::numeric_limits<> and that both are indeed -/// integers. -/// -/// These functions make absolutely no assumptions about the platform -/// except that it complies with at least C++03. - -template -inline bool int_equal_to(A, B) noexcept; -template -inline bool int_not_equal_to(A, B) noexcept; -template -inline bool int_less_than(A, B) noexcept; -template -inline bool int_less_than_or_equal(A, B) noexcept; -template -inline bool int_greater_than(A, B) noexcept; -template -inline bool int_greater_than_or_equal(A, B) noexcept; - -//@} - - -//@{ - -/// Check for overflow in integer variable `lval` while adding integer -/// `rval` to it, or while subtracting integer `rval` from it. Returns -/// true on positive or negative overflow. -/// -/// Both `lval` and `rval` must be of an integer type for which a -/// specialization of std::numeric_limits<> exists. The two types need -/// not be the same, in particular, one can be signed and the other -/// one can be unsigned. -/// -/// These functions are especially well suited for cases where \a rval -/// is a compile-time constant. -/// -/// These functions check at compile time that both types have valid -/// specializations of std::numeric_limits<> and that both are indeed -/// integers. -/// -/// These functions make absolutely no assumptions about the platform -/// except that it complies with at least C++03. - -template -inline bool int_add_with_overflow_detect(L& lval, R rval) noexcept; - -template -inline bool int_subtract_with_overflow_detect(L& lval, R rval) noexcept; - -//@} - - -/// Check for positive overflow when multiplying two positive integers -/// of the same, or of different type. Returns true on overflow. -/// -/// \param lval Must not be negative. Both signed and unsigned types -/// can be used. -/// -/// \param rval Must be stricly greater than zero. Both signed and -/// unsigned types can be used. -/// -/// This function is especially well suited for cases where \a rval is -/// a compile-time constant. -/// -/// This function checks at compile time that both types have valid -/// specializations of std::numeric_limits<> and that both are indeed -/// integers. -/// -/// This function makes absolutely no assumptions about the platform -/// except that it complies with at least C++03. -template -inline bool int_multiply_with_overflow_detect(L& lval, R rval) noexcept; - - -/// Checks for positive overflow when performing a bitwise shift to -/// the left on a non-negative value of arbitrary integer -/// type. Returns true on overflow. -/// -/// \param lval Must not be negative. Both signed and unsigned types -/// can be used. -/// -/// \param i Must be non-negative and such that L(1)>>i has a -/// value that is defined by the C++03 standard. In particular, the -/// value of i must not exceed the number of bits of storage type T as -/// shifting by this amount is not defined by the standard. -/// -/// This function makes absolutely no assumptions about the platform -/// except that it complies with at least C++03. -template -inline bool int_shift_left_with_overflow_detect(T& lval, int i) noexcept; - - -//@{ - -/// Check for overflow when casting an integer value from one type to -/// another. While the first function is a mere check, the second one -/// also carries out the cast, but only when there is no -/// overflow. Both return true on overflow. -/// -/// These functions check at compile time that both types have valid -/// specializations of std::numeric_limits<> and that both are indeed -/// integers. -/// -/// These functions make absolutely no assumptions about the platform -/// except that it complies with at least C++03. - -template -bool int_cast_has_overflow(From from) noexcept; - -template -bool int_cast_with_overflow_detect(From from, To& to) noexcept; - -//@} - - -/// Convert negative values from two's complement representation to the -/// platforms native representation. -/// -/// If `To` is an unsigned type, this function does nothing beyond casting the -/// specified value to `To`. Otherwise, `To` is a signed type, and negative -/// values will be converted from two's complement representation in unsigned -/// `From` to the platforms native representation in `To`. -/// -/// For signed `To` the result is well-defined if, and only if the value with -/// the specified two's complement representation is representable in the -/// specified signed type. While this is generally the case when using -/// corresponding signed/unsigned type pairs, it is not guaranteed by the -/// standard. However, if you know that the signed type has at least as many -/// value bits as the unsigned type, then the result is always -/// well-defined. Note that a 'value bit' in this context is the same as a -/// 'digit' from the point of view of `std::numeric_limits`. -/// -/// On platforms that use two's complement representation of negative values, -/// this function is expected to be completely optimized away. This has been -/// observed to be true with both GCC 4.8 and Clang 3.2. -/// -/// Note that the **opposite** direction (from the platforms native -/// representation to two's complement) is trivially handled by casting the -/// signed value to a value of a sufficiently wide unsigned integer type. An -/// unsigned type will be sufficiently wide if it has at least one more value -/// bit than the signed type. -/// -/// Interestingly, the C++ language offers no direct way of doing what this -/// function does, yet, this function is implemented in a way that makes no -/// assumption about the underlying platform except what is guaranteed by C++11. -/// -/// \tparam From The unsigned type used to store the two's complement -/// representation. -/// -/// \tparam To A signed or unsigned integer type. -template -To from_twos_compl(From twos_compl) noexcept; - - -// Implementation: - -template -inline typename Promote::type promote(T value) noexcept -{ - typedef typename Promote::type promoted_type; - promoted_type value_2 = promoted_type(value); - return value_2; -} - -} // namespace util - -namespace _impl { - -template -struct IsNegative { - static bool test(T value) noexcept - { - return value < 0; - } -}; -template -struct IsNegative { - static bool test(T) noexcept - { - return false; - } -}; - -template -struct CastToUnsigned { - template - static To cast(From value) noexcept - { - return To(value); - } -}; -template <> -struct CastToUnsigned { - template - static bool cast(From value) noexcept - { - return bool(unsigned(value) & 1); - } -}; - -template -struct SafeIntBinopsImpl { -}; - -// (unsigned, unsigned) (all size combinations) -// -// This implementation utilizes the fact that overflow in unsigned -// arithmetic is guaranteed to be handled by reduction modulo 2**N -// where N is the number of bits in the unsigned type. The purpose of -// the bitwise 'and' with lim_l::max() is to make a cast to bool -// behave the same way as casts to other unsigned integer types. -// Finally, this implementation uses the fact that if modular addition -// overflows, then the result must be a value that is less than both -// operands. Also, if modular subtraction overflows, then the result -// must be a value that is greater than the first operand. -template -struct SafeIntBinopsImpl { - typedef std::numeric_limits lim_l; - typedef std::numeric_limits lim_r; - static const int needed_bits_l = lim_l::digits; - static const int needed_bits_r = lim_r::digits; - static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; - typedef typename util::FastestUnsigned::type common_unsigned; - static bool equal(L l, R r) noexcept - { - return common_unsigned(l) == common_unsigned(r); - } - static bool less(L l, R r) noexcept - { - return common_unsigned(l) < common_unsigned(r); - } - static bool add(L& lval, R rval) noexcept - { - L lval_2 = util::cast_to_unsigned(lval + rval); - bool overflow = common_unsigned(lval_2) < common_unsigned(rval); - if (REALM_UNLIKELY(overflow)) - return true; - lval = lval_2; - return false; - } - static bool sub(L& lval, R rval) noexcept - { - common_unsigned lval_2 = common_unsigned(lval) - common_unsigned(rval); - bool overflow = lval_2 > common_unsigned(lval); - if (REALM_UNLIKELY(overflow)) - return true; - lval = util::cast_to_unsigned(lval_2); - return false; - } -}; - -// (unsigned, signed) (all size combinations) -template -struct SafeIntBinopsImpl { - typedef std::numeric_limits lim_l; - typedef std::numeric_limits lim_r; - static const int needed_bits_l = lim_l::digits; - static const int needed_bits_r = lim_r::digits + 1; - static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; - typedef typename util::FastestUnsigned::type common_unsigned; - typedef std::numeric_limits lim_cu; - static bool equal(L l, R r) noexcept - { - return (lim_l::digits > lim_r::digits) ? r >= 0 && l == util::cast_to_unsigned(r) : R(l) == r; - } - static bool less(L l, R r) noexcept - { - return (lim_l::digits > lim_r::digits) ? r >= 0 && l < util::cast_to_unsigned(r) : R(l) < r; - } - static bool add(L& lval, R rval) noexcept - { - common_unsigned lval_2 = lval + common_unsigned(rval); - bool overflow; - if (lim_l::digits < lim_cu::digits) { - overflow = common_unsigned(lval_2) > common_unsigned(lim_l::max()); - } - else { - overflow = (lval_2 < common_unsigned(lval)) == (rval >= 0); - } - if (REALM_UNLIKELY(overflow)) - return true; - lval = util::cast_to_unsigned(lval_2); - return false; - } - static bool sub(L& lval, R rval) noexcept - { - common_unsigned lval_2 = lval - common_unsigned(rval); - bool overflow; - if (lim_l::digits < lim_cu::digits) { - overflow = common_unsigned(lval_2) > common_unsigned(lim_l::max()); - } - else { - overflow = (common_unsigned(lval_2) > common_unsigned(lval)) == (rval >= 0); - } - if (REALM_UNLIKELY(overflow)) - return true; - lval = util::cast_to_unsigned(lval_2); - return false; - } -}; - -// (signed, unsigned) (all size combinations) -template -struct SafeIntBinopsImpl { - typedef std::numeric_limits lim_l; - typedef std::numeric_limits lim_r; - static const int needed_bits_l = lim_l::digits + 1; - static const int needed_bits_r = lim_r::digits; - static const int needed_bits = needed_bits_l >= needed_bits_r ? needed_bits_l : needed_bits_r; - typedef typename util::FastestUnsigned::type common_unsigned; - static bool equal(L l, R r) noexcept - { - return (lim_l::digits < lim_r::digits) ? l >= 0 && util::cast_to_unsigned(l) == r : l == L(r); - } - static bool less(L l, R r) noexcept - { - return (lim_l::digits < lim_r::digits) ? l < 0 || util::cast_to_unsigned(l) < r : l < L(r); - } - static bool add(L& lval, R rval) noexcept - { - common_unsigned max_add = common_unsigned(lim_l::max()) - common_unsigned(lval); - bool overflow = common_unsigned(rval) > max_add; - if (REALM_UNLIKELY(overflow)) - return true; - lval = util::from_twos_compl(common_unsigned(lval) + rval); - return false; - } - static bool sub(L& lval, R rval) noexcept - { - common_unsigned max_sub = common_unsigned(lval) - common_unsigned(lim_l::min()); - bool overflow = common_unsigned(rval) > max_sub; - if (REALM_UNLIKELY(overflow)) - return true; - lval = util::from_twos_compl(common_unsigned(lval) - rval); - return false; - } -}; - -// (signed, signed) (all size combinations) -template -struct SafeIntBinopsImpl { - typedef std::numeric_limits lim_l; - static bool equal(L l, R r) noexcept - { - return l == r; - } - static bool less(L l, R r) noexcept - { - return l < r; - } - static bool add(L& lval, R rval) noexcept - { - // Note that both subtractions below occur in a signed type - // that is at least as wide as both of the two types. Note - // also that any signed type guarantees that there is no - // overflow when subtracting two negative values or two - // non-negative value. See C99 (adopted as subset of C++11) - // section 6.2.6.2 "Integer types" paragraph 2. - if (rval < 0) { - if (REALM_UNLIKELY(lval < lim_l::min() - rval)) - return true; - } - else { - if (REALM_UNLIKELY(lval > lim_l::max() - rval)) - return true; - } - // The following statement has exactly the same effect as - // `lval += rval`. - lval = L(lval + rval); - return false; - } - static bool sub(L& lval, R rval) noexcept - { - // Note that both subtractions below occur in a signed type - // that is at least as wide as both of the two types. Note - // also that there can be no overflow when adding a negative - // value to a non-negative value, or when adding a - // non-negative value to a negative one. - if (rval < 0) { - if (REALM_UNLIKELY(lval > lim_l::max() + rval)) - return true; - } - else { - if (REALM_UNLIKELY(lval < lim_l::min() + rval)) - return true; - } - // The following statement has exactly the same effect as - // `lval += rval`. - lval = L(lval - rval); - return false; - } -}; - -template -struct SafeIntBinops : SafeIntBinopsImpl::is_signed, std::numeric_limits::is_signed> { - typedef std::numeric_limits lim_l; - typedef std::numeric_limits lim_r; - static_assert(lim_l::is_specialized && lim_r::is_specialized, - "std::numeric_limits<> must be specialized for both types"); - static_assert(lim_l::is_integer && lim_r::is_integer, "Both types must be integers"); -}; - -} // namespace _impl - -namespace util { - -template -inline bool is_negative(T value) noexcept -{ - return _impl::IsNegative::is_signed>::test(value); -} - -template -inline To cast_to_unsigned(From value) noexcept -{ - return _impl::CastToUnsigned::cast(value); -} - -template -inline bool int_equal_to(A a, B b) noexcept -{ - return _impl::SafeIntBinops::equal(a, b); -} - -template -inline bool int_not_equal_to(A a, B b) noexcept -{ - return !_impl::SafeIntBinops::equal(a, b); -} - -template -inline bool int_less_than(A a, B b) noexcept -{ - return _impl::SafeIntBinops::less(a, b); -} - -template -inline bool int_less_than_or_equal(A a, B b) noexcept -{ - return !_impl::SafeIntBinops::less(b, a); // Not greater than -} - -template -inline bool int_greater_than(A a, B b) noexcept -{ - return _impl::SafeIntBinops::less(b, a); -} - -template -inline bool int_greater_than_or_equal(A a, B b) noexcept -{ - return !_impl::SafeIntBinops::less(a, b); // Not less than -} - -template -inline bool int_add_with_overflow_detect(L& lval, R rval) noexcept -{ - return _impl::SafeIntBinops::add(lval, rval); -} - -template -inline bool int_subtract_with_overflow_detect(L& lval, R rval) noexcept -{ - return _impl::SafeIntBinops::sub(lval, rval); -} - -template -inline bool int_multiply_with_overflow_detect(L& lval, R rval) noexcept -{ - // FIXME: Check if the following optimizes better (if it works at all): - // L lval_2 = L(lval * rval); - // bool overflow = rval != 0 && (lval_2 / rval) != lval; - typedef std::numeric_limits lim_l; - typedef std::numeric_limits lim_r; - static_assert(lim_l::is_specialized && lim_r::is_specialized, - "std::numeric_limits<> must be specialized for both types"); - static_assert(lim_l::is_integer && lim_r::is_integer, "Both types must be integers"); - REALM_ASSERT(int_greater_than_or_equal(lval, 0)); - REALM_ASSERT(int_greater_than(rval, 0)); - if (int_less_than(lim_l::max() / rval, lval)) - return true; - lval = L(lval * rval); - return false; -} - -template -inline bool int_shift_left_with_overflow_detect(T& lval, int i) noexcept -{ - typedef std::numeric_limits lim; - static_assert(lim::is_specialized, "std::numeric_limits<> must be specialized for T"); - static_assert(lim::is_integer, "T must be an integer type"); - REALM_ASSERT(int_greater_than_or_equal(lval, 0)); - if ((lim::max() >> i) < lval) - return true; - lval <<= i; - return false; -} - -template -inline bool int_cast_has_overflow(From from) noexcept -{ - typedef std::numeric_limits lim_to; - return int_less_than(from, lim_to::min()) || int_less_than(lim_to::max(), from); -} - -template -inline bool int_cast_with_overflow_detect(From from, To& to) noexcept -{ - if (REALM_LIKELY(!int_cast_has_overflow(from))) { - to = To(from); - return false; - } - return true; -} - -template -inline To from_twos_compl(From twos_compl) noexcept -{ - typedef std::numeric_limits lim_f; - typedef std::numeric_limits lim_t; - static_assert(lim_f::is_specialized && lim_t::is_specialized, - "std::numeric_limits<> must be specialized for both types"); - static_assert(lim_f::is_integer && lim_t::is_integer, "Both types must be integers"); - static_assert(!lim_f::is_signed, "`From` must be unsigned"); - To native; - int sign_bit_pos = lim_f::digits - 1; - From sign_bit = From(1) << sign_bit_pos; - bool non_negative = !lim_t::is_signed || (twos_compl & sign_bit) == 0; - if (non_negative) { - // Non-negative value - native = To(twos_compl); - } - else { - // Negative value - native = To(-1 - To(From(-1) - twos_compl)); - } - return native; -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SAFE_INT_OPS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/scope_exit.hpp b/Lesson14/Pods/Realm/include/core/realm/util/scope_exit.hpp deleted file mode 100644 index 5410d19..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/scope_exit.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_SCOPE_EXIT_HPP -#define REALM_UTIL_SCOPE_EXIT_HPP - -#include -#include - -#include - -namespace realm { -namespace util { - -template -class ScopeExit { -public: - explicit ScopeExit(const H& handler) noexcept(std::is_nothrow_copy_constructible::value) - : m_handler(handler) - { - } - - explicit ScopeExit(H&& handler) noexcept(std::is_nothrow_move_constructible::value) - : m_handler(std::move(handler)) - { - } - - ScopeExit(ScopeExit&& se) noexcept(std::is_nothrow_move_constructible::value) - : m_handler(std::move(se.m_handler)) - { - se.m_handler = none; - } - - ~ScopeExit() noexcept - { - if (m_handler) - (*m_handler)(); - } - - static_assert(noexcept(std::declval()()), "Handler must be nothrow executable"); - static_assert(std::is_nothrow_destructible::value, "Handler must be nothrow destructible"); - -private: - util::Optional m_handler; -}; - -template -ScopeExit::type> make_scope_exit(H&& handler) noexcept( - noexcept(ScopeExit::type>(std::forward(handler)))) -{ - return ScopeExit::type>(std::forward(handler)); -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SCOPE_EXIT_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/serializer.hpp b/Lesson14/Pods/Realm/include/core/realm/util/serializer.hpp deleted file mode 100644 index 5f7fc03..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/serializer.hpp +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_SERIALIZER_HPP -#define REALM_UTIL_SERIALIZER_HPP - -#include -#include - -#include -#include -#include - -namespace realm { - -class BinaryData; -struct null; -struct RowIndex; -class StringData; -class Timestamp; -class LinkMap; - -namespace util { -namespace serializer { - - -// Definitions -template -std::string print_value(T value); - -template -std::string print_value(Optional value); - -const static std::string value_separator = "."; - -// Specializations declared here to be defined in the cpp file -template <> std::string print_value<>(BinaryData); -template <> std::string print_value<>(bool); -template <> std::string print_value<>(realm::null); -template <> std::string print_value<>(StringData); -template <> std::string print_value<>(realm::Timestamp); -template <> std::string print_value<>(realm::RowIndex); - -// General implementation for most types -template -std::string print_value(T value) -{ - std::stringstream ss; - ss << value; - return ss.str(); -} - -template -std::string print_value(Optional value) -{ - if (bool(value)) { - return print_value(*value); - } else { - return "NULL"; - } -} - -struct SerialisationState -{ - std::string describe_column(ConstTableRef table, size_t col_ndx); - std::string describe_columns(const LinkMap& link_map, size_t target_col_ndx); - std::string get_column_name(ConstTableRef table, size_t col_ndx); - std::string get_backlink_column_name(ConstTableRef from, size_t col_ndx); - std::string get_variable_name(ConstTableRef table); - std::vector subquery_prefix_list; -}; - -} // namespace serializer -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SERIALIZER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/shared_ptr.hpp b/Lesson14/Pods/Realm/include/core/realm/util/shared_ptr.hpp deleted file mode 100644 index 1a34701..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/shared_ptr.hpp +++ /dev/null @@ -1,131 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_SHARED_PTR_HPP -#define REALM_SHARED_PTR_HPP - -#include // size_t - -namespace realm { -namespace util { - -template -class SharedPtr { -public: - SharedPtr(T* p) - { - init(p); - } - - SharedPtr() - { - init(0); - } - - ~SharedPtr() - { - decref(); - } - - SharedPtr(const SharedPtr& o) - : m_ptr(o.m_ptr) - , m_count(o.m_count) - { - incref(); - } - - SharedPtr& operator=(const SharedPtr& o) - { - // if (m_ptr == o.m_ptr) - if (this == &o) - return *this; - decref(); - m_ptr = o.m_ptr; - m_count = o.m_count; - incref(); - return *this; - } - - T* operator->() const - { - return m_ptr; - } - - T& operator*() const - { - return *m_ptr; - } - - T* get() const - { - return m_ptr; - } - - bool operator==(const SharedPtr& o) const - { - return m_ptr == o.m_ptr; - } - - bool operator!=(const SharedPtr& o) const - { - return m_ptr != o.m_ptr; - } - - bool operator<(const SharedPtr& o) const - { - return m_ptr < o.m_ptr; - } - - size_t ref_count() const - { - return *m_count; - } - -private: - void init(T* p) - { - m_ptr = p; - try { - m_count = new size_t(1); - } - catch (...) { - delete p; - throw; - } - } - - void decref() - { - if (--(*m_count) == 0) { - delete m_ptr; - delete m_count; - } - } - - void incref() - { - ++(*m_count); - } - - T* m_ptr; - size_t* m_count; -}; -} -} - -#endif diff --git a/Lesson14/Pods/Realm/include/core/realm/util/signal_blocker.hpp b/Lesson14/Pods/Realm/include/core/realm/util/signal_blocker.hpp deleted file mode 100644 index bb1489b..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/signal_blocker.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_SIGNAL_BLOCKER_HPP -#define REALM_UTIL_SIGNAL_BLOCKER_HPP - -#include - -#include - - -namespace realm { -namespace util { - -/// \brief Block all signals from being delivered to the instantiating thread. -/// -/// On platforms that support POSIX signals, the constructor will set the signal -/// mask such that all signals are blocked from being delivered to the calling -/// thread, and the destructor will restore the signal mask to its original -/// value. -/// -/// This scheme assumes that it is always the same thread that constructs and -/// destroys a particular instance of SignalBlocker, and that, for a particular -/// thread, two SignalBlocker objects never overlap in time, and the signal mask -/// is never modified by other means while a SignalBlocker object exists. -class SignalBlocker { -public: - SignalBlocker() noexcept; - ~SignalBlocker() noexcept; - -private: -#ifndef _WIN32 - ::sigset_t m_orig_mask; -#endif -}; - - - -// Implementation - -inline SignalBlocker::SignalBlocker() noexcept -{ -#ifndef _WIN32 - ::sigset_t mask; - sigfillset(&mask); - int ret = ::pthread_sigmask(SIG_BLOCK, &mask, &m_orig_mask); - REALM_ASSERT(ret == 0); -#endif -} - -inline SignalBlocker::~SignalBlocker() noexcept -{ -#ifndef _WIN32 - int ret = ::pthread_sigmask(SIG_SETMASK, &m_orig_mask, nullptr); - REALM_ASSERT(ret == 0); -#endif -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SIGNAL_BLOCKER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/string_buffer.hpp b/Lesson14/Pods/Realm/include/core/realm/util/string_buffer.hpp deleted file mode 100644 index 71736bd..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/string_buffer.hpp +++ /dev/null @@ -1,209 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_STRING_BUFFER_HPP -#define REALM_UTIL_STRING_BUFFER_HPP - -#include -#include -#include - -#include -#include - -namespace realm { -namespace util { - - -// FIXME: In C++17, this can be replaced with std::string (since -// std::string::data() can return a mutable pointer in C++17). -template -class BasicStringBuffer { -public: - BasicStringBuffer() noexcept; - - std::string str() const; - - /// Returns the current size of the string in this buffer. This - /// size does not include the terminating zero. - size_t size() const noexcept; - - /// Gives read and write access to the bytes of this buffer. The - /// caller may read and write from *c_str() up to, but not - /// including, *(c_str()+size()). - char* data() noexcept; - - /// Gives read access to the bytes of this buffer. The caller may - /// read from *c_str() up to, but not including, - /// *(c_str()+size()). - const char* data() const noexcept; - - /// Guarantees that the returned string is zero terminated, that - /// is, *(c_str()+size()) is zero. The caller may read from - /// *c_str() up to and including *(c_str()+size()). - const char* c_str() const noexcept; - - void append(const std::string&); - - void append(const char* append_data, size_t append_size); - - /// Append a zero-terminated string to this buffer. - void append_c_str(const char* c_string); - - /// The specified size is understood as not including the - /// terminating zero. If the specified size is less than the - /// current size, then the string is truncated accordingly. If the - /// specified size is greater than the current size, then the - /// extra characters will have undefined values, however, there - /// will be a terminating zero at *(c_str()+size()), and the - /// original terminating zero will also be left in place such that - /// from the point of view of c_str(), the size of the string is - /// unchanged. - void resize(size_t new_size); - - /// The specified minimum capacity is understood as not including - /// the terminating zero. This operation does not change the size - /// of the string in the buffer as returned by size(). If the - /// specified capacity is less than the current capacity, this - /// operation has no effect. - void reserve(size_t min_capacity); - - /// Set size to zero. The capacity remains unchanged. - void clear() noexcept; - -private: - util::Buffer m_buffer; - size_t m_size; // Excluding the terminating zero - void reallocate(size_t min_capacity); -}; - -using StringBuffer = BasicStringBuffer; - - -// Implementation: - -template -BasicStringBuffer::BasicStringBuffer() noexcept - : m_size(0) -{ -} - -template -std::string BasicStringBuffer::str() const -{ - return std::string(m_buffer.data(), m_size); -} - -template -size_t BasicStringBuffer::size() const noexcept -{ - return m_size; -} - -template -char* BasicStringBuffer::data() noexcept -{ - return m_buffer.data(); -} - -template -const char* BasicStringBuffer::data() const noexcept -{ - return m_buffer.data(); -} - -template -const char* BasicStringBuffer::c_str() const noexcept -{ - static const char zero = 0; - const char* d = data(); - return d ? d : &zero; -} - -template -void BasicStringBuffer::append(const std::string& s) -{ - return append(s.data(), s.size()); -} - -template -void BasicStringBuffer::append_c_str(const char* c_string) -{ - append(c_string, std::strlen(c_string)); -} - -template -void BasicStringBuffer::reserve(size_t min_capacity) -{ - size_t capacity = m_buffer.size(); - if (capacity == 0 || capacity - 1 < min_capacity) - reallocate(min_capacity); -} - -template -void BasicStringBuffer::resize(size_t new_size) -{ - reserve(new_size); - // Note that even reserve(0) will attempt to allocate a - // buffer, so we can safely write the truncating zero at this - // time. - m_size = new_size; - m_buffer[new_size] = 0; -} - -template -void BasicStringBuffer::clear() noexcept -{ - if (m_buffer.size() == 0) - return; - m_size = 0; - m_buffer[0] = 0; -} - -template -void BasicStringBuffer::append(const char* append_data, size_t append_data_size) -{ - size_t new_size = m_size; - if (int_add_with_overflow_detect(new_size, append_data_size)) - throw util::BufferSizeOverflow(); - reserve(new_size); // Throws - realm::safe_copy_n(append_data, append_data_size, m_buffer.data() + m_size); - m_size = new_size; - m_buffer[new_size] = 0; // Add zero termination -} - - -template -void BasicStringBuffer::reallocate(size_t min_capacity) -{ - size_t min_capacity_2 = min_capacity; - // Make space for zero termination - if (int_add_with_overflow_detect(min_capacity_2, 1)) - throw util::BufferSizeOverflow(); - size_t new_capacity = m_buffer.size(); - if (int_multiply_with_overflow_detect(new_capacity, 2)) - new_capacity = std::numeric_limits::max(); // LCOV_EXCL_LINE - if (new_capacity < min_capacity_2) - new_capacity = min_capacity_2; - m_buffer.resize(new_capacity, 0, m_size, 0); // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_STRING_BUFFER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/string_view.hpp b/Lesson14/Pods/Realm/include/core/realm/util/string_view.hpp deleted file mode 100644 index 74fdcb6..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/string_view.hpp +++ /dev/null @@ -1,478 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_STRING_VIEW_HPP -#define REALM_UTIL_STRING_VIEW_HPP - -#include -#include -#include -#include -#include -#include -#include - -#include - - -namespace realm { -namespace util { - -template> class BasicStringView { -public: - using value_type = C; - using traits_type = T; - using pointer = C*; - using const_pointer = const C*; - using reference = C&; - using const_reference = const C&; - using iterator = const_pointer; - using const_iterator = const_pointer; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - - static constexpr size_type npos = size_type(-1); - - BasicStringView() noexcept; - BasicStringView(const std::basic_string&) noexcept; - BasicStringView(const char* data, size_type size) noexcept; - BasicStringView(const char* c_str) noexcept; - - explicit operator std::basic_string() const; - - const_iterator begin() const noexcept; - const_iterator end() const noexcept; - const_iterator cbegin() const noexcept; - const_iterator cend() const noexcept; - - const_reverse_iterator rbegin() const noexcept; - const_reverse_iterator rend() const noexcept; - const_reverse_iterator crbegin() const noexcept; - const_reverse_iterator crend() const noexcept; - - const_reference operator[](size_type i) const noexcept; - const_reference at(size_type i) const; - const_reference front() const noexcept; - const_reference back() const noexcept; - - const_pointer data() const noexcept; - size_type size() const noexcept; - bool empty() const noexcept; - - BasicStringView substr(size_type i = 0, size_type n = npos) const; - int compare(BasicStringView other) const noexcept; - size_type find(BasicStringView, size_type i = 0) const noexcept; - size_type find(C ch, size_type i = 0) const noexcept; - size_type find_first_of(BasicStringView, size_type i = 0) const noexcept; - size_type find_first_of(C ch, size_type i = 0) const noexcept; - size_type find_first_not_of(BasicStringView, size_type i = 0) const noexcept; - size_type find_first_not_of(C ch, size_type i = 0) const noexcept; - -private: - const char* m_data = nullptr; - std::size_t m_size = 0; -}; - -template bool operator==(BasicStringView, BasicStringView) noexcept; -template bool operator!=(BasicStringView, BasicStringView) noexcept; -template bool operator< (BasicStringView, BasicStringView) noexcept; -template bool operator> (BasicStringView, BasicStringView) noexcept; -template bool operator<=(BasicStringView, BasicStringView) noexcept; -template bool operator>=(BasicStringView, BasicStringView) noexcept; - -template -bool operator==(std::decay_t>, BasicStringView) noexcept; -template -bool operator!=(std::decay_t>, BasicStringView) noexcept; -template -bool operator< (std::decay_t>, BasicStringView) noexcept; -template -bool operator> (std::decay_t>, BasicStringView) noexcept; -template -bool operator<=(std::decay_t>, BasicStringView) noexcept; -template -bool operator>=(std::decay_t>, BasicStringView) noexcept; - -template -bool operator==(BasicStringView, std::decay_t>) noexcept; -template -bool operator!=(BasicStringView, std::decay_t>) noexcept; -template -bool operator< (BasicStringView, std::decay_t>) noexcept; -template -bool operator> (BasicStringView, std::decay_t>) noexcept; -template -bool operator<=(BasicStringView, std::decay_t>) noexcept; -template -bool operator>=(BasicStringView, std::decay_t>) noexcept; - - -template -std::basic_ostream& operator<<(std::basic_ostream&, BasicStringView); - - -using StringView = BasicStringView; - - - - - -// Implementation - -template -inline BasicStringView::BasicStringView() noexcept -{ -} - -template -inline BasicStringView::BasicStringView(const std::basic_string& str) noexcept : - m_data{str.data()}, - m_size{str.size()} -{ -} - -template -inline BasicStringView::BasicStringView(const char* data, size_type size) noexcept : - m_data{data}, - m_size{size} -{ -} - -template -inline BasicStringView::BasicStringView(const char* c_str) noexcept : - m_data{c_str}, - m_size{T::length(c_str)} -{ -} - -template -inline BasicStringView::operator std::basic_string() const -{ - return {m_data, m_size}; // Throws -} - -template -inline auto BasicStringView::begin() const noexcept -> const_iterator -{ - return m_data; -} - -template -inline auto BasicStringView::end() const noexcept -> const_iterator -{ - return m_data + m_size; -} - -template -inline auto BasicStringView::cbegin() const noexcept -> const_iterator -{ - return begin(); -} - -template -inline auto BasicStringView::cend() const noexcept -> const_iterator -{ - return end(); -} - -template -inline auto BasicStringView::rbegin() const noexcept -> const_reverse_iterator -{ - return const_reverse_iterator{end()}; -} - -template -inline auto BasicStringView::rend() const noexcept -> const_reverse_iterator -{ - return const_reverse_iterator{begin()}; -} - -template -inline auto BasicStringView::crbegin() const noexcept -> const_reverse_iterator -{ - return rbegin(); -} - -template -inline auto BasicStringView::crend() const noexcept -> const_reverse_iterator -{ - return rend(); -} - -template -inline auto BasicStringView::operator[](size_type i) const noexcept -> const_reference -{ - return m_data[i]; -} - -template -inline auto BasicStringView::at(size_type i) const -> const_reference -{ - if (REALM_LIKELY(i < m_size)) - return m_data[i]; - throw std::out_of_range("index"); -} - -template -inline auto BasicStringView::front() const noexcept -> const_reference -{ - return m_data[0]; -} - -template -inline auto BasicStringView::back() const noexcept -> const_reference -{ - return m_data[m_size - 1]; -} - -template -inline auto BasicStringView::data() const noexcept -> const_pointer -{ - return m_data; -} - -template -inline auto BasicStringView::size() const noexcept -> size_type -{ - return m_size; -} - -template -inline bool BasicStringView::empty() const noexcept -{ - return (size() == 0); -} - -template -inline BasicStringView BasicStringView::substr(size_type i, size_type n) const -{ - if (REALM_LIKELY(i <= m_size)) { - size_type m = std::min(n, m_size - i); - return BasicStringView{m_data + i, m}; - } - throw std::out_of_range("index"); -} - -template -inline int BasicStringView::compare(BasicStringView other) const noexcept -{ - size_type n = std::min(m_size, other.m_size); - int ret = T::compare(m_data, other.m_data, n); - if (REALM_LIKELY(ret != 0)) - return ret; - if (m_size < other.m_size) - return -1; - if (m_size > other.m_size) - return 1; - return 0; -} - -template -inline auto BasicStringView::find(BasicStringView v, size_type i) const noexcept -> - size_type -{ - if (REALM_LIKELY(!v.empty())) { - if (REALM_LIKELY(i < m_size)) { - const C* p = std::search(begin() + i, end(), v.begin(), v.end()); - if (p != end()) - return size_type(p - begin()); - } - return npos; - } - return i; -} - -template -inline auto BasicStringView::find(C ch, size_type i) const noexcept -> size_type -{ - if (REALM_LIKELY(i < m_size)) { - const C* p = std::find(begin() + i, end(), ch); - if (p != end()) - return size_type(p - begin()); - } - return npos; -} - -template -inline auto BasicStringView::find_first_of(BasicStringView v, - size_type i) const noexcept -> size_type -{ - for (size_type j = i; j < m_size; ++j) { - if (REALM_LIKELY(v.find(m_data[j]) == npos)) - continue; - return j; - } - return npos; -} - -template -inline auto BasicStringView::find_first_of(C ch, size_type i) const noexcept -> size_type -{ - for (size_type j = i; j < m_size; ++j) { - if (REALM_UNLIKELY(m_data[j] == ch)) - return j; - } - return npos; -} - -template -inline auto BasicStringView::find_first_not_of(BasicStringView v, - size_type i) const noexcept -> size_type -{ - for (size_type j = i; j < m_size; ++j) { - if (REALM_UNLIKELY(v.find(m_data[j]) == npos)) - return j; - } - return npos; -} - -template -inline auto BasicStringView::find_first_not_of(C ch, size_type i) const noexcept -> size_type -{ - for (size_type j = i; j < m_size; ++j) { - if (REALM_UNLIKELY(m_data[j] != ch)) - return j; - } - return npos; -} - -template -inline bool operator==(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) == 0); -} - -template -inline bool operator!=(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) != 0); -} - -template -inline bool operator<(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) < 0); -} - -template -inline bool operator>(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) > 0); -} - -template -inline bool operator<=(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) <= 0); -} - -template -inline bool operator>=(BasicStringView lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) >= 0); -} - -template -inline bool operator==(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) == 0); -} - -template -inline bool operator!=(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) != 0); -} - -template -inline bool operator<(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) < 0); -} - -template -inline bool operator>(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) > 0); -} - -template -inline bool operator<=(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) <= 0); -} - -template -inline bool operator>=(std::decay_t> lhs, BasicStringView rhs) noexcept -{ - return (lhs.compare(rhs) >= 0); -} - -template -inline bool operator==(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) == 0); -} - -template -inline bool operator!=(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) != 0); -} - -template -inline bool operator<(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) < 0); -} - -template -inline bool operator>(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) > 0); -} - -template -inline bool operator<=(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) <= 0); -} - -template -inline bool operator>=(BasicStringView lhs, std::decay_t> rhs) noexcept -{ - return (lhs.compare(rhs) >= 0); -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& out, - BasicStringView view) -{ - typename std::basic_ostream::sentry sentry{out}; - if (REALM_LIKELY(sentry)) - out.write(view.data(), view.size()); - return out; -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_STRING_VIEW_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/substitute.hpp b/Lesson14/Pods/Realm/include/core/realm/util/substitute.hpp deleted file mode 100644 index b551f31..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/substitute.hpp +++ /dev/null @@ -1,373 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_SUBSTITUTE_HPP -#define REALM_UTIL_SUBSTITUTE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - - -namespace realm { -namespace util { -namespace _private { - -class SubstituterBase { -protected: - template struct FindArg1; - template struct FindArg2; - static StderrLogger s_default_logger; -}; - -} // namespace _private - - -struct SubstituterConfig { - /// Allow parsing to be considered successful even when syntax errors are - /// detected. When enabled, logging will happen on `warn`, instead of - /// `error` level. - bool lenient = false; - - /// The logger to be used by default. If left unspecified, the default - /// logger is one that logs to STDERR. In any case, logging happens only - /// during parsing. - Logger* logger = nullptr; -}; - - -/// Perform variable substitutions in text. -/// -/// A variable reference generally has the form `@{}`, where `` is -/// the variable name. For example, if the variable name is `x`, then `@{x}` is -/// a reference to that variable. If the variable name consists of a single -/// letter, then a shorter form of reference, `@` is available, i.e., -/// since `x` is a single letter, `@x` is a reference to `x`. As a special rule, -/// `@@` is substituted by `@`. -/// -/// Example of use: -/// -/// struct CtxA { int y = 0; }; -/// struct CtxB { int x = 0; }; -/// using Subst = Substituter; -/// Subst subst; -/// subst["x"] = &CtxB::x; -/// subst["y"] = [](std::ostream& out, const CtxA& a, const CtxB&) { -/// out << a.y; -/// }; -/// Subst::Template templ; -/// if (subst.parse("<@x:@y>\n", templ)) { -/// CtxA a; -/// CtxB b; -/// for (int i = 0; i < 3; ++i) { -/// templ.expand(std::cout, a, b); -/// a.y += 1; -/// b.x += 2; -/// } -/// } -/// -/// This code should write -/// -/// <0:0> -/// <2:1> -/// <4:2> -/// -/// to STDOUT. -template class Substituter : private _private::SubstituterBase { -public: - using EvalFunc = void(std::ostream&, A&...); - class ProtoDef; - class Template; - - Substituter(SubstituterConfig = {}) noexcept; - - ProtoDef operator[](const char* name) noexcept; - - bool expand(StringView text, std::ostream&, A&&...) const; - - bool parse(StringView text, Template&) const; - bool parse(StringView text, Template&, Logger&) const; - -private: - using size_type = StringView::size_type; - struct Substitution; - - const bool m_lenient; - Logger& m_logger; - - using Variables = std::map>; - Variables m_variables; - - void define(const char* name, std::function); -}; - - - -template class Substituter::ProtoDef { -public: - template void operator=(T*); - template void operator=(T C::*); - void operator=(std::function); - -private: - Substituter& m_substituter; - const char* m_name; - - ProtoDef(Substituter& substituter, const char* name) noexcept; - - friend class Substituter; -}; - - - -template class Substituter::Template { -public: - /// Uses std::locale::classic(). - std::string expand(A&&...) const; - - void expand(std::ostream&, A...) const; - - bool refers_to(const char* name) const noexcept; - -private: - StringView m_text; - std::vector m_substitutions; - - friend class Substituter; -}; - - - - - -// Implementation - -namespace _private { - -template struct SubstituterBase::FindArg2 { - static const T& find(const A&, const B&... b) noexcept - { - return FindArg1::find(b...); - } -}; - -template -struct SubstituterBase::FindArg2 { - static const T& find(const A& a, const B&...) noexcept - { - return a; - } -}; - -template struct SubstituterBase::FindArg1 { - static const T& find(const A& a, const B&... b) noexcept - { - using P = typename std::remove_reference::type*; - return FindArg2::value, A, B...>::find(a, b...); - } -}; - -} // namespace _private - -template struct Substituter::Substitution { - size_type begin, end; - const typename Variables::value_type* var_def; -}; - -template inline Substituter::Substituter(SubstituterConfig config) noexcept : - m_lenient{config.lenient}, - m_logger{config.logger ? *config.logger : s_default_logger} -{ -} - -template inline auto Substituter::operator[](const char* name) noexcept -> ProtoDef -{ - return ProtoDef{*this, name}; -} - -template -inline bool Substituter::expand(StringView text, std::ostream& out, A&&... arg) const -{ - Template templ; - if (parse(text, templ)) { // Throws - templ.expand(out, std::forward(arg)...); // Throws - return true; - } - return false; -} - -template inline bool Substituter::parse(StringView text, Template& templ) const -{ - return parse(text, templ, m_logger); // Throws -} - -template -bool Substituter::parse(StringView text, Template& templ, Logger& logger) const -{ - bool error = false; - Logger::Level log_level = (m_lenient ? Logger::Level::warn : Logger::Level::error); - std::vector substitutions; - StringView var_name; - size_type curr = 0; - size_type end = text.size(); - for (;;) { - size_type i = text.find('@', curr); - if (i == StringView::npos) - break; - if (i + 1 == end) { - logger.log(log_level, "Unterminated `@` at end of text"); // Throws - error = true; - break; - } - char ch = text[i + 1]; - if (ch == '{') { - size_type j = text.find('}', i + 2); - if (j == StringView::npos) { - logger.log(log_level, "Unterminated `@{`"); // Throws - error = true; - curr = i + 2; - continue; - } - var_name = text.substr(i + 2, j - (i + 2)); - curr = j + 1; - } - else { - var_name = text.substr(i + 1, 1); // Throws - curr = i + 2; - } - const typename Variables::value_type* var_def = nullptr; - if (ch != '@') { - auto k = m_variables.find(var_name); - if (k == m_variables.end()) { - logger.log(log_level, "Undefined variable `%1` in substitution `%2`", var_name, - text.substr(i, curr - i)); // Throws - error = true; - continue; - } - var_def = &*k; - } - substitutions.push_back({i, curr, var_def}); // Throws - } - if (error && !m_lenient) - return false; - templ.m_text = text; - templ.m_substitutions = std::move(substitutions); - return true; -} - -template -inline void Substituter::define(const char* name, std::function func) -{ - auto p = m_variables.emplace(name, std::move(func)); // Throws - bool was_inserted = p.second; - if (!was_inserted) - throw std::runtime_error("Multiple definitions for same variable name"); -} - -template template inline void Substituter::ProtoDef::operator=(T* var) -{ - *this = [var](std::ostream& out, const A&...) { - out << *var; // Throws - }; -} - -template -template inline void Substituter::ProtoDef::operator=(T C::* var) -{ - *this = [var](std::ostream& out, const A&... arg) { - const C& obj = FindArg1::find(arg...); - out << obj.*var; // Throws - }; -} - -template -inline void Substituter::ProtoDef::operator=(std::function func) -{ - m_substituter.define(m_name, std::move(func)); // Throws -} - -template -inline Substituter::ProtoDef::ProtoDef(Substituter& substituter, const char* name) noexcept : - m_substituter{substituter}, - m_name{name} -{ -} - -template std::string Substituter::Template::expand(A&&... arg) const -{ - std::ostringstream out; - out.imbue(std::locale::classic()); - expand(out, std::forward(arg)...); // Throws - std::string str = std::move(out).str(); // Throws - return str; -} - -template void Substituter::Template::expand(std::ostream& out, A... arg) const -{ - std::ios_base::fmtflags flags = out.flags(); - try { - size_type curr = 0; - for (const Substitution& subst: m_substitutions) { - out << m_text.substr(curr, subst.begin - curr); // Throws - if (subst.var_def) { - const std::function& eval_func = subst.var_def->second; - eval_func(out, arg...); // Throws - out.flags(flags); - } - else { - out << "@"; // Throws - } - curr = subst.end; - } - out << m_text.substr(curr); // Throws - } - catch (...) { - out.flags(flags); - throw; - } -} - -template -inline bool Substituter::Template::refers_to(const char* name) const noexcept -{ - StringView name_2 = name; - for (const auto& subst: m_substitutions) { - if (subst.var_def) { - if (name_2 != subst.var_def->first) - continue; - return true; - } - } - return false; -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SUBSTITUTE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/system_process.hpp b/Lesson14/Pods/Realm/include/core/realm/util/system_process.hpp deleted file mode 100644 index c84addd..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/system_process.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_SYSTEM_PROCESS_HPP -#define REALM_UTIL_SYSTEM_PROCESS_HPP - -#include -#include -#include -#include - -#include - - -namespace realm { -namespace util { -namespace sys_proc { - -using Environment = std::map; - -/// This function is safe to call only when the caller can be sure that there -/// are no threads that modify the environment concurrently. -/// -/// When possible, call this function from the main thread before any other -/// threads are created, such as early in `main()`. -Environment copy_local_environment(); - - -struct ExitInfo { - /// If nonzero, the process was killed by a signal. The value is the - /// signal number. - int killed_by_signal = 0; - - /// Zero if the process was killed by a signal, otherwise this is the value - /// returned by the `main()` function, or passed to `exit()`. - /// - /// On a POSIX system, if an error occurs during ::execve(), that is, after - /// ::fork(), an exit status of 127 will be used (aligned with - /// ::posix_spawn()). - int status = 0; - - /// In some cases, ChildHandle::join() will set `signal_name` when it sets - /// `killed_by_signal` to a non-zero value. In those cases, `signal_name` is - /// set to point to a null-terminated string specifying the name of the - /// signal that killed the child process. - const char* signal_name = nullptr; - - /// Returns true if, and only if both `killed_by_signal` and `status` are - /// zero. - explicit operator bool() const noexcept; -}; - - -struct SpawnConfig { - /// When set to true, the child process will be able to use a - /// ParentDeathGuard to detect the destruction of the SystemProcess object - /// in the parent process, even when this happens implicitly due to abrupt - /// termination of the parent process. - bool parent_death_guard = false; - - /// If a logger is specified here, the child process will be able to - /// instantiate a ParentLogger object, and messages logged through that - /// ParentLogger object will be transported to the parent process and - /// submitted to the logger pointed to by `logger`. The specified logger is - /// guaranteed to only be accessed while ChildHandle::join() is executing, - /// and only by the thread that executes ChildHandle::join(). See - /// ParentLogger for further details. - Logger* logger = nullptr; -}; - - -class ChildHandle { -public: - /// Wait for the child process to exit. - /// - /// If a logger was passed to spawn() (SpawnConfig::logger), then this - /// function will also transport log messages from the child to the parent - /// process while waiting for the child process to exit. See ParentLogger - /// for details. - ExitInfo join(); - - ChildHandle(ChildHandle&&) noexcept; - ~ChildHandle() noexcept; - -private: - class Impl; - std::unique_ptr m_impl; - - ChildHandle(Impl*) noexcept; - - friend ChildHandle spawn(const std::string&, const std::vector&, - const Environment&, const SpawnConfig&); -}; - - -/// Returns true if, and only if the spawn() functions work on this platform. If -/// this function returns false, the spawn() functions will throw. -bool is_spawn_supported() noexcept; - - -//@{ -/// Spawn a child process. -ChildHandle spawn(const std::string& path, const std::vector& args = {}, - const Environment& = {}); -ChildHandle spawn(const std::string& path, const std::vector& args, - const Environment&, const SpawnConfig&); -//@} - - -/// Force a child process to terminate immediately if the parent process is -/// terminated, or if the parent process destroys the ChildHandle object -/// representing the child process. -/// -/// If a child process instantiates an object of this type, and keeps it alive, -/// and the child process was spawned with support for detection of parent -/// termination (SpawnConfig::parent_death_guard), then the child process will -/// be killed shortly after the parent destroys its ChildHandle object, even -/// when this happens implicitly due to abrupt termination of the parent -/// process. -/// -/// If a child process instantiates an object of this type, that object must be -/// instantiated by the main thread, and before any other thread is spawned in -/// the child process. -/// -/// In order for the guard to have the intended effect, it must be instantiated -/// immediately in the child process, and be kept alive for as long as the child -/// process is running. -class ParentDeathGuard { -public: - ParentDeathGuard(); - ~ParentDeathGuard() noexcept; - -private: - std::thread m_thread; - int m_stop_pipe_write = -1; -}; - - -/// A logger that can transport log messages from the child to the parent -/// process. -/// -/// If the parent process specifies a logger when spawning a child process -/// (SpawnConfig::logger), then that child process can instantiate a -/// ParentLogger object, and messages logged through it will be transported to -/// the parent process. While the parent process is executing -/// ChildHandle::join(), those messages will be written to the logger specified -/// by the parent process. -/// -/// If a child process instantiates an object of this type, that object must be -/// instantiated by the main thread, and before any other thread is spawned in -/// the child process. -/// -/// At most one ParentLogger object may be instantiated per child process. -/// -/// This logger is **not** thread-safe. -class ParentLogger : public RootLogger { -public: - ParentLogger(); - ~ParentLogger() noexcept; - -protected: - void do_log(Level, std::string) override final; - -private: - int m_pipe_write = -1; -}; - - - - -// Implementation - -inline ExitInfo::operator bool() const noexcept -{ - return (killed_by_signal == 0 && status == 0); -} - -inline ChildHandle spawn(const std::string& path, const std::vector& args, - const Environment& env) -{ - return spawn(path, args, env, SpawnConfig{}); // Throws -} - -} // namespace sys_proc -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_SYSTEM_PROCESS_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/terminate.hpp b/Lesson14/Pods/Realm/include/core/realm/util/terminate.hpp deleted file mode 100644 index 4e6034e..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/terminate.hpp +++ /dev/null @@ -1,59 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_TERMINATE_HPP -#define REALM_UTIL_TERMINATE_HPP - -#include - -#include -#include -#include - -#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__) - -namespace realm { -namespace util { - -REALM_NORETURN void terminate(const char* message, const char* file, long line, - std::initializer_list&& = {}) noexcept; -REALM_NORETURN void terminate_with_info(const char* message, const char* file, long line, - const char* interesting_names, - std::initializer_list&& = {}) noexcept; - -// LCOV_EXCL_START -template -REALM_NORETURN void terminate(const char* message, const char* file, long line, Ts... infos) noexcept -{ - static_assert(sizeof...(infos) == 2 || sizeof...(infos) == 4 || sizeof...(infos) == 6, - "Called realm::util::terminate() with wrong number of arguments"); - terminate(message, file, line, {Printable(infos)...}); -} - -template -REALM_NORETURN void terminate_with_info(const char* assert_message, int line, const char* file, - const char* interesting_names, Args&&... interesting_values) noexcept -{ - terminate_with_info(assert_message, file, line, interesting_names, {Printable(interesting_values)...}); -} -// LCOV_EXCL_STOP - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_TERMINATE_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/thread.hpp b/Lesson14/Pods/Realm/include/core/realm/util/thread.hpp deleted file mode 100644 index 8ca5e38..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/thread.hpp +++ /dev/null @@ -1,759 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_THREAD_HPP -#define REALM_UTIL_THREAD_HPP - -#include - -#ifdef _WIN32 -#include -#include // for windows non-interprocess condvars we use std::condition_variable -#include -#include // _getpid() -#else -#include -#endif - -// Use below line to enable a thread bug detection tool. Note: Will make program execution slower. -// #include <../test/pthread_test.hpp> - -#include -#include -#include - -#include -#include -#include -#include - -#include - -namespace realm { -namespace util { - - -/// A separate thread of execution. -/// -/// This class is a C++03 compatible reproduction of a subset of std::thread -/// from C++11 (when discounting Thread::start(), Thread::set_name(), and -/// Thread::get_name()). -class Thread { -public: - Thread(); - ~Thread() noexcept; - - template - explicit Thread(F func); - - // Disable copying. It is an error to copy this Thread class. - Thread(const Thread&) = delete; - Thread& operator=(const Thread&) = delete; - - Thread(Thread&&); - - /// This method is an extension of the API provided by - /// std::thread. This method exists because proper move semantics - /// is unavailable in C++03. If move semantics had been available, - /// calling `start(func)` would have been equivalent to `*this = - /// Thread(func)`. Please see std::thread::operator=() for - /// details. - template - void start(F func); - - bool joinable() noexcept; - - void join(); - - // If supported by the platform, set the name of the calling thread (mainly - // for debugging purposes). The name will be silently clamped to whatever - // limit the platform places on these names. Linux places a limit of 15 - // characters for these names. - static void set_name(const std::string&); - - // If supported by the platform, this function assigns the name of the - // calling thread to \a name, and returns true, otherwise it does nothing - // and returns false. - static bool get_name(std::string& name); - -private: - -#ifdef _WIN32 - std::thread m_std_thread; -#else - pthread_t m_id; -#endif - bool m_joinable; - typedef void* (*entry_func_type)(void*); - - void start(entry_func_type, void* arg); - - template - static void* entry_point(void*) noexcept; - - REALM_NORETURN static void create_failed(int); - REALM_NORETURN static void join_failed(int); -}; - - -/// Low-level mutual exclusion device. -class Mutex { -public: - Mutex(); - ~Mutex() noexcept; - - struct process_shared_tag { - }; - /// Initialize this mutex for use across multiple processes. When - /// constructed this way, the instance may be placed in memory - /// shared by multiple processes, as well as in a memory mapped - /// file. Such a mutex remains valid even after the constructing - /// process terminates. Deleting the instance (freeing the memory - /// or deleting the file) without first calling the destructor is - /// legal and will not cause any system resources to be leaked. - Mutex(process_shared_tag); - - // Disable copying. - Mutex(const Mutex&) = delete; - Mutex& operator=(const Mutex&) = delete; - - friend class LockGuard; - friend class UniqueLock; - friend class InterprocessCondVar; - - void lock() noexcept; - bool try_lock() noexcept; - void unlock() noexcept; - -protected: -#ifdef _WIN32 - // Used for non-process-shared mutex. We only know at runtime whether or not to use it, depending on if we call - // Mutex::Mutex(process_shared_tag) - CRITICAL_SECTION m_critical_section; -#else - pthread_mutex_t m_impl = PTHREAD_MUTEX_INITIALIZER; -#endif - - struct no_init_tag { - }; - Mutex(no_init_tag) - { - } - - void init_as_regular(); - void init_as_process_shared(bool robust_if_available); - - REALM_NORETURN static void init_failed(int); - REALM_NORETURN static void attr_init_failed(int); - REALM_NORETURN static void destroy_failed(int) noexcept; - REALM_NORETURN static void lock_failed(int) noexcept; - -private: - friend class CondVar; - friend class RobustMutex; -}; - - -/// A simple mutex ownership wrapper. -class LockGuard { -public: - LockGuard(Mutex&) noexcept; - ~LockGuard() noexcept; - -private: - Mutex& m_mutex; - friend class CondVar; -}; - - -/// See UniqueLock. -struct defer_lock_tag { -}; - -/// A general-purpose mutex ownership wrapper supporting deferred -/// locking as well as repeated unlocking and relocking. -class UniqueLock { -public: - UniqueLock(Mutex&) noexcept; - UniqueLock(Mutex&, defer_lock_tag) noexcept; - ~UniqueLock() noexcept; - - void lock() noexcept; - void unlock() noexcept; - bool holds_lock() noexcept; - -private: - Mutex* m_mutex; - bool m_is_locked; -}; - - -/// A robust version of a process-shared mutex. -/// -/// A robust mutex is one that detects whether a thread (or process) -/// has died while holding a lock on the mutex. -/// -/// When the present platform does not offer support for robust -/// mutexes, this mutex class behaves as a regular process-shared -/// mutex, which means that if a thread dies while holding a lock, any -/// future attempt at locking will block indefinitely. -class RobustMutex : private Mutex { -public: - RobustMutex(); - ~RobustMutex() noexcept; - - static bool is_robust_on_this_platform() noexcept; - - class NotRecoverable; - - /// \param recover_func If the present platform does not support - /// robust mutexes, this function is never called. Otherwise it is - /// called if, and only if a thread has died while holding a - /// lock. The purpose of the function is to reestablish a - /// consistent shared state. If it fails to do this by throwing an - /// exception, the mutex enters the 'unrecoverable' state where - /// any future attempt at locking it will fail and cause - /// NotRecoverable to be thrown. This function is advised to throw - /// NotRecoverable when it fails, but it may throw any exception. - /// - /// \throw NotRecoverable If thrown by the specified recover - /// function, or if the mutex has entered the 'unrecoverable' - /// state due to a different thread throwing from its recover - /// function. - template - void lock(Func recover_func); - - template - bool try_lock(Func recover_func); - - void unlock() noexcept; - - /// Low-level locking of robust mutex. - /// - /// If the present platform does not support robust mutexes, this - /// function always returns true. Otherwise it returns false if, - /// and only if a thread has died while holding a lock. - /// - /// \note Most application should never call this function - /// directly. It is called automatically when using the ordinary - /// lock() function. - /// - /// \throw NotRecoverable If this mutex has entered the "not - /// recoverable" state. It enters this state if - /// mark_as_consistent() is not called between a call to - /// robust_lock() that returns false and the corresponding call to - /// unlock(). - bool low_level_lock(); - - /// Low-level try-lock of robust mutex - /// - /// If the present platform does not support robust mutexes, this - /// function always returns 0 or 1. Otherwise it returns -1 if, - /// and only if a thread has died while holding a lock. - /// - /// Returns 1 if the lock is succesfully obtained. - /// Returns 0 if the lock is held by somebody else (not obtained) - /// Returns -1 if a thread has died while holding a lock. - /// - /// \note Most application should never call this function - /// directly. It is called automatically when using the ordinary - /// lock() function. - /// - /// \throw NotRecoverable If this mutex has entered the "not - /// recoverable" state. It enters this state if - /// mark_as_consistent() is not called between a call to - /// robust_lock() that returns false and the corresponding call to - /// unlock(). - int try_low_level_lock(); - - /// Pull this mutex out of the 'inconsistent' state. - /// - /// Must be called only after low_level_lock() has returned false. - /// - /// \note Most application should never call this function - /// directly. It is called automatically when using the ordinary - /// lock() function. - void mark_as_consistent() noexcept; - - /// Attempt to check if this mutex is a valid object. - /// - /// This attempts to trylock() the mutex, and if that fails returns false if - /// the return value indicates that the low-level mutex is invalid (which is - /// distinct from 'inconsistent'). Although pthread_mutex_trylock() may - /// return EINVAL if the argument is not an initialized mutex object, merely - /// attempting to check if an arbitrary blob of memory is a mutex object may - /// involve undefined behavior, so it is only safe to assume that this - /// function will run correctly when it is known that the mutex object is - /// valid. - bool is_valid() noexcept; - - friend class CondVar; -}; - -class RobustMutex::NotRecoverable : public std::exception { -public: - const char* what() const noexcept override - { - return "Failed to recover consistent state of shared memory"; - } -}; - - -/// A simple robust mutex ownership wrapper. -class RobustLockGuard { -public: - /// \param m the mutex to guard - /// \param func See RobustMutex::lock(). - template - RobustLockGuard(RobustMutex& m, TFunc func); - ~RobustLockGuard() noexcept; - -private: - RobustMutex& m_mutex; - friend class CondVar; -}; - - -/// Condition variable for use in synchronization monitors. -class CondVar { -public: - CondVar(); - ~CondVar() noexcept; - - struct process_shared_tag { - }; - - /// Initialize this condition variable for use across multiple - /// processes. When constructed this way, the instance may be - /// placed in memory shared by multimple processes, as well as in - /// a memory mapped file. Such a condition variable remains valid - /// even after the constructing process terminates. Deleting the - /// instance (freeing the memory or deleting the file) without - /// first calling the destructor is legal and will not cause any - /// system resources to be leaked. - CondVar(process_shared_tag); - - /// Wait for another thread to call notify() or notify_all(). - void wait(LockGuard& l) noexcept; - template - void wait(RobustMutex& m, Func recover_func, const struct timespec* tp = nullptr); - - /// If any threads are wating for this condition, wake up at least - /// one. - void notify() noexcept; - - /// Wake up every thread that is currently wating on this - /// condition. - void notify_all() noexcept; - -private: -#ifdef _WIN32 - CONDITION_VARIABLE m_condvar = CONDITION_VARIABLE_INIT; -#else - pthread_cond_t m_impl; -#endif - - REALM_NORETURN static void init_failed(int); - REALM_NORETURN static void attr_init_failed(int); - REALM_NORETURN static void destroy_failed(int) noexcept; - void handle_wait_error(int error); -}; - - -// Implementation: - -inline Thread::Thread() - : m_joinable(false) -{ -} - -template -inline Thread::Thread(F func) - : m_joinable(true) -{ - std::unique_ptr func2(new F(func)); // Throws - start(&Thread::entry_point, func2.get()); // Throws - func2.release(); -} - -inline Thread::Thread(Thread&& thread) -{ -#ifndef _WIN32 - m_id = thread.m_id; - m_joinable = thread.m_joinable; - thread.m_joinable = false; -#endif -} - -template -inline void Thread::start(F func) -{ - if (m_joinable) - std::terminate(); - std::unique_ptr func2(new F(func)); // Throws - start(&Thread::entry_point, func2.get()); // Throws - func2.release(); - m_joinable = true; -} - -inline Thread::~Thread() noexcept -{ - if (m_joinable) - REALM_TERMINATE("Destruction of joinable thread"); -} - -inline bool Thread::joinable() noexcept -{ - return m_joinable; -} - -inline void Thread::start(entry_func_type entry_func, void* arg) -{ -#ifdef _WIN32 - m_std_thread = std::thread(entry_func, arg); -#else - const pthread_attr_t* attr = nullptr; // Use default thread attributes - int r = pthread_create(&m_id, attr, entry_func, arg); - if (REALM_UNLIKELY(r != 0)) - create_failed(r); // Throws -#endif -} - -template -inline void* Thread::entry_point(void* cookie) noexcept -{ - std::unique_ptr func(static_cast(cookie)); - try { - (*func)(); - } - catch (...) { - std::terminate(); - } - return 0; -} - - -inline Mutex::Mutex() -{ - init_as_regular(); -} - -inline Mutex::Mutex(process_shared_tag) -{ - bool robust_if_available = false; - init_as_process_shared(robust_if_available); -} - -inline Mutex::~Mutex() noexcept -{ -#ifndef _WIN32 - int r = pthread_mutex_destroy(&m_impl); - if (REALM_UNLIKELY(r != 0)) - destroy_failed(r); -#else - DeleteCriticalSection(&m_critical_section); -#endif -} - -inline void Mutex::init_as_regular() -{ -#ifndef _WIN32 - int r = pthread_mutex_init(&m_impl, 0); - if (REALM_UNLIKELY(r != 0)) - init_failed(r); -#else - InitializeCriticalSection(&m_critical_section); -#endif -} - -inline void Mutex::lock() noexcept -{ -#ifdef _WIN32 - EnterCriticalSection(&m_critical_section); -#else - int r = pthread_mutex_lock(&m_impl); - if (REALM_LIKELY(r == 0)) - return; - lock_failed(r); -#endif -} - -inline bool Mutex::try_lock() noexcept -{ -#ifdef _WIN32 - return TryEnterCriticalSection(&m_critical_section); -#else - int r = pthread_mutex_trylock(&m_impl); - if (r == EBUSY) { - return false; - } - else if (r == 0) { - return true; - } - lock_failed(r); -#endif -} - -inline void Mutex::unlock() noexcept -{ -#ifdef _WIN32 - LeaveCriticalSection(&m_critical_section); -#else - int r = pthread_mutex_unlock(&m_impl); - REALM_ASSERT(r == 0); -#endif -} - - -inline LockGuard::LockGuard(Mutex& m) noexcept - : m_mutex(m) -{ - m_mutex.lock(); -} - -inline LockGuard::~LockGuard() noexcept -{ - m_mutex.unlock(); -} - - -inline UniqueLock::UniqueLock(Mutex& m) noexcept - : m_mutex(&m) -{ - m_mutex->lock(); - m_is_locked = true; -} - -inline UniqueLock::UniqueLock(Mutex& m, defer_lock_tag) noexcept - : m_mutex(&m) -{ - m_is_locked = false; -} - -inline UniqueLock::~UniqueLock() noexcept -{ - if (m_is_locked) - m_mutex->unlock(); -} - -inline bool UniqueLock::holds_lock() noexcept -{ - return m_is_locked; -} - -inline void UniqueLock::lock() noexcept -{ - m_mutex->lock(); - m_is_locked = true; -} - -inline void UniqueLock::unlock() noexcept -{ - m_mutex->unlock(); - m_is_locked = false; -} - -template -inline RobustLockGuard::RobustLockGuard(RobustMutex& m, TFunc func) - : m_mutex(m) -{ - m_mutex.lock(func); -} - -inline RobustLockGuard::~RobustLockGuard() noexcept -{ - m_mutex.unlock(); -} - - -inline RobustMutex::RobustMutex() - : Mutex(no_init_tag()) -{ - bool robust_if_available = true; - init_as_process_shared(robust_if_available); -} - -inline RobustMutex::~RobustMutex() noexcept -{ -} - -template -inline void RobustMutex::lock(Func recover_func) -{ - bool no_thread_has_died = low_level_lock(); // Throws - if (REALM_LIKELY(no_thread_has_died)) - return; - try { - recover_func(); // Throws - mark_as_consistent(); - // If we get this far, the protected memory has been - // brought back into a consistent state, and the mutex has - // been notified about this. This means that we can safely - // enter the applications critical section. - } - catch (...) { - // Unlocking without first calling mark_as_consistent() - // means that the mutex enters the "not recoverable" - // state, which will cause all future attempts at locking - // to fail. - unlock(); - throw; - } -} - -template -inline bool RobustMutex::try_lock(Func recover_func) -{ - int lock_result = try_low_level_lock(); // Throws - if (lock_result == 0) return false; - bool no_thread_has_died = lock_result == 1; - if (REALM_LIKELY(no_thread_has_died)) - return true; - try { - recover_func(); // Throws - mark_as_consistent(); - // If we get this far, the protected memory has been - // brought back into a consistent state, and the mutex has - // been notified aboit this. This means that we can safely - // enter the applications critical section. - } - catch (...) { - // Unlocking without first calling mark_as_consistent() - // means that the mutex enters the "not recoverable" - // state, which will cause all future attempts at locking - // to fail. - unlock(); - throw; - } - return true; -} - -inline void RobustMutex::unlock() noexcept -{ - Mutex::unlock(); -} - - -inline CondVar::CondVar() -{ -#ifndef _WIN32 - int r = pthread_cond_init(&m_impl, 0); - if (REALM_UNLIKELY(r != 0)) - init_failed(r); -#endif -} - -inline CondVar::~CondVar() noexcept -{ -#ifndef _WIN32 - int r = pthread_cond_destroy(&m_impl); - if (REALM_UNLIKELY(r != 0)) - destroy_failed(r); -#endif -} - -inline void CondVar::wait(LockGuard& l) noexcept -{ -#ifdef _WIN32 - SleepConditionVariableCS(&m_condvar, &l.m_mutex.m_critical_section, INFINITE); -#else - int r = pthread_cond_wait(&m_impl, &l.m_mutex.m_impl); - if (REALM_UNLIKELY(r != 0)) - REALM_TERMINATE("pthread_cond_wait() failed"); -#endif -} - -template -inline void CondVar::wait(RobustMutex& m, Func recover_func, const struct timespec* tp) -{ - int r; - - if (!tp) { -#ifdef _WIN32 - if (!SleepConditionVariableCS(&m_condvar, &m.m_critical_section, INFINITE)) - r = GetLastError(); - else - r = 0; -#else - r = pthread_cond_wait(&m_impl, &m.m_impl); -#endif - } - else { -#ifdef _WIN32 - if (!SleepConditionVariableCS(&m_condvar, &m.m_critical_section, tp->tv_sec / 1000)) { - r = GetLastError(); - if (r == ERROR_TIMEOUT) - return; - } else { - r = 0 - } -#else - r = pthread_cond_timedwait(&m_impl, &m.m_impl, tp); - if (r == ETIMEDOUT) - return; -#endif - } - - if (REALM_LIKELY(r == 0)) - return; - - handle_wait_error(r); - - try { - recover_func(); // Throws - m.mark_as_consistent(); - // If we get this far, the protected memory has been - // brought back into a consistent state, and the mutex has - // been notified aboit this. This means that we can safely - // enter the applications critical section. - } - catch (...) { - // Unlocking without first calling mark_as_consistent() - // means that the mutex enters the "not recoverable" - // state, which will cause all future attempts at locking - // to fail. - m.unlock(); - throw; - } -} - -inline void CondVar::notify() noexcept -{ -#ifdef _WIN32 - WakeConditionVariable(&m_condvar); -#else - int r = pthread_cond_signal(&m_impl); - REALM_ASSERT(r == 0); -#endif -} - -inline void CondVar::notify_all() noexcept -{ -#ifdef _WIN32 - WakeAllConditionVariable(&m_condvar); -#else - int r = pthread_cond_broadcast(&m_impl); - REALM_ASSERT(r == 0); -#endif -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_THREAD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp b/Lesson14/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp deleted file mode 100644 index b779e5a..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/thread_exec_guard.hpp +++ /dev/null @@ -1,334 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2015] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ -#ifndef REALM_UTIL_THREAD_EXEC_GUARD_HPP -#define REALM_UTIL_THREAD_EXEC_GUARD_HPP - -#include -#include -#include - -#include -#include - - -namespace realm { -namespace util { - -/// Execute a `R::run()` using a managed thread. -/// -/// \tparam R The type of the runnable object. This type must satisfy the -/// requirements of the Runnable concept. See ThreadExecGuardWithParent. -template class ThreadExecGuard { -public: - explicit ThreadExecGuard(R& runnable); - - ThreadExecGuard(ThreadExecGuard&&) = default; - - /// If start() or start_with_signals_blocked() was successfully executed, - /// and stop_and_rethrow() has not been called, call `R::stop()`, and then - /// wait for the thread to terminate (join). - ~ThreadExecGuard() noexcept = default; - - // @{ - /// Launch a thread and make it execute `R::run()` of the associated - /// "runnable" object. - /// - /// At most one of these functions are allowed to be called on a particular - /// guard object, and it must only be called once. - void start(); - void start(const std::string& thread_name); - void start_with_signals_blocked(); - void start_with_signals_blocked(const std::string& thread_name); - // @} - - /// If start() or start_with_signals_blocked() was successfully executed, - /// call `R::stop()`, wait for the thread to terminate (join), and then, if - /// an exception was thrown by `R::run()`, rethrow it. - void stop_and_rethrow(); - -private: - struct State { - R& runnable; - util::Thread thread; - std::exception_ptr exception; - State(R&) noexcept; - ~State() noexcept; - void start(const std::string* thread_name); - void stop_and_rethrow(); - }; - - std::unique_ptr m_state; -}; - - -/// Execute a `R::run()` using a managed thread. -/// -/// \tparam R The type of the runnable object. This type must satisfy the -/// requirements of the Runnable concept. See below. -/// -/// \tparam P The type of the object representing the parent thread. This type -/// must satisfy the requirements of the Stoppable concept. See below. -/// -/// A type satisfies the requirements of the *Stoppable* concept, if -/// - it has a nonthrowing member function named `stop()`, and -/// - `stop()` is thread-safe, and -/// - `stop()` is idempotent (can be called multiple times). -/// -/// A type satisfies the requirements of the *Runnable* concept, if -/// - it satisfies the requirements of the Stoppable concept, and -/// - it has a member function named `run()`, and -/// - `run()` will stop executing within a reasonable amount of time after -/// `stop()` has been called. -/// -template class ThreadExecGuardWithParent { -public: - explicit ThreadExecGuardWithParent(R& runnable, P& parent); - - ThreadExecGuardWithParent(ThreadExecGuardWithParent&&) = default; - - /// If start() or start_with_signals_blocked() was successfully executed, - /// and stop_and_rethrow() has not been called, call `R::stop()`, and then - /// wait for the thread to terminate (join). - ~ThreadExecGuardWithParent() noexcept = default; - - // @{ - /// Launch a thread and make it execute `R::run()` of the associated - /// "runnable" object. - /// - /// If `R::run()` throws, call `P::stop()` on the specified parent. - /// - /// At most one of these functions are allowed to be called on a particular - /// guard object, and it must only be called once. - void start(); - void start(const std::string& thread_name); - void start_with_signals_blocked(); - void start_with_signals_blocked(const std::string& thread_name); - // @} - - /// If start() or start_with_signals_blocked() was successfully executed, - /// call `R::stop()`, wait for the thread to terminate (join), and then, if - /// an exception was thrown by `R::run()`, rethrow it. - void stop_and_rethrow(); - -private: - struct State { - R& runnable; - P& parent; - util::Thread thread; - std::exception_ptr exception; - State(R&, P&) noexcept; - ~State() noexcept; - void start(const std::string* thread_name); - void stop_and_rethrow(); - }; - - std::unique_ptr m_state; -}; - - -template ThreadExecGuard make_thread_exec_guard(R& runnable); - -template -ThreadExecGuardWithParent make_thread_exec_guard(R& runnable, P& parent); - - - - -// Implementation - -template inline ThreadExecGuard::ThreadExecGuard(R& runnable) : - m_state{std::make_unique(runnable)} // Throws -{ -} - -template inline void ThreadExecGuard::start() -{ - const std::string* thread_name = nullptr; - m_state->start(thread_name); // Throws -} - -template inline void ThreadExecGuard::start(const std::string& thread_name) -{ - m_state->start(&thread_name); // Throws -} - -template inline void ThreadExecGuard::start_with_signals_blocked() -{ - SignalBlocker sb; - const std::string* thread_name = nullptr; - m_state->start(thread_name); // Throws -} - -template -inline void ThreadExecGuard::start_with_signals_blocked(const std::string& thread_name) -{ - SignalBlocker sb; - m_state->start(&thread_name); // Throws -} - -template inline void ThreadExecGuard::stop_and_rethrow() -{ - m_state->stop_and_rethrow(); // Throws -} - -template inline ThreadExecGuard::State::State(R& r) noexcept : - runnable{r} -{ -} - -template inline ThreadExecGuard::State::~State() noexcept -{ - if (thread.joinable()) { - runnable.stop(); - thread.join(); - } -} - -template inline void ThreadExecGuard::State::start(const std::string* thread_name) -{ - bool set_thread_name = false; - std::string thread_name_2; - if (thread_name) { - set_thread_name = true; - thread_name_2 = *thread_name; // Throws (copy) - } - auto run = [this, set_thread_name, thread_name=std::move(thread_name_2)]() noexcept { - try { - if (set_thread_name) - util::Thread::set_name(thread_name); // Throws - runnable.run(); // Throws - } - catch (...) { - exception = std::current_exception(); - } - }; - thread.start(std::move(run)); // Throws -} - -template inline void ThreadExecGuard::State::stop_and_rethrow() -{ - if (thread.joinable()) { - runnable.stop(); - thread.join(); - if (exception) - std::rethrow_exception(exception); // Throws - } -} - -template -inline ThreadExecGuardWithParent::ThreadExecGuardWithParent(R& runnable, P& parent) : - m_state{std::make_unique(runnable, parent)} // Throws -{ -} - -template inline void ThreadExecGuardWithParent::start() -{ - const std::string* thread_name = nullptr; - m_state->start(thread_name); // Throws -} - -template -inline void ThreadExecGuardWithParent::start(const std::string& thread_name) -{ - m_state->start(&thread_name); // Throws -} - -template inline void ThreadExecGuardWithParent::start_with_signals_blocked() -{ - SignalBlocker sb; - const std::string* thread_name = nullptr; - m_state->start(thread_name); // Throws -} - -template -inline void ThreadExecGuardWithParent::start_with_signals_blocked(const std::string& thread_name) -{ - SignalBlocker sb; - m_state->start(&thread_name); // Throws -} - -template inline void ThreadExecGuardWithParent::stop_and_rethrow() -{ - m_state->stop_and_rethrow(); // Throws -} - -template -inline ThreadExecGuardWithParent::State::State(R& r, P& p) noexcept : - runnable{r}, - parent{p} -{ -} - -template inline ThreadExecGuardWithParent::State::~State() noexcept -{ - if (thread.joinable()) { - runnable.stop(); - thread.join(); - } -} - -template -inline void ThreadExecGuardWithParent::State::start(const std::string* thread_name) -{ - bool set_thread_name = false; - std::string thread_name_2; - if (thread_name) { - set_thread_name = true; - thread_name_2 = *thread_name; // Throws (copy) - } - auto run = [this, set_thread_name, thread_name=std::move(thread_name_2)]() noexcept { - try { - if (set_thread_name) - util::Thread::set_name(thread_name); // Throws - runnable.run(); // Throws - } - catch (...) { - exception = std::current_exception(); - parent.stop(); - } - }; - thread.start(std::move(run)); // Throws -} - -template inline void ThreadExecGuardWithParent::State::stop_and_rethrow() -{ - if (thread.joinable()) { - runnable.stop(); - thread.join(); - if (exception) - std::rethrow_exception(exception); // Throws - } -} - -template inline ThreadExecGuard make_thread_exec_guard(R& runnable) -{ - return ThreadExecGuard{runnable}; // Throws -} - -template -inline ThreadExecGuardWithParent make_thread_exec_guard(R& runnable, P& parent) -{ - return ThreadExecGuardWithParent{runnable, parent}; // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_THREAD_EXEC_GUARD_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/time.hpp b/Lesson14/Pods/Realm/include/core/realm/util/time.hpp deleted file mode 100644 index 75d9861..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/time.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_TIME_HPP -#define REALM_UTIL_TIME_HPP - -#include -#include -#include -#include -#include -#include - - -namespace realm { -namespace util { - -/// Thread safe version of std::localtime(). Uses localtime_r() on POSIX. -std::tm localtime(std::time_t); - -/// Thread safe version of std::gmtime(). Uses gmtime_r() on POSIX. -std::tm gmtime(std::time_t); - -/// Similar to std::put_time() from . See std::put_time() for -/// information about the format string. This function is provided because -/// std::put_time() is unavailable in GCC 4. This function is thread safe. -/// -/// The default format is ISO 8601 date and time. -template -void put_time(std::basic_ostream&, const std::tm&, const C* format = "%FT%T%z"); - -// @{ -/// These functions combine localtime() or gmtime() with put_time() and -/// std::ostringstream. For detals on the format string, see -/// std::put_time(). These function are thread safe. -std::string format_local_time(std::time_t, const char* format = "%FT%T%z"); -std::string format_utc_time(std::time_t, const char* format = "%FT%T%z"); -// @} - -/// The local time since the epoch in microseconds. -/// -/// FIXME: This function has nothing to do with local time. -double local_time_microseconds(); - - - - -// Implementation - -template -inline void put_time(std::basic_ostream& out, const std::tm& tm, const C* format) -{ - const auto& facet = std::use_facet>(out.getloc()); // Throws - facet.put(std::ostreambuf_iterator(out), out, ' ', &tm, - format, format + T::length(format)); // Throws -} - -inline std::string format_local_time(std::time_t time, const char* format) -{ - std::tm tm = util::localtime(time); - std::ostringstream out; - util::put_time(out, tm, format); // Throws - return out.str(); // Throws -} - -inline std::string format_utc_time(std::time_t time, const char* format) -{ - std::tm tm = util::gmtime(time); - std::ostringstream out; - util::put_time(out, tm, format); // Throws - return out.str(); // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_TIME_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp b/Lesson14/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp deleted file mode 100644 index 47e4ce3..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/timestamp_formatter.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_TIMESTAMP_FORMATTER_HPP -#define REALM_UTIL_TIMESTAMP_FORMATTER_HPP - -#include -#include -#include -#include - -#include -#include -#include -#include - - -namespace realm { -namespace util { - -class TimestampFormatter { -public: - using char_type = char; - using string_view_type = util::BasicStringView; - - enum class Precision { seconds, milliseconds, microseconds, nanoseconds }; - - /// Default configuration for corresponds to local time in ISO 8601 date and - /// time format. - struct Config { - Config() {} - - bool utc_time = false; - - Precision precision = Precision::seconds; - - /// The format of the timestamp as understood by std::put_time(), except - /// that the first occurrence of `%S` (also taking into account the `%S` - /// that is an implicit part of `%T`) is expanded to `SS.fff` if \ref - /// precision is Precision::milliseconds, or to `SS.ffffff` if \ref - /// precision is Precision::microseconds, or to `SS.fffffffff` if \ref - /// precision is Precision::nanoseconds, where `SS` is what `%S` expands - /// to conventionally. - const char* format = "%FT%T%z"; - }; - - TimestampFormatter(Config = {}); - - // FIXME: Use std::timespec in C++17. - string_view_type format(std::time_t time, long nanoseconds); - - template string_view_type format(std::chrono::time_point); - -private: - using memory_output_stream_type = util::MemoryOutputStream; - using format_segments_type = std::pair; - - const bool m_utc_time; - const Precision m_precision; - const format_segments_type m_format_segments; - char_type m_buffer[64]; - memory_output_stream_type m_out; - - static format_segments_type make_format_segments(const Config&); -}; - - - - - -// Implementation - -template -inline auto TimestampFormatter::format(std::chrono::time_point time) -> string_view_type -{ - using clock_type = B; - using time_point_type = std::chrono::time_point; - std::time_t time_2 = clock_type::to_time_t(time); - time_point_type time_3 = clock_type::from_time_t(time_2); - if (REALM_UNLIKELY(time_3 > time)) { - --time_2; - time_3 = clock_type::from_time_t(time_2); - } - long nanoseconds = - int(std::chrono::duration_cast(time - time_3).count()); - REALM_ASSERT(nanoseconds >= 0 && nanoseconds < 1000000000); - return format(time_2, nanoseconds); // Throws -} - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_TIMESTAMP_FORMATTER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/timestamp_logger.hpp b/Lesson14/Pods/Realm/include/core/realm/util/timestamp_logger.hpp deleted file mode 100644 index a9789a5..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/timestamp_logger.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/************************************************************************* - * - * REALM CONFIDENTIAL - * __________________ - * - * [2011] - [2016] Realm Inc - * All Rights Reserved. - * - * NOTICE: All information contained herein is, and remains - * the property of Realm Incorporated and its suppliers, - * if any. The intellectual and technical concepts contained - * herein are proprietary to Realm Incorporated - * and its suppliers and may be covered by U.S. and Foreign Patents, - * patents in process, and are protected by trade secret or copyright law. - * Dissemination of this information or reproduction of this material - * is strictly forbidden unless prior written permission is obtained - * from Realm Incorporated. - * - **************************************************************************/ - -#ifndef REALM_UTIL_TIMESTAMP_LOGGER_HPP -#define REALM_UTIL_TIMESTAMP_LOGGER_HPP - -#include -#include - - -namespace realm { -namespace util { - -class TimestampStderrLogger : public RootLogger { -public: - using Precision = TimestampFormatter::Precision; - using Config = TimestampFormatter::Config; - - explicit TimestampStderrLogger(Config = {}); - -protected: - void do_log(Logger::Level, std::string message) override; - -private: - TimestampFormatter m_formatter; -}; - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_TIMESTAMP_LOGGER_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/to_string.hpp b/Lesson14/Pods/Realm/include/core/realm/util/to_string.hpp deleted file mode 100644 index c3fac65..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/to_string.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_TO_STRING_HPP -#define REALM_UTIL_TO_STRING_HPP - -#include -#include - -namespace realm { -namespace util { - -class Printable { -public: - Printable(bool value) - : m_type(Type::Bool) - , m_uint(value) - { - } - Printable(unsigned char value) - : m_type(Type::Uint) - , m_uint(value) - { - } - Printable(unsigned int value) - : m_type(Type::Uint) - , m_uint(value) - { - } - Printable(unsigned long value) - : m_type(Type::Uint) - , m_uint(value) - { - } - Printable(unsigned long long value) - : m_type(Type::Uint) - , m_uint(value) - { - } - Printable(char value) - : m_type(Type::Int) - , m_int(value) - { - } - Printable(int value) - : m_type(Type::Int) - , m_int(value) - { - } - Printable(long value) - : m_type(Type::Int) - , m_int(value) - { - } - Printable(long long value) - : m_type(Type::Int) - , m_int(value) - { - } - Printable(const char* value) - : m_type(Type::String) - , m_string(value) - { - } - Printable(std::string const& value) - : m_type(Type::String) - , m_string(value.c_str()) - { - } - - - void print(std::ostream& out, bool quote) const; - std::string str() const; - - static void print_all(std::ostream& out, const std::initializer_list& values, bool quote); - -private: - enum class Type { - Bool, - Int, - Uint, - String, - } m_type; - - union { - uintmax_t m_uint; - intmax_t m_int; - const char* m_string; - }; -}; - - -template -std::string to_string(const T& v) -{ - return Printable(v).str(); -} - -std::string format(const char* fmt, std::initializer_list); - -template -std::string format(const char* fmt, Args&&... args) -{ - return format(fmt, {Printable(args)...}); -} - - -} // namespace util -} // namespace realm - -#endif // REALM_UTIL_TO_STRING_HPP diff --git a/Lesson14/Pods/Realm/include/core/realm/util/type_list.hpp b/Lesson14/Pods/Realm/include/core/realm/util/type_list.hpp deleted file mode 100644 index da847c7..0000000 --- a/Lesson14/Pods/Realm/include/core/realm/util/type_list.hpp +++ /dev/null @@ -1,244 +0,0 @@ -/************************************************************************* - * - * Copyright 2016 Realm Inc. - * - * 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 REALM_UTIL_TYPE_LIST_HPP -#define REALM_UTIL_TYPE_LIST_HPP - -namespace realm { -namespace util { - - -/// The 'cons' operator for building lists of types. -/// -/// \tparam H The head of the list, that is, the first type in the -/// list. -/// -/// \tparam T The tail of the list, that is, the list of types -/// following the head. It is 'void' if nothing follows the head, -/// otherwise it matches TypeCons. -/// -/// Note that 'void' is interpreted as a zero-length list. -template -struct TypeCons { - typedef H head; - typedef T tail; -}; - - -/// Append a type the the end of a type list. The resulting type list -/// is available as TypeAppend::type. -/// -/// \tparam List A list of types constructed using TypeCons<>. Note -/// that 'void' is interpreted as a zero-length list. -/// -/// \tparam T The new type to be appended. -template -struct TypeAppend { - typedef TypeCons::type> type; -}; -/// Base case for empty type list. -template -struct TypeAppend { - typedef TypeCons type; -}; - - -/// Get an element from the specified list of types. The result is -/// available as TypeAt::type. -/// -/// \tparam List A list of types constructed using TypeCons<>. Note -/// that 'void' is interpreted as a zero-length list. -/// -/// \tparam i The index of the list element to get. -template -struct TypeAt { - typedef typename TypeAt::type type; -}; -/// Base case for empty type list. -template -struct TypeAt { - typedef typename List::head type; -}; - - -/// Count the number of elements in the specified list of types. The -/// result is available as TypeCount::value. -/// -/// \tparam List The list of types, constructed using TypeCons<>. Note -/// that 'void' is interpreted as a zero-length list. -template -struct TypeCount { - static const int value = 1 + TypeCount::value; -}; -/// Base case for empty type list. -template <> -struct TypeCount { - static const int value = 0; -}; - - -/// Find the first type in the specified list that satisfies the -/// specified predicate. -/// -/// \tparam List The list of types, constructed using TypeCons<>. Note -/// that 'void' is interpreted as a zero-length list. -/// -/// \tparam Pred Must be such that `Pred::%value` is true if, and -/// only if the predicate is satisfied for `T`. -template class Pred> -struct FindType { -private: - typedef typename List::head type_1; - typedef typename FindType::type type_2; - -public: - typedef typename std::conditional::value, type_1, type_2>::type type; -}; -/// Base case for empty type list. -template